New directory structure. Files have been moved to the new destination locations.
Change-Id: I00077fccfdbe466be736696287bad5598210c7a9
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "combined-update-render-controller.h"
-
-// EXTERNAL INCLUDES
-#include <errno.h>
-#include <dali/integration-api/platform-abstraction.h>
-
-// INTERNAL INCLUDES
-#include <trigger-event-factory.h>
-#include <base/combined-update-render/combined-update-render-controller-debug.h>
-#include <base/environment-options.h>
-#include <base/time-service.h>
-#include <base/interfaces/adaptor-internal-services.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int CREATED_THREAD_COUNT = 1u;
-
-const int CONTINUOUS = -1;
-const int ONCE = 1;
-
-const unsigned int TRUE = 1u;
-const unsigned int FALSE = 0u;
-
-const unsigned int MILLISECONDS_PER_SECOND( 1e+3 );
-const float NANOSECONDS_TO_SECOND( 1e-9f );
-const unsigned int NANOSECONDS_PER_SECOND( 1e+9 );
-const unsigned int NANOSECONDS_PER_MILLISECOND( 1e+6 );
-
-// The following values will get calculated at compile time
-const float DEFAULT_FRAME_DURATION_IN_SECONDS( 1.0f / 60.0f );
-const uint64_t DEFAULT_FRAME_DURATION_IN_MILLISECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * MILLISECONDS_PER_SECOND );
-const uint64_t DEFAULT_FRAME_DURATION_IN_NANOSECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * NANOSECONDS_PER_SECOND );
-
-/**
- * Handles the use case when an update-request is received JUST before we process a sleep-request. If we did not have an update-request count then
- * there is a danger that, on the event-thread we could have:
- * 1) An update-request where we do nothing as Update/Render thread still running.
- * 2) Quickly followed by a sleep-request being handled where we pause the Update/Render Thread (even though we have an update to process).
- *
- * Using a counter means we increment the counter on an update-request, and decrement it on a sleep-request. This handles the above scenario because:
- * 1) MAIN THREAD: Update Request: COUNTER = 1
- * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
- * 3) MAIN THREAD: Update Request: COUNTER = 2
- * 4) MAIN THREAD: Sleep Request: COUNTER = 1 -> We do not sleep just yet
- *
- * Also ensures we preserve battery life by only doing ONE update when the above use case is not triggered.
- * 1) MAIN THREAD: Update Request: COUNTER = 1
- * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
- * 3) MAIN THREAD: Sleep Request: COUNTER = 0 -> Go to sleep
- */
-const unsigned int MAXIMUM_UPDATE_REQUESTS = 2;
-} // unnamed namespace
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// EVENT THREAD
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-CombinedUpdateRenderController::CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions )
-: mFpsTracker( environmentOptions ),
- mUpdateStatusLogger( environmentOptions ),
- mRenderHelper( adaptorInterfaces ),
- mEventThreadSemaphore(),
- mUpdateRenderThreadWaitCondition(),
- mAdaptorInterfaces( adaptorInterfaces ),
- mPerformanceInterface( adaptorInterfaces.GetPerformanceInterface() ),
- mCore( adaptorInterfaces.GetCore() ),
- mEnvironmentOptions( environmentOptions ),
- mNotificationTrigger( adaptorInterfaces.GetProcessCoreEventsTrigger() ),
- mSleepTrigger( NULL ),
- mUpdateRenderThread( NULL ),
- mDefaultFrameDelta( 0.0f ),
- mDefaultFrameDurationMilliseconds( 0u ),
- mDefaultFrameDurationNanoseconds( 0u ),
- mDefaultHalfFrameNanoseconds( 0u ),
- mUpdateRequestCount( 0u ),
- mRunning( FALSE ),
- mUpdateRenderRunCount( 0 ),
- mDestroyUpdateRenderThread( FALSE ),
- mUpdateRenderThreadCanSleep( FALSE ),
- mPendingRequestUpdate( FALSE ),
- mUseElapsedTimeAfterWait( FALSE ),
- mNewSurface( NULL ),
- mPostRendering( FALSE ),
- mSurfaceResized( FALSE )
-{
- LOG_EVENT_TRACE;
-
- // Initialise frame delta/duration variables first
- SetRenderRefreshRate( environmentOptions.GetRenderRefreshRate() );
-
- // Set the thread-synchronization interface on the render-surface
- RenderSurface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
- if( currentSurface )
- {
- currentSurface->SetThreadSynchronization( *this );
- }
-
- TriggerEventFactoryInterface& triggerFactory = mAdaptorInterfaces.GetTriggerEventFactoryInterface();
- mSleepTrigger = triggerFactory.CreateTriggerEvent( MakeCallback( this, &CombinedUpdateRenderController::ProcessSleepRequest ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
-
- sem_init( &mEventThreadSemaphore, 0, 0 ); // Initialize to 0 so that it just waits if sem_post has not been called
-}
-
-CombinedUpdateRenderController::~CombinedUpdateRenderController()
-{
- LOG_EVENT_TRACE;
-
- Stop();
-
- delete mSleepTrigger;
-}
-
-void CombinedUpdateRenderController::Initialize()
-{
- LOG_EVENT_TRACE;
-
- // Ensure Update/Render Thread not already created
- DALI_ASSERT_ALWAYS( ! mUpdateRenderThread );
-
- // Create Update/Render Thread
- mUpdateRenderThread = new pthread_t();
- int error = pthread_create( mUpdateRenderThread, NULL, InternalUpdateRenderThreadEntryFunc, this );
- DALI_ASSERT_ALWAYS( !error && "Return code from pthread_create() when creating UpdateRenderThread" );
-
- // The Update/Render thread will now run and initialise EGL etc. and will then wait for Start to be called
- // When this function returns, the application initialisation on the event thread should occur
-}
-
-void CombinedUpdateRenderController::Start()
-{
- LOG_EVENT_TRACE;
-
- DALI_ASSERT_ALWAYS( !mRunning && mUpdateRenderThread );
-
- // Wait until all threads created in Initialise are up and running
- for( unsigned int i = 0; i < CREATED_THREAD_COUNT; ++i )
- {
- sem_wait( &mEventThreadSemaphore );
- }
-
- mRenderHelper.Start();
-
- mRunning = TRUE;
-
- LOG_EVENT( "Startup Complete, starting Update/Render Thread" );
-
- RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
-}
-
-void CombinedUpdateRenderController::Pause()
-{
- LOG_EVENT_TRACE;
-
- mRunning = FALSE;
-
- PauseUpdateRenderThread();
-
- AddPerformanceMarker( PerformanceInterface::PAUSED );
-}
-
-void CombinedUpdateRenderController::Resume()
-{
- LOG_EVENT_TRACE;
-
- if( !mRunning && IsUpdateRenderThreadPaused() )
- {
- LOG_EVENT( "Resuming" );
-
- RunUpdateRenderThread( CONTINUOUS, true /* Animation progression required while we were paused */ );
-
- AddPerformanceMarker( PerformanceInterface::RESUME );
-
- mRunning = TRUE;
- }
-}
-
-void CombinedUpdateRenderController::Stop()
-{
- LOG_EVENT_TRACE;
-
- // Stop Rendering and the Update/Render Thread
- mRenderHelper.Stop();
-
- StopUpdateRenderThread();
-
- if( mUpdateRenderThread )
- {
- LOG_EVENT( "Destroying UpdateRenderThread" );
-
- // wait for the thread to finish
- pthread_join( *mUpdateRenderThread, NULL );
-
- delete mUpdateRenderThread;
- mUpdateRenderThread = NULL;
- }
-
- mRunning = FALSE;
-}
-
-void CombinedUpdateRenderController::RequestUpdate()
-{
- LOG_EVENT_TRACE;
-
- // Increment the update-request count to the maximum
- if( mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS )
- {
- ++mUpdateRequestCount;
- }
-
- if( mRunning && IsUpdateRenderThreadPaused() )
- {
- LOG_EVENT( "Processing" );
-
- RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
- }
-
- ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
- mPendingRequestUpdate = TRUE;
-}
-
-void CombinedUpdateRenderController::RequestUpdateOnce()
-{
- // Increment the update-request count to the maximum
- if( mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS )
- {
- ++mUpdateRequestCount;
- }
-
- if( IsUpdateRenderThreadPaused() )
- {
- LOG_EVENT_TRACE;
-
- // Run Update/Render once
- RunUpdateRenderThread( ONCE, false /* No animation progression */ );
- }
-}
-
-void CombinedUpdateRenderController::ReplaceSurface( RenderSurface* newSurface )
-{
- LOG_EVENT_TRACE;
-
- // Set the ThreadSyncronizationInterface on the new surface
- newSurface->SetThreadSynchronization( *this );
-
- LOG_EVENT( "Starting to replace the surface, event-thread blocked" );
-
- // Start replacing the surface.
- {
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will replace the surface now
- mNewSurface = newSurface;
- mUpdateRenderThreadWaitCondition.Notify( lock );
- }
-
- // Wait until the surface has been replaced
- sem_wait( &mEventThreadSemaphore );
-
- LOG_EVENT( "Surface replaced, event-thread continuing" );
-}
-
-void CombinedUpdateRenderController::ResizeSurface()
-{
- LOG_EVENT_TRACE;
-
- LOG_EVENT( "Starting to resize the surface, event-thread blocked" );
-
- // Start resizing the surface.
- {
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will resize the surface now
- mSurfaceResized = TRUE;
- mUpdateRenderThreadWaitCondition.Notify( lock );
- }
-
- // Wait until the surface has been resized
- sem_wait( &mEventThreadSemaphore );
-
- LOG_EVENT( "Surface resized, event-thread continuing" );
-}
-
-void CombinedUpdateRenderController::SetRenderRefreshRate( unsigned int numberOfFramesPerRender )
-{
- // Not protected by lock, but written to rarely so not worth adding a lock when reading
- mDefaultFrameDelta = numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_SECONDS;
- mDefaultFrameDurationMilliseconds = uint64_t( numberOfFramesPerRender ) * DEFAULT_FRAME_DURATION_IN_MILLISECONDS;
- mDefaultFrameDurationNanoseconds = uint64_t( numberOfFramesPerRender ) * DEFAULT_FRAME_DURATION_IN_NANOSECONDS;
- mDefaultHalfFrameNanoseconds = mDefaultFrameDurationNanoseconds / 2u;
-
- LOG_EVENT( "mDefaultFrameDelta(%.6f), mDefaultFrameDurationMilliseconds(%lld), mDefaultFrameDurationNanoseconds(%lld)", mDefaultFrameDelta, mDefaultFrameDurationMilliseconds, mDefaultFrameDurationNanoseconds );
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// EVENT THREAD
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-void CombinedUpdateRenderController::RunUpdateRenderThread( int numberOfCycles, bool useElapsedTime )
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mUpdateRenderRunCount = numberOfCycles;
- mUpdateRenderThreadCanSleep = FALSE;
- mUseElapsedTimeAfterWait = useElapsedTime;
- LOG_COUNTER_EVENT( "mUpdateRenderRunCount: %d, mUseElapsedTimeAfterWait: %d", mUpdateRenderRunCount, mUseElapsedTimeAfterWait );
- mUpdateRenderThreadWaitCondition.Notify( lock );
-}
-
-void CombinedUpdateRenderController::PauseUpdateRenderThread()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mUpdateRenderRunCount = 0;
-}
-
-void CombinedUpdateRenderController::StopUpdateRenderThread()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mDestroyUpdateRenderThread = TRUE;
- mUpdateRenderThreadWaitCondition.Notify( lock );
-}
-
-bool CombinedUpdateRenderController::IsUpdateRenderThreadPaused()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- return ( mUpdateRenderRunCount != CONTINUOUS ) || // Report paused if NOT continuously running
- mUpdateRenderThreadCanSleep; // Report paused if sleeping
-}
-
-void CombinedUpdateRenderController::ProcessSleepRequest()
-{
- LOG_EVENT_TRACE;
-
- // Decrement Update request count
- if( mUpdateRequestCount > 0 )
- {
- --mUpdateRequestCount;
- }
-
- // Can sleep if our update-request count is 0
- // Update/Render thread can choose to carry on updating if it determines more update/renders are required
- if( mUpdateRequestCount == 0 )
- {
- LOG_EVENT( "Going to sleep" );
-
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mUpdateRenderThreadCanSleep = TRUE;
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// UPDATE/RENDER THREAD
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-void CombinedUpdateRenderController::UpdateRenderThread()
-{
- // Install a function for logging
- mEnvironmentOptions.InstallLogFunction();
-
- LOG_UPDATE_RENDER( "THREAD CREATED" );
-
- mRenderHelper.InitializeEgl();
-
- // tell core it has a context
- mCore.ContextCreated();
-
- NotifyThreadInitialised();
-
- // Update time
- uint64_t lastFrameTime;
- TimeService::GetNanoseconds( lastFrameTime );
-
- LOG_UPDATE_RENDER( "THREAD INITIALISED" );
-
- bool useElapsedTime = true;
- bool updateRequired = true;
- uint64_t timeToSleepUntil = 0;
- int extraFramesDropped = 0;
-
- const unsigned int renderToFboInterval = mEnvironmentOptions.GetRenderToFboInterval();
- const bool renderToFboEnabled = 0u != renderToFboInterval;
- unsigned int frameCount = 0u;
-
- while( UpdateRenderReady( useElapsedTime, updateRequired, timeToSleepUntil ) )
- {
- LOG_UPDATE_RENDER_TRACE;
-
- // Performance statistics are logged upon a VSYNC tick so use this point for a VSync marker
- AddPerformanceMarker( PerformanceInterface::VSYNC );
-
- uint64_t currentFrameStartTime = 0;
- TimeService::GetNanoseconds( currentFrameStartTime );
-
- const uint64_t timeSinceLastFrame = currentFrameStartTime - lastFrameTime;
-
- // Optional FPS Tracking when continuously rendering
- if( useElapsedTime && mFpsTracker.Enabled() )
- {
- float absoluteTimeSinceLastRender = timeSinceLastFrame * NANOSECONDS_TO_SECOND;
- mFpsTracker.Track( absoluteTimeSinceLastRender );
- }
-
- lastFrameTime = currentFrameStartTime; // Store frame start time
-
- //////////////////////////////
- // REPLACE SURFACE
- //////////////////////////////
-
- RenderSurface* newSurface = ShouldSurfaceBeReplaced();
- if( DALI_UNLIKELY( newSurface ) )
- {
- LOG_UPDATE_RENDER_TRACE_FMT( "Replacing Surface" );
- mRenderHelper.ReplaceSurface( newSurface );
- SurfaceReplaced();
- }
-
- //////////////////////////////
- // RESIZE SURFACE
- //////////////////////////////
-
- const bool isRenderingToFbo = renderToFboEnabled && ( ( 0u == frameCount ) || ( 0u != frameCount % renderToFboInterval ) );
- ++frameCount;
-
- // The resizing will be applied in the next loop
- bool surfaceResized = ShouldSurfaceBeResized();
- if( DALI_UNLIKELY( surfaceResized ) )
- {
- LOG_UPDATE_RENDER_TRACE_FMT( "Resizing Surface" );
- mRenderHelper.ResizeSurface();
- SurfaceResized();
- }
-
- //////////////////////////////
- // UPDATE
- //////////////////////////////
-
- const unsigned int currentTime = currentFrameStartTime / NANOSECONDS_PER_MILLISECOND;
- const unsigned int nextFrameTime = currentTime + mDefaultFrameDurationMilliseconds;
-
- uint64_t noOfFramesSinceLastUpdate = 1;
- float frameDelta = 0.0f;
- if( useElapsedTime )
- {
- // If using the elapsed time, then calculate frameDelta as a multiple of mDefaultFrameDelta
- noOfFramesSinceLastUpdate += extraFramesDropped;
-
- frameDelta = mDefaultFrameDelta * noOfFramesSinceLastUpdate;
- }
- LOG_UPDATE_RENDER( "timeSinceLastFrame(%llu) noOfFramesSinceLastUpdate(%u) frameDelta(%.6f)", timeSinceLastFrame, noOfFramesSinceLastUpdate, frameDelta );
-
- Integration::UpdateStatus updateStatus;
-
- AddPerformanceMarker( PerformanceInterface::UPDATE_START );
- mCore.Update( frameDelta,
- currentTime,
- nextFrameTime,
- updateStatus,
- renderToFboEnabled,
- isRenderingToFbo );
- AddPerformanceMarker( PerformanceInterface::UPDATE_END );
-
- unsigned int keepUpdatingStatus = updateStatus.KeepUpdating();
-
- // Tell the event-thread to wake up (if asleep) and send a notification event to Core if required
- if( updateStatus.NeedsNotification() )
- {
- mNotificationTrigger.Trigger();
- LOG_UPDATE_RENDER( "Notification Triggered" );
- }
-
- // Optional logging of update/render status
- mUpdateStatusLogger.Log( keepUpdatingStatus );
-
- //////////////////////////////
- // RENDER
- //////////////////////////////
-
- mRenderHelper.ConsumeEvents();
- mRenderHelper.PreRender();
-
- Integration::RenderStatus renderStatus;
-
- AddPerformanceMarker( PerformanceInterface::RENDER_START );
- mCore.Render( renderStatus );
- AddPerformanceMarker( PerformanceInterface::RENDER_END );
-
- if( renderStatus.NeedsPostRender() )
- {
- mRenderHelper.PostRender( isRenderingToFbo );
- }
-
- // Trigger event thread to request Update/Render thread to sleep if update not required
- if( ( Integration::KeepUpdating::NOT_REQUESTED == keepUpdatingStatus ) &&
- ! renderStatus.NeedsUpdate() )
- {
- mSleepTrigger->Trigger();
- updateRequired = false;
- LOG_UPDATE_RENDER( "Sleep Triggered" );
- }
- else
- {
- updateRequired = true;
- }
-
- //////////////////////////////
- // FRAME TIME
- //////////////////////////////
-
- extraFramesDropped = 0;
-
- if (timeToSleepUntil == 0)
- {
- // If this is the first frame after the thread is initialized or resumed, we
- // use the actual time the current frame starts from to calculate the time to
- // sleep until the next frame.
- timeToSleepUntil = currentFrameStartTime + mDefaultFrameDurationNanoseconds;
- }
- else
- {
- // Otherwise, always use the sleep-until time calculated in the last frame to
- // calculate the time to sleep until the next frame. In this way, if there is
- // any time gap between the current frame and the next frame, or if update or
- // rendering in the current frame takes too much time so that the specified
- // sleep-until time has already passed, it will try to keep the frames syncing
- // by shortening the duration of the next frame.
- timeToSleepUntil += mDefaultFrameDurationNanoseconds;
-
- // Check the current time at the end of the frame
- uint64_t currentFrameEndTime = 0;
- TimeService::GetNanoseconds( currentFrameEndTime );
- while ( currentFrameEndTime > timeToSleepUntil + mDefaultFrameDurationNanoseconds )
- {
- // We are more than one frame behind already, so just drop the next frames
- // until the sleep-until time is later than the current time so that we can
- // catch up.
- timeToSleepUntil += mDefaultFrameDurationNanoseconds;
- extraFramesDropped++;
- }
- }
-
- // Render to FBO is intended to measure fps above 60 so sleep is not wanted.
- if( 0u == renderToFboInterval )
- {
- // Sleep until at least the the default frame duration has elapsed. This will return immediately if the specified end-time has already passed.
- TimeService::SleepUntil( timeToSleepUntil );
- }
- }
-
- // Inform core of context destruction & shutdown EGL
- mCore.ContextDestroyed();
- mRenderHelper.ShutdownEgl();
-
- LOG_UPDATE_RENDER( "THREAD DESTROYED" );
-
- // Uninstall the logging function
- mEnvironmentOptions.UnInstallLogFunction();
-}
-
-bool CombinedUpdateRenderController::UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil )
-{
- useElapsedTime = true;
-
- ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
- while( ( ! mUpdateRenderRunCount || // Should try to wait if event-thread has paused the Update/Render thread
- ( mUpdateRenderThreadCanSleep && ! updateRequired && ! mPendingRequestUpdate ) ) && // Ensure we wait if we're supposed to be sleeping AND do not require another update
- ! mDestroyUpdateRenderThread && // Ensure we don't wait if the update-render-thread is supposed to be destroyed
- ! mNewSurface && // Ensure we don't wait if we need to replace the surface
- ! mSurfaceResized ) // Ensure we don't wait if we need to resize the surface
- {
- LOG_UPDATE_RENDER( "WAIT: mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
- LOG_UPDATE_RENDER( " mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
- LOG_UPDATE_RENDER( " mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
- LOG_UPDATE_RENDER( " mNewSurface: %d", mNewSurface );
- LOG_UPDATE_RENDER( " mSurfaceResized: %d", mSurfaceResized );
-
- // Reset the time when the thread is waiting, so the sleep-until time for
- // the first frame after resuming should be based on the actual start time
- // of the first frame.
- timeToSleepUntil = 0;
-
- mUpdateRenderThreadWaitCondition.Wait( updateLock );
-
- if( ! mUseElapsedTimeAfterWait )
- {
- useElapsedTime = false;
- }
- }
-
- LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
- LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
- LOG_COUNTER_UPDATE_RENDER( "mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
- LOG_COUNTER_UPDATE_RENDER( "mNewSurface: %d", mNewSurface );
- LOG_COUNTER_UPDATE_RENDER( "mSurfaceResized: %d", mSurfaceResized );
-
- mUseElapsedTimeAfterWait = FALSE;
- mUpdateRenderThreadCanSleep = FALSE;
- mPendingRequestUpdate = FALSE;
-
- // If we've been asked to run Update/Render cycles a finite number of times then decrement so we wait after the
- // requested number of cycles
- if( mUpdateRenderRunCount > 0 )
- {
- --mUpdateRenderRunCount;
- }
-
- // Keep the update-render thread alive if this thread is NOT to be destroyed
- return ! mDestroyUpdateRenderThread;
-}
-
-RenderSurface* CombinedUpdateRenderController::ShouldSurfaceBeReplaced()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
-
- RenderSurface* newSurface = mNewSurface;
- mNewSurface = NULL;
-
- return newSurface;
-}
-
-void CombinedUpdateRenderController::SurfaceReplaced()
-{
- // Just increment the semaphore
- sem_post( &mEventThreadSemaphore );
-}
-
-bool CombinedUpdateRenderController::ShouldSurfaceBeResized()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
-
- bool surfaceSized = mSurfaceResized;
- mSurfaceResized = FALSE;
-
- return surfaceSized;
-}
-
-void CombinedUpdateRenderController::SurfaceResized()
-{
- // Just increment the semaphore
- sem_post( &mEventThreadSemaphore );
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// ALL THREADS
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-void CombinedUpdateRenderController::NotifyThreadInitialised()
-{
- // Just increment the semaphore
- sem_post( &mEventThreadSemaphore );
-}
-
-void CombinedUpdateRenderController::AddPerformanceMarker( PerformanceInterface::MarkerType type )
-{
- if( mPerformanceInterface )
- {
- mPerformanceInterface->AddMarker( type );
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////////////
-// POST RENDERING: EVENT THREAD
-/////////////////////////////////////////////////////////////////////////////////////////////////
-
-void CombinedUpdateRenderController::PostRenderComplete()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mPostRendering = FALSE;
- mUpdateRenderThreadWaitCondition.Notify( lock );
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// POST RENDERING: RENDER THREAD
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-void CombinedUpdateRenderController::PostRenderStarted()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- mPostRendering = TRUE;
-}
-
-void CombinedUpdateRenderController::PostRenderWaitForCompletion()
-{
- ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
- while( mPostRendering &&
- ! mNewSurface && // We should NOT wait if we're replacing the surface
- ! mSurfaceResized && // We should NOT wait if we're resizing the surface
- ! mDestroyUpdateRenderThread )
- {
- mUpdateRenderThreadWaitCondition.Wait( lock );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
-#define __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <semaphore.h>
-#include <stdint.h>
-#include <dali/integration-api/core.h>
-#include <dali/devel-api/threading/conditional-wait.h>
-
-// INTERNAL INCLUDES
-#include <integration-api/thread-synchronization-interface.h>
-#include <base/interfaces/performance-interface.h>
-#include <base/fps-tracker.h>
-#include <base/render-helper.h>
-#include <base/thread-controller-interface.h>
-#include <base/update-status-logger.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-class TriggerEventInterface;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class AdaptorInternalServices;
-class EnvironmentOptions;
-
-/**
- * @brief Two threads where events/application interaction is handled on the main/event thread and the Update & Render
- * happen on the other thread.
- *
- * Key Points:
- * 1. Two Threads:
- * a. Main/Event Thread.
- * b. Update/Render Thread.
- * 2. There is NO VSync thread:
- * a. We retrieve the time before Update.
- * b. Then retrieve the time after Render.
- * c. We calculate the difference between these two times and if:
- * i. The difference is less than the default frame time, we sleep.
- * ii. If it’s more or the same, we continue.
- * 3. On the update/render thread, if we discover that we do not need to do any more updates, we use a trigger-event
- * to inform the main/event thread. This is then processed as soon as the event thread is able to do so where it
- * is easier to make a decision about whether we should stop the update/render thread or not (depending on any
- * update requests etc.).
- * 4. The main thread is blocked while the surface is being replaced.
- * 5. When we resume from paused, elapsed time is used for the animations, i.e. the could have finished while we were paused.
- * However, FinishedSignal emission will only happen upon resumption.
- * 6. Elapsed time is NOT used while if we are waking up from a sleep state or doing an UpdateOnce.
- */
-class CombinedUpdateRenderController : public ThreadControllerInterface,
- public ThreadSynchronizationInterface
-{
-public:
-
- /**
- * Constructor
- */
- CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions );
-
- /**
- * Non virtual destructor. Not intended as base class.
- */
- ~CombinedUpdateRenderController();
-
- /**
- * @copydoc ThreadControllerInterface::Initialize()
- */
- virtual void Initialize();
-
- /**
- * @copydoc ThreadControllerInterface::Start()
- */
- virtual void Start();
-
- /**
- * @copydoc ThreadControllerInterface::Pause()
- */
- virtual void Pause();
-
- /**
- * @copydoc ThreadControllerInterface::Resume()
- */
- virtual void Resume();
-
- /**
- * @copydoc ThreadControllerInterface::Stop()
- */
- virtual void Stop();
-
- /**
- * @copydoc ThreadControllerInterface::RequestUpdate()
- */
- virtual void RequestUpdate();
-
- /**
- * @copydoc ThreadControllerInterface::RequestUpdateOnce()
- */
- virtual void RequestUpdateOnce();
-
- /**
- * @copydoc ThreadControllerInterface::ReplaceSurface()
- */
- virtual void ReplaceSurface( RenderSurface* surface );
-
- /**
- * @copydoc ThreadControllerInterface::ResizeSurface()
- */
- virtual void ResizeSurface();
-
- /**
- * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
- */
- virtual void SetRenderRefreshRate( unsigned int numberOfFramesPerRender );
-
-private:
-
- // Undefined copy constructor.
- CombinedUpdateRenderController( const CombinedUpdateRenderController& );
-
- // Undefined assignment operator.
- CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& );
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // EventThread
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Runs the Update/Render Thread.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- *
- * @param[in] numberOfCycles The number of times the update/render cycle should run. If -1, then it will run continuously.
- * @param[in] useElapsedTimeAfterWait If true, then the elapsed time during wait is used for animations, otherwise no animation progression is made.
- */
- inline void RunUpdateRenderThread( int numberOfCycles, bool useElapsedTimeAfterWait );
-
- /**
- * Pauses the Update/Render Thread.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- */
- inline void PauseUpdateRenderThread();
-
- /**
- * Stops the Update/Render Thread.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- *
- * @note Should only be called in Stop as calling this will kill the update-thread.
- */
- inline void StopUpdateRenderThread();
-
- /**
- * Checks if the the Update/Render Thread is paused.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- *
- * @return true if paused, false otherwise
- */
- inline bool IsUpdateRenderThreadPaused();
-
- /**
- * Used as the callback for the sleep-trigger.
- *
- * Will sleep when enough requests are made without any requests.
- */
- void ProcessSleepRequest();
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // UpdateRenderThread
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * The Update/Render thread loop. This thread will be destroyed on exit from this function.
- */
- void UpdateRenderThread();
-
- /**
- * Called by the Update/Render Thread which ensures a wait if required.
- *
- * @param[out] useElapsedTime If true when returned, then the actual elapsed time will be used for animation.
- * If false when returned, then there should NOT be any animation progression in the next Update.
- * @param[in] updateRequired Whether another update is required.
- * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming.
- * @return false, if the thread should stop.
- */
- bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil );
-
- /**
- * Checks to see if the surface needs to be replaced.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- *
- * @return Pointer to the new surface, NULL otherwise
- */
- RenderSurface* ShouldSurfaceBeReplaced();
-
- /**
- * Called by the Update/Render thread after a surface has been replaced.
- *
- * This will lock the mutex in mEventThreadWaitCondition
- */
- void SurfaceReplaced();
-
- /**
- * Checks to see if the surface needs to be resized.
- * This will lock the mutex in mUpdateRenderThreadWaitCondition.
- *
- * @return true if the surface should be resized, false otherwise
- */
- bool ShouldSurfaceBeResized();
-
- /**
- * Called by the Update/Render thread after a surface has been resized.
- *
- * This will lock the mutex in mEventThreadWaitCondition
- */
- void SurfaceResized();
-
- /**
- * Helper for the thread calling the entry function
- * @param[in] This A pointer to the current object
- */
- static void* InternalUpdateRenderThreadEntryFunc( void* This )
- {
- ( static_cast<CombinedUpdateRenderController*>( This ) )->UpdateRenderThread();
- return NULL;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // ALL Threads
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called by the update-render & v-sync threads when they up and running.
- *
- * This will lock the mutex in mEventThreadWaitCondition.
- */
- void NotifyThreadInitialised();
-
- /**
- * Helper to add a performance marker to the performance server (if it's active)
- * @param[in] type performance marker type
- */
- void AddPerformanceMarker( PerformanceInterface::MarkerType type );
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // POST RENDERING - ThreadSynchronizationInterface overrides
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- //// Called by the Event Thread if post-rendering is required
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
- */
- virtual void PostRenderComplete();
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- //// Called by the Render Thread if post-rendering is required
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
- */
- virtual void PostRenderStarted();
-
- /**
- * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
- */
- virtual void PostRenderWaitForCompletion();
-
-private:
-
- FpsTracker mFpsTracker; ///< Object that tracks the FPS
- UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required.
-
- RenderHelper mRenderHelper; ///< Helper class for EGL, pre & post rendering
-
- sem_t mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
-
- ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread.
-
- AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface
- PerformanceInterface* mPerformanceInterface; ///< The performance logging interface
- Integration::Core& mCore; ///< Dali core reference
- const EnvironmentOptions& mEnvironmentOptions; ///< Environment options
- TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger
- TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
-
- pthread_t* mUpdateRenderThread; ///< The Update/Render thread.
-
- float mDefaultFrameDelta; ///< Default time delta between each frame (used for animations). Not protected by lock, but written to rarely so not worth adding a lock when reading.
- uint64_t mDefaultFrameDurationMilliseconds; ///< Default duration of a frame (used for predicting the time of the next frame). Not protected by lock, but written to rarely so not worth adding a lock when reading.
- uint64_t mDefaultFrameDurationNanoseconds; ///< Default duration of a frame (used for sleeping if not enough time elapsed). Not protected by lock, but written to rarely so not worth adding a lock when reading.
- uint64_t mDefaultHalfFrameNanoseconds; ///< Is half of mDefaultFrameDurationNanoseconds. Using a member variable avoids having to do the calculation every frame. Not protected by lock, but written to rarely so not worth adding a lock when reading.
-
- unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early.
- unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running.
-
- //
- // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
- //
-
- volatile int mUpdateRenderRunCount; ///< The number of times Update/Render cycle should run. If -1, then will run continuously (set by the event-thread, read by v-sync-thread).
- volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
- volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
- volatile unsigned int mPendingRequestUpdate; ///< Is set as soon as an RequestUpdate is made and unset when the next update happens (set by the event-thread and update-render thread, read by the update-render-thread).
- ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
-
- volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
-
- RenderSurface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread).
-
- volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
- volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <base/display-connection.h>
-
-// EXTERNAL INCLUDES
-
-// INTERNAL INCLUDES
-#include <display-connection-impl.h>
-#include <egl-interface.h>
-
-namespace Dali
-{
-
-DisplayConnection* DisplayConnection::New()
-{
- Internal::Adaptor::DisplayConnection* internal(Internal::Adaptor::DisplayConnection::New());
-
- return new DisplayConnection(internal);
-}
-
-DisplayConnection* DisplayConnection::New( RenderSurface::Type type )
-{
- Internal::Adaptor::DisplayConnection* internal(Internal::Adaptor::DisplayConnection::New());
- internal->SetSurfaceType( type );
-
- return new DisplayConnection(internal);
-}
-
-DisplayConnection::DisplayConnection()
-: mImpl( NULL )
-{
-}
-
-DisplayConnection::DisplayConnection(Internal::Adaptor::DisplayConnection* impl)
-: mImpl(impl)
-{
-}
-
-DisplayConnection::~DisplayConnection()
-{
- if (mImpl)
- {
- delete mImpl;
- mImpl = NULL;
- }
-}
-
-Any DisplayConnection::GetDisplay()
-{
- return mImpl->GetDisplay();
-}
-
-void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
-{
- Internal::Adaptor::DisplayConnection::GetDpi(dpiHorizontal, dpiVertical);
-}
-
-void DisplayConnection::ConsumeEvents()
-{
- mImpl->ConsumeEvents();
-}
-
-bool DisplayConnection::InitializeEgl(EglInterface& egl)
-{
- return mImpl->InitializeEgl(egl);
-}
-
-}
+++ /dev/null
-#ifndef __DALI_DISPLAY_CONNECTION_H__
-#define __DALI_DISPLAY_CONNECTION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/any.h>
-
-// INTERNAL INCLUDES
-#include <render-surface.h>
-
-
-namespace Dali
-{
-
-class EglInterface;
-
-namespace Internal
-{
- namespace Adaptor
- {
- class DisplayConnection;
- }
-}
-
-class DisplayConnection
-{
-public:
-
- /**
- * @brief Create an initialized DisplayConnection.
- *
- * @return A handle to a newly allocated DisplayConnection resource.
- */
- static DisplayConnection* New();
-
- /**
- * @brief Create an initialized DisplayConnection.
- * Native surface will need this instead of DisplayConnection::New()
- *
- * @param[in] type Render surface type
- * @return A handle to a newly allocated DisplayConnection resource.
- */
- static DisplayConnection* New( RenderSurface::Type type );
-
- /**
- * @brief Create a DisplayConnection handle; this can be initialised with DisplayConnection::New().
- *
- * Calling member functions with an uninitialised handle is not allowed.
- */
- DisplayConnection();
-
- /**
- * @brief Destructor
- *
- * This is non-virtual since derived Handle types must not contain data or virtual methods.
- */
- ~DisplayConnection();
-
- /**
- * @brief Get display
- *
- * @return display
- */
- Any GetDisplay();
-
- /**
- * @brief Get DPI
- * @param[out] dpiHorizontal set to the horizontal dpi
- * @param[out] dpiVertical set to the vertical dpi
- */
- static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
-
- /**
- * @brief Consumes any possible events on the queue so that there is no leaking between frames
- */
- void ConsumeEvents();
-
- /**
- * @brief Initialize EGL display
- *
- * @param egl implementation to use for the creation
- */
- bool InitializeEgl(EglInterface& egl);
-
-public:
-
- /**
- * @brief This constructor is used by DisplayConnection New() methods.
- *
- * @param [in] handle A pointer to a newly allocated DisplayConnection resource
- */
- explicit DALI_INTERNAL DisplayConnection(Internal::Adaptor::DisplayConnection* impl);
-
-private:
-
- Internal::Adaptor::DisplayConnection* mImpl;
-};
-
-}
-
-#endif // __DALI_DISPLAY_CONNECTION_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "environment-options.h"
-
-// EXTERNAL INCLUDES
-#include <cstdlib>
-#include <dali/integration-api/render-controller.h>
-#include <dali/public-api/math/math-utils.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-variables.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int DEFAULT_STATISTICS_LOG_FREQUENCY = 2;
-const int DEFAULT_MULTI_SAMPLING_LEVEL = -1;
-const bool DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING = true;
-const bool DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING = true;
-
-unsigned int GetIntegerEnvironmentVariable( const char* variable, unsigned int defaultValue )
-{
- const char* variableParameter = std::getenv(variable);
-
- // if the parameter exists convert it to an integer, else return the default value
- unsigned int intValue = variableParameter ? std::atoi(variableParameter) : defaultValue;
- return intValue;
-}
-
-bool GetIntegerEnvironmentVariable( const char* variable, int& intValue )
-{
- const char* variableParameter = std::getenv(variable);
-
- if( !variableParameter )
- {
- return false;
- }
- // if the parameter exists convert it to an integer, else return the default value
- intValue = std::atoi(variableParameter);
- return true;
-}
-
-bool GetFloatEnvironmentVariable( const char* variable, float& floatValue )
-{
- const char* variableParameter = std::getenv(variable);
-
- if( !variableParameter )
- {
- return false;
- }
- // if the parameter exists convert it to an integer, else return the default value
- floatValue = std::atof(variableParameter);
- return true;
-}
-
-const char * GetCharEnvironmentVariable( const char * variable )
-{
- return std::getenv( variable );
-}
-
-} // unnamed namespace
-
-EnvironmentOptions::EnvironmentOptions()
-: mLogFunction( NULL ),
- mWindowName(),
- mWindowClassName(),
- mNetworkControl( 0 ),
- mFpsFrequency( 0 ),
- mUpdateStatusFrequency( 0 ),
- mObjectProfilerInterval( 0 ),
- mPerformanceStatsLevel( 0 ),
- mPerformanceStatsFrequency( DEFAULT_STATISTICS_LOG_FREQUENCY ),
- mPerformanceTimeStampOutput( 0 ),
- mPanGestureLoggingLevel( 0 ),
- mWindowWidth( 0u ),
- mWindowHeight( 0u ),
- mRenderRefreshRate( 1u ),
- mMaxTextureSize( 0 ),
- mRenderToFboInterval( 0u ),
- mPanGesturePredictionMode( -1 ),
- mPanGesturePredictionAmount( -1 ), ///< only sets value in pan gesture if greater than 0
- mPanGestureMaxPredictionAmount( -1 ),
- mPanGestureMinPredictionAmount( -1 ),
- mPanGesturePredictionAmountAdjustment( -1 ),
- mPanGestureSmoothingMode( -1 ),
- mPanGestureSmoothingAmount( -1.0f ),
- mPanGestureUseActualTimes( -1 ),
- mPanGestureInterpolationTimeRange( -1 ),
- mPanGestureScalarOnlyPredictionEnabled( -1 ),
- mPanGestureTwoPointPredictionEnabled( -1 ),
- mPanGestureTwoPointInterpolatePastTime( -1 ),
- mPanGestureTwoPointVelocityBias( -1.0f ),
- mPanGestureTwoPointAccelerationBias( -1.0f ),
- mPanGestureMultitapSmoothingRange( -1 ),
- mPanMinimumDistance( -1 ),
- mPanMinimumEvents( -1 ),
- mGlesCallTime( 0 ),
- mMultiSamplingLevel( DEFAULT_MULTI_SAMPLING_LEVEL ),
- mIndicatorVisibleMode( -1 ),
- mThreadingMode( ThreadingMode::COMBINED_UPDATE_RENDER ),
- mGlesCallAccumulate( false ),
- mDepthBufferRequired( DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING ),
- mStencilBufferRequired( DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING )
-{
- ParseEnvironmentOptions();
-}
-
-EnvironmentOptions::~EnvironmentOptions()
-{
-}
-
-void EnvironmentOptions::SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction )
-{
- mLogFunction = logFunction;
-}
-
-void EnvironmentOptions::InstallLogFunction() const
-{
- Dali::Integration::Log::InstallLogFunction( mLogFunction );
-}
-
-void EnvironmentOptions::UnInstallLogFunction() const
-{
- Dali::Integration::Log::UninstallLogFunction();
-}
-
-unsigned int EnvironmentOptions::GetNetworkControlMode() const
-{
- return mNetworkControl;
-}
-unsigned int EnvironmentOptions::GetFrameRateLoggingFrequency() const
-{
- return mFpsFrequency;
-}
-
-unsigned int EnvironmentOptions::GetUpdateStatusLoggingFrequency() const
-{
- return mUpdateStatusFrequency;
-}
-
-unsigned int EnvironmentOptions::GetObjectProfilerInterval() const
-{
- return mObjectProfilerInterval;
-}
-
-unsigned int EnvironmentOptions::GetPerformanceStatsLoggingOptions() const
-{
- return mPerformanceStatsLevel;
-}
-unsigned int EnvironmentOptions::GetPerformanceStatsLoggingFrequency() const
-{
- return mPerformanceStatsFrequency;
-}
-unsigned int EnvironmentOptions::GetPerformanceTimeStampOutput() const
-{
- return mPerformanceTimeStampOutput;
-}
-
-unsigned int EnvironmentOptions::GetPanGestureLoggingLevel() const
-{
- return mPanGestureLoggingLevel;
-}
-
-int EnvironmentOptions::GetPanGesturePredictionMode() const
-{
- return mPanGesturePredictionMode;
-}
-
-int EnvironmentOptions::GetPanGesturePredictionAmount() const
-{
- return mPanGesturePredictionAmount;
-}
-
-int EnvironmentOptions::GetPanGestureMaximumPredictionAmount() const
-{
- return mPanGestureMaxPredictionAmount;
-}
-
-int EnvironmentOptions::GetPanGestureMinimumPredictionAmount() const
-{
- return mPanGestureMinPredictionAmount;
-}
-
-int EnvironmentOptions::GetPanGesturePredictionAmountAdjustment() const
-{
- return mPanGesturePredictionAmountAdjustment;
-}
-
-int EnvironmentOptions::GetPanGestureSmoothingMode() const
-{
- return mPanGestureSmoothingMode;
-}
-
-float EnvironmentOptions::GetPanGestureSmoothingAmount() const
-{
- return mPanGestureSmoothingAmount;
-}
-
-int EnvironmentOptions::GetPanGestureUseActualTimes() const
-{
- return mPanGestureUseActualTimes;
-}
-
-int EnvironmentOptions::GetPanGestureInterpolationTimeRange() const
-{
- return mPanGestureInterpolationTimeRange;
-}
-
-int EnvironmentOptions::GetPanGestureScalarOnlyPredictionEnabled() const
-{
- return mPanGestureScalarOnlyPredictionEnabled;
-}
-
-int EnvironmentOptions::GetPanGestureTwoPointPredictionEnabled() const
-{
- return mPanGestureTwoPointPredictionEnabled;
-}
-
-int EnvironmentOptions::GetPanGestureTwoPointInterpolatePastTime() const
-{
- return mPanGestureTwoPointInterpolatePastTime;
-}
-
-float EnvironmentOptions::GetPanGestureTwoPointVelocityBias() const
-{
- return mPanGestureTwoPointVelocityBias;
-}
-
-float EnvironmentOptions::GetPanGestureTwoPointAccelerationBias() const
-{
- return mPanGestureTwoPointAccelerationBias;
-}
-
-int EnvironmentOptions::GetPanGestureMultitapSmoothingRange() const
-{
- return mPanGestureMultitapSmoothingRange;
-}
-
-int EnvironmentOptions::GetMinimumPanDistance() const
-{
- return mPanMinimumDistance;
-}
-
-int EnvironmentOptions::GetMinimumPanEvents() const
-{
- return mPanMinimumEvents;
-}
-
-unsigned int EnvironmentOptions::GetWindowWidth() const
-{
- return mWindowWidth;
-}
-
-unsigned int EnvironmentOptions::GetWindowHeight() const
-{
- return mWindowHeight;
-}
-
-int EnvironmentOptions::GetGlesCallTime() const
-{
- return mGlesCallTime;
-}
-
-bool EnvironmentOptions::GetGlesCallAccumulate() const
-{
- return mGlesCallAccumulate;
-}
-
-const std::string& EnvironmentOptions::GetWindowName() const
-{
- return mWindowName;
-}
-
-const std::string& EnvironmentOptions::GetWindowClassName() const
-{
- return mWindowClassName;
-}
-
-ThreadingMode::Type EnvironmentOptions::GetThreadingMode() const
-{
- return mThreadingMode;
-}
-
-unsigned int EnvironmentOptions::GetRenderRefreshRate() const
-{
- return mRenderRefreshRate;
-}
-
-int EnvironmentOptions::GetMultiSamplingLevel() const
-{
- return mMultiSamplingLevel;
-}
-
-unsigned int EnvironmentOptions::GetMaxTextureSize() const
-{
- return mMaxTextureSize;
-}
-
-int EnvironmentOptions::GetIndicatorVisibleMode() const
-{
- return mIndicatorVisibleMode;
-}
-
-unsigned int EnvironmentOptions::GetRenderToFboInterval() const
-{
- return mRenderToFboInterval;
-}
-
-bool EnvironmentOptions::PerformanceServerRequired() const
-{
- return ( ( GetPerformanceStatsLoggingOptions() > 0) ||
- ( GetPerformanceTimeStampOutput() > 0 ) ||
- ( GetNetworkControlMode() > 0) );
-}
-
-bool EnvironmentOptions::DepthBufferRequired() const
-{
- return mDepthBufferRequired;
-}
-
-bool EnvironmentOptions::StencilBufferRequired() const
-{
- return mStencilBufferRequired;
-}
-
-void EnvironmentOptions::ParseEnvironmentOptions()
-{
- // get logging options
- mFpsFrequency = GetIntegerEnvironmentVariable( DALI_ENV_FPS_TRACKING, 0 );
- mUpdateStatusFrequency = GetIntegerEnvironmentVariable( DALI_ENV_UPDATE_STATUS_INTERVAL, 0 );
- mObjectProfilerInterval = GetIntegerEnvironmentVariable( DALI_ENV_OBJECT_PROFILER_INTERVAL, 0 );
- mPerformanceStatsLevel = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS, 0 );
- mPerformanceStatsFrequency = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS_FREQUENCY, 0 );
- mPerformanceTimeStampOutput = GetIntegerEnvironmentVariable( DALI_ENV_PERFORMANCE_TIMESTAMP_OUTPUT, 0 );
- mNetworkControl = GetIntegerEnvironmentVariable( DALI_ENV_NETWORK_CONTROL, 0 );
- mPanGestureLoggingLevel = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PAN_GESTURE, 0 );
-
- int predictionMode;
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_MODE, predictionMode) )
- {
- mPanGesturePredictionMode = predictionMode;
- }
- int predictionAmount(-1);
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_AMOUNT, predictionAmount) )
- {
- if( predictionAmount < 0 )
- {
- // do not support times in the past
- predictionAmount = 0;
- }
- mPanGesturePredictionAmount = predictionAmount;
- }
- int minPredictionAmount(-1);
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MIN_PREDICTION_AMOUNT, minPredictionAmount) )
- {
- if( minPredictionAmount < 0 )
- {
- // do not support times in the past
- minPredictionAmount = 0;
- }
- mPanGestureMinPredictionAmount = minPredictionAmount;
- }
- int maxPredictionAmount(-1);
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MAX_PREDICTION_AMOUNT, maxPredictionAmount) )
- {
- if( minPredictionAmount > -1 && maxPredictionAmount < minPredictionAmount )
- {
- // maximum amount should not be smaller than minimum amount
- maxPredictionAmount = minPredictionAmount;
- }
- mPanGestureMaxPredictionAmount = maxPredictionAmount;
- }
- int predictionAmountAdjustment(-1);
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_AMOUNT_ADJUSTMENT, predictionAmountAdjustment) )
- {
- if( predictionAmountAdjustment < 0 )
- {
- // negative amount doesn't make sense
- predictionAmountAdjustment = 0;
- }
- mPanGesturePredictionAmountAdjustment = predictionAmountAdjustment;
- }
- int smoothingMode;
- if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_SMOOTHING_MODE, smoothingMode) )
- {
- mPanGestureSmoothingMode = smoothingMode;
- }
- float smoothingAmount = 1.0f;
- if( GetFloatEnvironmentVariable(DALI_ENV_PAN_SMOOTHING_AMOUNT, smoothingAmount) )
- {
- smoothingAmount = Clamp(smoothingAmount, 0.0f, 1.0f);
- mPanGestureSmoothingAmount = smoothingAmount;
- }
-
- int useActualTimes( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_USE_ACTUAL_TIMES, useActualTimes ) )
- {
- mPanGestureUseActualTimes = useActualTimes == 0 ? 0 : 1;
- }
-
- int interpolationTimeRange( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_INTERPOLATION_TIME_RANGE, interpolationTimeRange ) )
- {
- if( interpolationTimeRange < 0 )
- {
- interpolationTimeRange = 0;
- }
- mPanGestureInterpolationTimeRange = interpolationTimeRange;
- }
-
- int scalarOnlyPredictionEnabled( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_SCALAR_ONLY_PREDICTION_ENABLED, scalarOnlyPredictionEnabled ) )
- {
- mPanGestureScalarOnlyPredictionEnabled = scalarOnlyPredictionEnabled == 0 ? 0 : 1;
- }
-
- int twoPointPredictionEnabled( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_PREDICTION_ENABLED, twoPointPredictionEnabled ) )
- {
- mPanGestureTwoPointPredictionEnabled = twoPointPredictionEnabled == 0 ? 0 : 1;
- }
-
- int twoPointPastInterpolateTime( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_PAST_INTERPOLATE_TIME, twoPointPastInterpolateTime ) )
- {
- if( twoPointPastInterpolateTime < 0 )
- {
- twoPointPastInterpolateTime = 0;
- }
- mPanGestureTwoPointInterpolatePastTime = twoPointPastInterpolateTime;
- }
-
- float twoPointVelocityBias = -1.0f;
- if( GetFloatEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_VELOCITY_BIAS, twoPointVelocityBias ) )
- {
- twoPointVelocityBias = Clamp( twoPointVelocityBias, 0.0f, 1.0f );
- mPanGestureTwoPointVelocityBias = twoPointVelocityBias;
- }
-
- float twoPointAccelerationBias = -1.0f;
- if( GetFloatEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_ACCELERATION_BIAS, twoPointAccelerationBias ) )
- {
- twoPointAccelerationBias = Clamp( twoPointAccelerationBias, 0.0f, 1.0f );
- mPanGestureTwoPointAccelerationBias = twoPointAccelerationBias;
- }
-
- int multitapSmoothingRange( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_MULTITAP_SMOOTHING_RANGE, multitapSmoothingRange ) )
- {
- if( multitapSmoothingRange < 0 )
- {
- multitapSmoothingRange = 0;
- }
- mPanGestureMultitapSmoothingRange = multitapSmoothingRange;
- }
-
- int minimumDistance(-1);
- if ( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MINIMUM_DISTANCE, minimumDistance ))
- {
- mPanMinimumDistance = minimumDistance;
- }
-
- int minimumEvents(-1);
- if ( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MINIMUM_EVENTS, minimumEvents ))
- {
- mPanMinimumEvents = minimumEvents;
- }
-
- int glesCallTime(0);
- if ( GetIntegerEnvironmentVariable(DALI_GLES_CALL_TIME, glesCallTime ))
- {
- mGlesCallTime = glesCallTime;
- }
-
- int glesCallAccumulate( 0 );
- if ( GetIntegerEnvironmentVariable( DALI_GLES_CALL_ACCUMULATE, glesCallAccumulate ) )
- {
- mGlesCallAccumulate = glesCallAccumulate != 0;
- }
-
- int windowWidth(0), windowHeight(0);
- if ( GetIntegerEnvironmentVariable( DALI_WINDOW_WIDTH, windowWidth ) && GetIntegerEnvironmentVariable( DALI_WINDOW_HEIGHT, windowHeight ) )
- {
- mWindowWidth = windowWidth;
- mWindowHeight = windowHeight;
- }
-
- const char * windowName = GetCharEnvironmentVariable( DALI_WINDOW_NAME );
- if ( windowName )
- {
- mWindowName = windowName;
- }
-
- const char * windowClassName = GetCharEnvironmentVariable( DALI_WINDOW_CLASS_NAME );
- if ( windowClassName )
- {
- mWindowClassName = windowClassName;
- }
-
- int threadingMode(0);
- if ( GetIntegerEnvironmentVariable( DALI_THREADING_MODE, threadingMode ) )
- {
- switch( threadingMode )
- {
- case ThreadingMode::COMBINED_UPDATE_RENDER:
- {
- mThreadingMode = static_cast< ThreadingMode::Type >( threadingMode );
- break;
- }
- }
- }
-
- int renderRefreshRate(0);
- if ( GetIntegerEnvironmentVariable( DALI_REFRESH_RATE, renderRefreshRate ) )
- {
- // Only change it if it's valid
- if( renderRefreshRate > 1 )
- {
- mRenderRefreshRate = renderRefreshRate;
- }
- }
-
- int multiSamplingLevel( 0 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_MULTI_SAMPLING_LEVEL, multiSamplingLevel ) )
- {
- mMultiSamplingLevel = multiSamplingLevel;
- }
-
- int maxTextureSize( 0 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_MAX_TEXTURE_SIZE, maxTextureSize ) )
- {
- if( maxTextureSize > 0 )
- {
- mMaxTextureSize = maxTextureSize;
- }
- }
-
- int indicatorVisibleMode( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_INDICATOR_VISIBLE_MODE, indicatorVisibleMode ) )
- {
- if( indicatorVisibleMode > -1 )
- {
- mIndicatorVisibleMode = indicatorVisibleMode;
- }
- }
-
- mRenderToFboInterval = GetIntegerEnvironmentVariable( DALI_RENDER_TO_FBO, 0u );
-
-
- int depthBufferRequired( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_DISABLE_DEPTH_BUFFER, depthBufferRequired ) )
- {
- if( depthBufferRequired > 0 )
- {
- mDepthBufferRequired = false;
- mStencilBufferRequired = false; // Disable stencil buffer as well
- }
- }
-
- int stencilBufferRequired( -1 );
- if( GetIntegerEnvironmentVariable( DALI_ENV_DISABLE_STENCIL_BUFFER, stencilBufferRequired ) )
- {
- if( stencilBufferRequired > 0 )
- {
- mStencilBufferRequired = false;
- }
- }
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
-#define DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <base/threading-mode.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * This class provides the environment options which define settings as well as
- * the ability to install a log function.
- *
- */
-class EnvironmentOptions
-{
-public:
-
- /**
- * Constructor
- */
- EnvironmentOptions();
-
- /**
- * non-virtual destructor, not intended as a base class
- */
- ~EnvironmentOptions();
-
- /**
- * @param logFunction logging function
- */
- void SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction );
-
- /**
- * Install the log function for the current thread.
- */
- void InstallLogFunction() const;
-
- /**
- * Un-install the log function for the current thread.
- */
- void UnInstallLogFunction() const;
-
- /**
- * @return whether network control is enabled or not ( 0 = off, 1 = on )
- */
- unsigned int GetNetworkControlMode() const;
-
- /**
- * @return frequency of how often FPS is logged out (e.g. 0 = off, 2 = every 2 seconds).
- */
- unsigned int GetFrameRateLoggingFrequency() const;
-
- /**
- * @return frequency of how often Update Status is logged out (e.g. 0 = off, 60 = log every 60 frames = 1 second @ 60FPS).
- */
- unsigned int GetUpdateStatusLoggingFrequency() const;
-
- /**
- * @return object profiler status interval ( 0 == off )
- */
- unsigned int GetObjectProfilerInterval() const;
-
- /**
- * @return performance statistics log level ( 0 == off )
- */
- unsigned int GetPerformanceStatsLoggingOptions() const;
-
- /**
- * @return performance statistics log frequency in seconds
- */
- unsigned int GetPerformanceStatsLoggingFrequency() const;
-
- /**
- * @return performance time stamp output ( 0 == off)
- */
- unsigned int GetPerformanceTimeStampOutput() const;
-
- /**
- * @return pan-gesture logging level ( 0 == off )
- */
- unsigned int GetPanGestureLoggingLevel() const;
-
- /**
- * @return pan-gesture prediction mode ( -1 means not set so no prediction, 0 = no prediction )
- */
- int GetPanGesturePredictionMode() const;
-
- /**
- * @return pan-gesture prediction amount
- */
- int GetPanGesturePredictionAmount() const;
-
- /**
- * @return maximum pan-gesture prediction amount
- */
- int GetPanGestureMaximumPredictionAmount() const;
-
- /**
- * @return minimum pan-gesture prediction amount
- */
- int GetPanGestureMinimumPredictionAmount() const;
-
- /**
- * @brief Gets the prediction amount to adjust when the pan velocity is changed.
- *
- * If the pan velocity is accelerating, the prediction amount will be increased
- * by the specified amount until it reaches the upper bound. If the pan velocity
- * is decelerating, the prediction amount will be decreased by the specified
- * amount until it reaches the lower bound.
- *
- * @return pan-gesture prediction amount adjustment
- */
- int GetPanGesturePredictionAmountAdjustment() const;
-
- /**
- * @return pan-gesture smoothing mode ( -1 means not set so no smoothing, 0 = no smoothing )
- */
- int GetPanGestureSmoothingMode() const;
-
- /**
- * @return pan-gesture smoothing amount
- */
- float GetPanGestureSmoothingAmount() const;
-
- /**
- * @return pan-gesture use actual times is true if real gesture and frame times are to be used.
- */
- int GetPanGestureUseActualTimes() const;
-
- /**
- * @return pan-gesture interpolation time range is the time range (ms) of past points to use (with weights) when interpolating.
- */
- int GetPanGestureInterpolationTimeRange() const;
-
- /**
- * @return pan-gesture scalar only prediction, when enabled, ignores acceleration.
- */
- int GetPanGestureScalarOnlyPredictionEnabled() const;
-
- /**
- * @return pan-gesture two point prediction combines two interpolated points to get more steady acceleration and velocity values.
- */
- int GetPanGestureTwoPointPredictionEnabled() const;
-
- /**
- * @return pan-gesture two point interpolate past time is the time delta (ms) in the past to interpolate the second point.
- */
- int GetPanGestureTwoPointInterpolatePastTime() const;
-
- /**
- * @return pan-gesture two point velocity bias is the ratio of first and second points to use for velocity.
- * 0.0f = 100% of first point. 1.0f = 100% of second point.
- */
- float GetPanGestureTwoPointVelocityBias() const;
-
- /**
- * @return pan-gesture two point acceleration bias is the ratio of first and second points to use for acceleration.
- * 0.0f = 100% of first point. 1.0f = 100% of second point.
- */
- float GetPanGestureTwoPointAccelerationBias() const;
-
- /**
- * @return pan-gesture multitap smoothing range is the range in time (ms) of points in the history to smooth the final output against.
- */
- int GetPanGestureMultitapSmoothingRange() const;
-
- /**
- * @return The minimum distance before a pan can be started (-1 means it's not set)
- */
- int GetMinimumPanDistance() const;
-
- /**
- * @return The minimum events before a pan can be started (-1 means it's not set)
- */
- int GetMinimumPanEvents() const;
-
- /**
- * @return The width of the window
- */
- unsigned int GetWindowWidth() const;
-
- /**
- * @return The height of the window
- */
- unsigned int GetWindowHeight() const;
-
- /**
- * @brief Get the graphics status time
- */
- int GetGlesCallTime() const;
-
- /**
- * @brief Get whether or not to accumulate gles call statistics
- */
- bool GetGlesCallAccumulate() const;
-
- /**
- * @return true if performance server is required
- */
- bool PerformanceServerRequired() const;
-
- /**
- * @return Gets the window name.
- */
- const std::string& GetWindowName() const;
-
- /**
- * @return Gets the window class.
- */
- const std::string& GetWindowClassName() const;
-
- /**
- * @return The thread mode that DALi should use.
- */
- ThreadingMode::Type GetThreadingMode() const;
-
- /**
- * @return The render refresh rate.
- */
- unsigned int GetRenderRefreshRate() const;
-
- /**
- * @return The number of samples required in multisample buffers
- */
- int GetMultiSamplingLevel() const;
-
- /**
- * @return The maximum texture size
- */
- unsigned int GetMaxTextureSize() const;
-
- /**
- * @return The maximum texture size
- */
- int GetIndicatorVisibleMode() const;
-
- /**
- * @brief Retrieves the interval of frames to be rendered into the Frame Buffer Object and the Frame Buffer.
- *
- * @return The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer.
- */
- unsigned int GetRenderToFboInterval() const;
-
- /**
- * @return Whether the depth buffer is required.
- */
- bool DepthBufferRequired() const;
-
- /**
- * @return Whether the stencil buffer is required.
- */
- bool StencilBufferRequired() const;
-
- /// Deleted copy constructor.
- EnvironmentOptions( const EnvironmentOptions& ) = delete;
-
- /// Deleted move constructor.
- EnvironmentOptions( const EnvironmentOptions&& ) = delete;
-
- /// Deleted assignment operator.
- EnvironmentOptions& operator=( const EnvironmentOptions& ) = delete;
-
- /// Deleted move assignment operator.
- EnvironmentOptions& operator=( const EnvironmentOptions&& ) = delete;
-
-private: // Internal
-
- /**
- * Parses the environment options.
- * Called from the constructor
- */
- void ParseEnvironmentOptions();
-
-private: // Data
-
- Dali::Integration::Log::LogFunction mLogFunction;
-
- std::string mWindowName; ///< name of the window
- std::string mWindowClassName; ///< name of the class the window belongs to
- unsigned int mNetworkControl; ///< whether network control is enabled
- unsigned int mFpsFrequency; ///< how often fps is logged out in seconds
- unsigned int mUpdateStatusFrequency; ///< how often update status is logged out in frames
- unsigned int mObjectProfilerInterval; ///< how often object counts are logged out in seconds
- unsigned int mPerformanceStatsLevel; ///< performance statistics logging bitmask
- unsigned int mPerformanceStatsFrequency; ///< performance statistics logging frequency (seconds)
- unsigned int mPerformanceTimeStampOutput; ///< performance time stamp output ( bitmask)
- unsigned int mPanGestureLoggingLevel; ///< pan-gesture log level
- unsigned int mWindowWidth; ///< width of the window
- unsigned int mWindowHeight; ///< height of the window
- unsigned int mRenderRefreshRate; ///< render refresh rate
- unsigned int mMaxTextureSize; ///< The maximum texture size that GL can handle
- unsigned int mRenderToFboInterval; ///< The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer.
- int mPanGesturePredictionMode; ///< prediction mode for pan gestures
- int mPanGesturePredictionAmount; ///< prediction amount for pan gestures
- int mPanGestureMaxPredictionAmount; ///< maximum prediction amount for pan gestures
- int mPanGestureMinPredictionAmount; ///< minimum prediction amount for pan gestures
- int mPanGesturePredictionAmountAdjustment; ///< adjustment of prediction amount for pan gestures
- int mPanGestureSmoothingMode; ///< prediction mode for pan gestures
- float mPanGestureSmoothingAmount; ///< prediction amount for pan gestures
- int mPanGestureUseActualTimes; ///< Disable to optionally override actual times if they make results worse.
- int mPanGestureInterpolationTimeRange; ///< Time into past history (ms) to use points to interpolate the first point.
- int mPanGestureScalarOnlyPredictionEnabled; ///< If enabled, prediction is done using velocity alone (no integration or acceleration).
- int mPanGestureTwoPointPredictionEnabled; ///< If enabled, a second interpolated point is predicted and combined with the first to get more stable values.
- int mPanGestureTwoPointInterpolatePastTime; ///< The target time in the past to generate the second interpolated point.
- float mPanGestureTwoPointVelocityBias; ///< The ratio of first and second interpolated points to use for velocity. 0.0f = 100% of first point. 1.0f = 100% of second point.
- float mPanGestureTwoPointAccelerationBias; ///< The ratio of first and second interpolated points to use for acceleration. 0.0f = 100% of first point. 1.0f = 100% of second point.
- int mPanGestureMultitapSmoothingRange; ///< The range in time (ms) of points in the history to smooth the final output against.
- int mPanMinimumDistance; ///< minimum distance required before pan starts
- int mPanMinimumEvents; ///< minimum events required before pan starts
- int mGlesCallTime; ///< time in seconds between status updates
- int mMultiSamplingLevel; ///< The number of samples required in multisample buffers
- int mIndicatorVisibleMode; ///< Indicator visible mode
- ThreadingMode::Type mThreadingMode; ///< threading mode
- bool mGlesCallAccumulate; ///< Whether or not to accumulate gles call statistics
- bool mDepthBufferRequired; ///< Whether the depth buffer is required
- bool mStencilBufferRequired; ///< Whether the stencil buffer is required
-};
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif // DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
+++ /dev/null
-# Add local source files here
-
-base_adaptor_src_files = \
- $(base_adaptor_src_dir)/display-connection.cpp \
- $(base_adaptor_src_dir)/environment-options.cpp \
- $(base_adaptor_src_dir)/fps-tracker.cpp \
- $(base_adaptor_src_dir)/render-helper.cpp \
- $(base_adaptor_src_dir)/thread-controller.cpp \
- $(base_adaptor_src_dir)/time-service.cpp \
- $(base_adaptor_src_dir)/update-status-logger.cpp \
- $(base_adaptor_src_dir)/performance-logging/frame-time-stamp.cpp \
- $(base_adaptor_src_dir)/performance-logging/frame-time-stats.cpp \
- $(base_adaptor_src_dir)/performance-logging/performance-marker.cpp \
- $(base_adaptor_src_dir)/performance-logging/performance-server.cpp \
- $(base_adaptor_src_dir)/performance-logging/performance-interface-factory.cpp \
- $(base_adaptor_src_dir)/performance-logging/statistics/stat-context.cpp \
- $(base_adaptor_src_dir)/performance-logging/statistics/stat-context-manager.cpp \
- $(base_adaptor_src_dir)/combined-update-render/combined-update-render-controller.cpp
-
-base_adaptor_networking_src_files = \
- $(base_adaptor_src_dir)/performance-logging/networking/network-performance-protocol.cpp \
- $(base_adaptor_src_dir)/performance-logging/networking/network-performance-client.cpp \
- $(base_adaptor_src_dir)/performance-logging/networking/network-performance-server.cpp \
- $(base_adaptor_src_dir)/performance-logging/networking/event/automation.cpp
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "fps-tracker.h"
-
-// EXTERNAL INCLUDES
-#include <cstdio>
-#include <cmath>
-#include <sys/stat.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const char* DALI_TEMP_UPDATE_FPS_FILE( "/tmp/dalifps.txt" );
-} // unnamed namespace
-
-FpsTracker::FpsTracker( const EnvironmentOptions& environmentOptions )
-: mFpsTrackingSeconds( fabsf( environmentOptions.GetFrameRateLoggingFrequency() ) ),
- mFrameCount( 0.0f ),
- mElapsedTime( 0.0f )
-{
-}
-
-FpsTracker::~FpsTracker()
-{
- if( mFpsTrackingSeconds > 0.f )
- {
- OutputFPSRecord();
- }
-}
-
-void FpsTracker::Track( float secondsFromLastFrame )
-{
- if( mFpsTrackingSeconds > 0.f )
- {
- if ( mElapsedTime < mFpsTrackingSeconds )
- {
- mElapsedTime += secondsFromLastFrame;
- mFrameCount += 1.f;
- }
- else
- {
- OutputFPSRecord();
- mFrameCount = 0.f;
- mElapsedTime = 0.f;
- }
- }
-}
-
-bool FpsTracker::Enabled() const
-{
- return mFpsTrackingSeconds > 0.0f;
-}
-
-void FpsTracker::OutputFPSRecord()
-{
- float fps = mFrameCount / mElapsedTime;
- DALI_LOG_FPS("Frame count %.0f, elapsed time %.1fs, FPS: %.2f\n", mFrameCount, mElapsedTime, fps );
-
- struct stat fileStat;
-
- // Check file path
- if( lstat( DALI_TEMP_UPDATE_FPS_FILE, &fileStat ) != 0 )
- {
- return;
- }
-
- if( !S_ISREG( fileStat.st_mode ) )
- {
- return;
- }
-
- // Dumps out the frame rate.
- FILE* outfile = fopen( DALI_TEMP_UPDATE_FPS_FILE, "w" );
- if( outfile )
- {
- char fpsString[10];
- snprintf(fpsString,sizeof(fpsString),"%.2f \n", fps );
- fputs( fpsString, outfile ); // ignore the error on purpose
- fclose( outfile );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
-#define __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/core.h>
-#include <dali/integration-api/gl-abstraction.h>
-
-// INTERNAL INCLUDES
-#include <trigger-event-interface.h>
-#include <trigger-event-factory-interface.h>
-#include <base/interfaces/egl-factory-interface.h>
-#include <base/interfaces/socket-factory-interface.h>
-#include <base/interfaces/performance-interface.h>
-#include <base/interfaces/vsync-monitor-interface.h>
-#include <base/interfaces/trace-interface.h>
-#include <render-surface.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * A class to contain various interfaces provided by the adaptor which
- * can be used by the cross platform parts of adaptor.
- * E.g. any files held in adaptors/base/ directory
- *
- */
-class AdaptorInternalServices
-{
-
-public:
-
- /**
- * @return core
- */
- virtual Dali::Integration::Core& GetCore() = 0;
-
- /**
- * @return platform abstraction
- */
- virtual Dali::Integration::PlatformAbstraction& GetPlatformAbstractionInterface() = 0;
-
- /**
- * @return gles abstraction
- */
- virtual Dali::Integration::GlAbstraction& GetGlesInterface() = 0;
-
- /**
- * @return egl factory
- */
- virtual EglFactoryInterface& GetEGLFactoryInterface() const = 0;
-
- /**
- * Used by update-thread to notify core (main-thread) it has messages to process
- * @return trigger event ProcessCoreEvents
- */
- virtual TriggerEventInterface& GetProcessCoreEventsTrigger() = 0;
-
- /**
- * @return trigger event factory interface
- */
- virtual TriggerEventFactoryInterface& GetTriggerEventFactoryInterface() = 0;
-
- /**
- * @return socket factory interface
- */
- virtual SocketFactoryInterface& GetSocketFactoryInterface() = 0;
-
- /**
- * @return render surface
- */
- virtual RenderSurface* GetRenderSurfaceInterface() = 0;
-
- /**
- * @return vsync monitor interface
- */
- virtual VSyncMonitorInterface* GetVSyncMonitorInterface() = 0;
-
- /**
- * @return performance interface
- */
- virtual PerformanceInterface* GetPerformanceInterface() = 0;
-
- /**
- * @return interface for logging to the kernel ( e.g. using ftrace )
- */
- virtual TraceInterface& GetKernelTraceInterface() = 0;
-
- /**
- * @return system trace interface, e.g. for using Tizen Trace (ttrace) or Android Trace (atrace)
- */
- virtual TraceInterface& GetSystemTraceInterface() = 0;
-
-
-protected:
-
- /**
- * constructor
- */
- AdaptorInternalServices()
- {
- };
-
- /**
- * virtual destructor
- */
- virtual ~AdaptorInternalServices()
- {
- };
-
- // Undefined copy constructor.
- AdaptorInternalServices( const AdaptorInternalServices& );
-
- // Undefined assignment operator.
- AdaptorInternalServices& operator=( const AdaptorInternalServices& );
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_BASE_INDICATOR_INTERFACE_H__
-#define __DALI_INTERNAL_BASE_INDICATOR_INTERFACE_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/actors/actor.h>
-
-// INTERNAL INCLUDES
-#include <window.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-class Adaptor;
-
-/**
- * @brief The Indicator interface.
- * Can be used to draw an indicator graphic generated from the platform as an overlay on
- * top of DALi scene contents.
- */
-class IndicatorInterface
-{
-public:
-
- /**
- * @brief Type of indiciator
- */
- enum Type
- {
- INDICATOR_TYPE_UNKNOWN,
- INDICATOR_TYPE_1,
- INDICATOR_TYPE_2
- };
-
-
-public:
-
- /**
- * @brief observer for listening to indicator events
- */
- class Observer
- {
- public:
- /**
- * @brief Notify the observer if the indicator type changes
- * @param[in] type The new indicator type
- */
- virtual void IndicatorTypeChanged( Type type ) = 0;
-
- /**
- * @brief Notify the observer when the upload has completed.
- * @param[in] indicator The indicator that has finished uploading.
- */
- virtual void IndicatorClosed(IndicatorInterface* indicator) = 0;
-
- /**
- * @brief Notify the observer when the indicator visible status is changed.
- * @param[in] isShowing Whether the indicator is visible.
- */
- virtual void IndicatorVisibilityChanged( bool isVisible ) = 0;
- };
-
-
-public:
-
- /**
- * @brief constructor
- */
- IndicatorInterface() {}
-
- /**
- * @brief Virtual Destructor
- */
- virtual ~IndicatorInterface() {}
-
- /**
- * @brief assign the adaptor to this object
- * @param[in] adaptor
- */
- virtual void SetAdaptor(Adaptor* adaptor) = 0;
-
- /**
- * @brief Get the actor which contains the indicator image. Ensure that the handle is
- * released when no longer needed.
- * Changes from the indicator service will modify the image and resize the actor appropriately.
- * @return The indicator actor.
- */
- virtual Dali::Actor GetActor() = 0;
-
- /**
- * Opens a new connection for the required orientation.
- * @param[in] orientation The new orientation
- */
- virtual void Open( Dali::Window::WindowOrientation orientation ) = 0;
-
- /**
- * Close the current connection. Will respond with Observer::IndicatorClosed()
- * when done.
- * @note, IndicatorClosed() will be called synchronously if there's no update
- * in progress, or asychronously if waiting for SignalUploaded )
- */
- virtual void Close() = 0;
-
- /**
- * Set the opacity mode of the indicator background.
- * @param[in] mode opacity mode
- */
- virtual void SetOpacityMode( Dali::Window::IndicatorBgOpacity mode ) = 0;
-
- /**
- * Set whether the indicator is visible or not.
- * @param[in] visibleMode visible mode for indicator bar.
- * @param[in] forceUpdate true if want to change visible mode forcely
- */
- virtual void SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate = false ) = 0;
-
- /**
- * Check whether the indicator is connected to the indicator service.
- * @return whether the indicator is connected or not.
- */
- virtual bool IsConnected() = 0;
-
- /**
- * Send message to the indicator service.
- * @param[in] messageDomain Message Reference number
- * @param[in] messageId Reference number of the message this message refers to
- * @param[in] data The data to send as part of the message
- * @param[in] size Length of the data, in bytes, to send
- * @return whether the message is sent successfully or not
- */
- virtual bool SendMessage( int messageDomain, int messageId, const void *data, int size ) = 0;
-
-
-};
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
-#define __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <base/interfaces/socket-interface.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * @brief abstract class to create and destroy sockets
- */
-class SocketFactoryInterface
-{
-public:
-
- /**
- * @brief Create a new socket
- * @param protocol network protocol
- * @return true on success, false on failure
- */
- virtual SocketInterface* NewSocket( SocketInterface::Protocol protocol ) = 0;
-
- /**
- * @brief destroy a socket
- * @param[in] socket socket to destroy
- */
- virtual void DestroySocket( SocketInterface* socket ) = 0;
-
-protected:
-
- /**
- * @brief Constructor
- */
- SocketFactoryInterface( )
- {
- }
-
- /**
- * @brief Virtual destructor
- */
- virtual ~SocketFactoryInterface()
- {
- }
-
-private:
-
- // Undefined copy constructor.
- SocketFactoryInterface( const SocketFactoryInterface& );
-
- // Undefined assignment operator.
- SocketFactoryInterface& operator=( const SocketFactoryInterface& );
-
-};
-
-
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_BASE_TRACE_INTERFACE_H__
-#define __DALI_INTERNAL_BASE_TRACE_INTERFACE_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/performance-marker.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Abstract Tracing Interface.
- * Used to log trace messages.
- * E.g. On Linux this may use ftrace
- *
- */
-class TraceInterface
-{
-
-public:
-
- /**
- * Write a trace message
- * @param marker performance marker
- * @param traceMessage trace message
- */
- virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage ) = 0;
-
-protected:
-
- /**
- * Constructor
- */
- TraceInterface()
- {
- }
-
- /**
- * virtual destructor
- */
- virtual ~TraceInterface()
- {
- }
-
- // Undefined copy constructor.
- TraceInterface( const TraceInterface& );
-
- // Undefined assignment operator.
- TraceInterface& operator=( const TraceInterface& );
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "frame-time-stamp.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-FrameTimeStamp::FrameTimeStamp()
-: frame(0),
- microseconds(0),
- bufferIndex(0)
-{
-}
-
-FrameTimeStamp::FrameTimeStamp(unsigned int frame,
- uint64_t microseconds,
- unsigned int bufferIndex)
-: frame( frame ),
- microseconds( microseconds ),
- bufferIndex( bufferIndex )
-{
-}
-
-FrameTimeStamp::FrameTimeStamp( unsigned int bufferIndex )
-: frame( 0 ),
- microseconds( 0 ),
- bufferIndex( bufferIndex )
-{
-}
-
-unsigned int FrameTimeStamp::MicrosecondDiff( const FrameTimeStamp& start,const FrameTimeStamp& end )
-{
- return end.microseconds - start.microseconds;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// STRUCT HEADER
-#include "frame-time-stats.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const float EPSILON = 0.9f; // rolling average = (average * epsilon) + (current * epsilon)
-const float ONE_OVER_MICROSECONDS_TO_SECONDS = 1.f / 1000000.f; ///< microseconds per second
-}
-
-FrameTimeStats::FrameTimeStats()
-: mTotal( 0.f)
-{
- mSamples.Reserve( 16 ); // Fill out a little to avoid early reallocations
-
- Reset();
-}
-
-FrameTimeStats::~FrameTimeStats()
-{
-}
-
-void FrameTimeStats::StartTime( const FrameTimeStamp& timeStamp )
-{
- // check to make sure we don't get 2 start times in a row
- if( mTimeState != WAITING_FOR_START_TIME )
- {
- Reset();
- }
-
- mStart = timeStamp;
- mTimeState = WAITING_FOR_END_TIME;
-}
-
-void FrameTimeStats::EndTime( const FrameTimeStamp& timeStamp )
-{
- if( mTimeState != WAITING_FOR_END_TIME )
- {
- Reset();
- return;
- }
-
- mTimeState = WAITING_FOR_START_TIME;
- mRunCount++;
-
- // frame time in seconds
- unsigned int elapsedTime = FrameTimeStamp::MicrosecondDiff( mStart, timeStamp);
-
- mSamples.PushBack( elapsedTime );
-
- // if the min and max times haven't been set, do that now.
- if( !mMinMaxTimeSet )
- {
- mMin = elapsedTime;
- mMax = elapsedTime;
- mMinMaxTimeSet = true;
- }
- else
- {
- if (elapsedTime < mMin)
- {
- mMin= elapsedTime;
- }
- else if (elapsedTime > mMax)
- {
- mMax = elapsedTime;
- }
- }
-
- mTotal += elapsedTime;
-}
-
-void FrameTimeStats::Reset()
-{
- mTimeState = WAITING_FOR_START_TIME;
- mMinMaxTimeSet = false;
- mMin = 0.f;
- mMax = 0.f;
- mRunCount = 0;
- mSamples.Clear();
-}
-
-float FrameTimeStats::GetMaxTime() const
-{
- return mMax * ONE_OVER_MICROSECONDS_TO_SECONDS;
-}
-
-float FrameTimeStats::GetMinTime() const
-{
- return mMin * ONE_OVER_MICROSECONDS_TO_SECONDS;
-}
-
-float FrameTimeStats::GetTotalTime() const
-{
- return mTotal * ONE_OVER_MICROSECONDS_TO_SECONDS;
-}
-
-unsigned int FrameTimeStats::GetRunCount() const
-{
- return mRunCount;
-}
-
-void FrameTimeStats::CalculateMean( float& meanOut, float& standardDeviationOut ) const
-{
- if( mSamples.Size() > 0 )
- {
- // Mean
- unsigned int sum = 0;
- for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it )
- {
- unsigned int value = *it;
-
- sum += value;
- }
-
- meanOut = static_cast<float>(sum) / mSamples.Size();
-
- // Variance
- float variance = 0.0f;
- for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it )
- {
- unsigned int value = *it;
-
- float difference = static_cast<float>(value) - meanOut;
-
- variance += difference * difference;
- }
-
- variance /= mSamples.Size();
-
- // Standard deviation
- standardDeviationOut = sqrtf( variance );
-
- meanOut *= ONE_OVER_MICROSECONDS_TO_SECONDS;
- standardDeviationOut *= ONE_OVER_MICROSECONDS_TO_SECONDS;
- }
- else
- {
- meanOut = 0.0f;
- standardDeviationOut = 0.0f;
- }
-}
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
-#define __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/frame-time-stamp.h>
-#include <dali/public-api/common/dali-vector.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Used to get statistics about time stamps over a period of time.
- * E.g. the min, max, total and average time spent inside two markers,
- * such as UPDATE_START and UPDATE_END
- */
-struct FrameTimeStats
-{
- /**
- * Constructor
- */
- FrameTimeStats();
-
- /**
- * Destructor, not intended as a base class
- */
- ~FrameTimeStats();
-
- /**
- * Timer start time
- * @param timeStamp time stamp
- */
- void StartTime( const FrameTimeStamp& timeStamp );
-
- /**
- * Timer end time
- * @param timeStamp time stamp
- */
- void EndTime( const FrameTimeStamp& timeStamp );
-
- /**
- * Reset all internal counters / state except total time.
- */
- void Reset();
-
- /**
- * @return maximum time in seconds
- */
- float GetMaxTime() const;
-
- /**
- * @return minimum time in seconds
- */
- float GetMinTime() const;
-
- /**
- * @return total time in second
- */
- float GetTotalTime() const;
-
- /**
- * Get how many times the timer has been started /stopped
- */
- unsigned int GetRunCount() const;
-
- /**
- * Calculate the mean and standard deviation
- *
- * @param[out] mean The return mean value
- * @param[out] standardDeviation The return standard deviation value
- */
- void CalculateMean( float& meanOut, float& standardDeviationOut ) const;
-
-private:
-
- /**
- * internal time state.
- */
- enum TimeState
- {
- WAITING_FOR_START_TIME, ///< waiting for start time marker
- WAITING_FOR_END_TIME ///< waiting for end time marker
- };
-
- typedef Dali::Vector< unsigned int > Samples;
- Samples mSamples;
-
- unsigned int mMin; ///< current minimum value in microseconds
- unsigned int mMax; ///< current maximum value in microseconds
- unsigned int mTotal; ///< current total in in microseconds
- unsigned int mRunCount; ///< how many times the timer has been start / stopped
- FrameTimeStamp mStart; ///< start time stamp, to calculate the diff
- TimeState mTimeState:1; ///< time state
- bool mMinMaxTimeSet:1; ///< whether the min-max values have been configured
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
-
+++ /dev/null
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "automation.h"
-
-// EXTERNAL INCLUDES
-#include <sstream>
-#include <iomanip>
-#include <stdio.h>
-#include <dali/public-api/dali-core.h>
-#include <dali/integration-api/debug.h>
-
-
-namespace // un-named namespace
-{
-
-const unsigned int MAX_SET_PROPERTY_STRING_LENGTH = 256; ///< maximum length of a set property command
-
-class JsonPropertyValue
-{
-public:
- JsonPropertyValue( const std::string& str )
- {
- std::size_t strLength = str.length();
-
- mString.reserve( strLength );
- for( std::size_t i = 0; i < strLength; ++i )
- {
- const char c = str[i];
- if( (c != '[') && c != ']')
- {
- mString.push_back( c );
- }
- }
-
- }
- std::string GetString() const
- {
- return mString;
- }
- float GetFloat() const
- {
- return atof( mString.c_str() );
- }
- int GetInt()
- {
- return atoi( mString.c_str() );
- }
- bool GetBoolean()
- {
- return (GetInt() != 0);
- }
-
- Dali::Vector2 GetVector2()
- {
- Dali::Vector2 vec2;
-
- int count = sscanf( mString.c_str(),"%f,%f",&vec2.x,&vec2.y );
- if( count != 2 )
- {
- DALI_LOG_ERROR("Bad format\n");
- }
- return vec2;
- }
-
- Dali::Vector3 GetVector3()
- {
- Dali::Vector3 vec3;
-
- int count = sscanf( mString.c_str(),"%f,%f,%f",&vec3.x,&vec3.y,&vec3.z );
- if( count != 3 )
- {
- DALI_LOG_ERROR("Bad format\n");
- }
- return vec3;
- }
-
- Dali::Vector4 GetVector4()
- {
- Dali::Vector4 vec4;
-
- int count = sscanf( mString.c_str(),"%f,%f,%f,%f", &vec4.x, &vec4.y, &vec4.z, &vec4.w );
- if( count != 4 )
- {
- DALI_LOG_ERROR("Bad format\n");
- }
- return vec4;
- }
-
-private:
- std::string mString;
-
-};
-
-void SetProperty( Dali::Handle handle, int propertyId, JsonPropertyValue& propertyValue )
-{
- Dali::Property::Type type = handle.GetPropertyType( propertyId );
- switch( type )
- {
- case Dali::Property::FLOAT:
- {
- float val = propertyValue.GetFloat();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- case Dali::Property::INTEGER:
- {
- int val = propertyValue.GetInt();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- case Dali::Property::BOOLEAN:
- {
- bool val = propertyValue.GetBoolean();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- case Dali::Property::STRING:
- {
- std::string str = propertyValue.GetString();
- handle.SetProperty( propertyId, Dali::Property::Value( str ) );
- break;
- }
- case Dali::Property::VECTOR2:
- {
- Dali::Vector2 val = propertyValue.GetVector2();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- case Dali::Property::VECTOR3:
- {
- Dali::Vector3 val = propertyValue.GetVector3();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- case Dali::Property::VECTOR4:
- {
- Dali::Vector4 val = propertyValue.GetVector4();
- handle.SetProperty( propertyId, Dali::Property::Value( val ) );
- break;
- }
- default:
- {
- break;
- }
- }
-}
-
-int SetProperties( const std::string& setPropertyMessage )
-{
- std::istringstream iss( setPropertyMessage );
- std::string token;
- getline( iss, token, '|' ); // swallow command name
- while( getline( iss, token, '|' ) )
- {
- std::string actorId, propName, propValue;
- if( token.compare( "---" ) != 0 )
- {
- std::istringstream propss( token );
- getline( propss, actorId, ';' );
- getline( propss, propName, ';' );
- getline( propss, propValue );
-
- Dali::Actor root = Dali::Stage::GetCurrent().GetRootLayer();
- int id = atoi( actorId.c_str() );
- Dali::Actor a = root.FindChildById( id );
- if( a )
- {
- // lookup by name for custom properties
- int propId = a.GetPropertyIndex( propName );
- if( propId > 0 )
- {
- JsonPropertyValue pv( propValue );
- SetProperty( a, propId, pv );
- }
-
- }
- }
- }
-
- return 0;
-}
-
-
-}; // un-named namespace
-
-inline std::string Quote( const std::string& in )
-{
- return (std::string( "\"" ) + in + std::string( "\"" ));
-}
-
-template<class T>
-std::string ToString( T i )
-{
- std::stringstream ss;
- std::string s;
- ss << i;
- s = ss.str();
-
- return s;
-}
-
-
-// currently rotations are output in Euler format ( may change)
-void AppendPropertyNameAndValue( Dali::Handle handle, int propertyIndex, std::ostringstream& outputStream)
-{
- // get the property name and the value as a string
- std::string propertyName( handle.GetPropertyName( propertyIndex ) );
-
- // Apply quotes around the property name
- outputStream << "\"" << propertyName << "\"" << ",";
-
- // Convert value to a string
- std::ostringstream valueStream;
- Dali::Property::Value value = handle.GetProperty( propertyIndex );
- valueStream << value;
- std::string valueString = valueStream.str();
-
- if( value.GetType() == Dali::Property::STRING )
- {
- // Escape the string (to ensure valid json)
- // Write out quotes, escapes and control characters using unicode syntax \uXXXX
- std::ostringstream escapedValue;
- for( std::string::iterator c = valueString.begin() ; c != valueString.end(); ++c )
- {
- if( *c == '"' )
- {
- escapedValue << "\\\"";
- }
- else if( *c == '\\' )
- {
- escapedValue << "\\\\";
- }
- else if( '\x00' <= *c && *c <= '\x1f' )
- {
- escapedValue << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(*c);
- }
- else
- {
- escapedValue << *c;
- }
- }
-
- valueString = escapedValue.str();
- }
-
- outputStream << "\"" << valueString << "\"";
-}
-
-bool ExcludeProperty( int propIndex )
-{
- return (propIndex == Dali::Actor::Property::NAME ||
-
- // all of these are repeat properties of values in vectors....
- // We don't really need these in the UI
- propIndex == Dali::Actor::Property::ANCHOR_POINT_X || propIndex == Dali::Actor::Property::ANCHOR_POINT_Y || propIndex == Dali::Actor::Property::ANCHOR_POINT_Z || propIndex == Dali::Actor::Property::PARENT_ORIGIN_X
- || propIndex == Dali::Actor::Property::PARENT_ORIGIN_Y || propIndex == Dali::Actor::Property::PARENT_ORIGIN_Z || propIndex == Dali::Actor::Property::COLOR_RED || propIndex == Dali::Actor::Property::COLOR_GREEN
- || propIndex == Dali::Actor::Property::COLOR_BLUE || propIndex == Dali::Actor::Property::COLOR_ALPHA|| propIndex == Dali::Actor::Property::POSITION_X || propIndex == Dali::Actor::Property::POSITION_Y
- || propIndex == Dali::Actor::Property::POSITION_Z|| propIndex == Dali::Actor::Property::SIZE_WIDTH|| propIndex == Dali::Actor::Property::SIZE_HEIGHT || propIndex == Dali::Actor::Property::SCALE_X || propIndex == Dali::Actor::Property::SCALE_Y
- || propIndex == Dali::Actor::Property::SCALE_Z || propIndex == Dali::Actor::Property::SIZE_DEPTH);
-}
-
-std::string DumpJson( Dali::Actor actor, int level )
-{
- // All the information about this actor
- std::ostringstream msg;
- msg << "{ " << Quote( "Name" ) << " : " << Quote( actor.GetName() ) << ", " << Quote( "level" ) << " : " << level << ", " << Quote( "id" ) << " : " << actor.GetId() << ", " << Quote( "IsVisible" )
- << " : " << actor.IsVisible() << ", " << Quote( "IsSensitive" ) << " : " << actor.IsSensitive();
-
- msg << ", " << Quote( "properties" ) << ": [ ";
-
- Dali::Property::IndexContainer indices;
- actor.GetPropertyIndices( indices );
-
- Dali::Property::IndexContainer::Iterator iter = indices.Begin();
- int numCustom = 0;
- for( ; iter != indices.End() ; iter++ )
- {
- int i = *iter;
- if( !ExcludeProperty( i ) )
- {
- if( numCustom++ != 0 )
- {
- msg << ", ";
- }
- msg << "[";
-
- AppendPropertyNameAndValue( actor, i,msg );
-
- msg << "]";
- }
- }
- msg << "]";
- msg << ", " << Quote( "children" ) << " : [ ";
-
- // Recursively dump all the children as well
- for( unsigned int i = 0 ; i < actor.GetChildCount() ; ++i )
- {
- if( i )
- {
- msg << " , ";
- }
- msg << DumpJson( actor.GetChildAt( i ), level + 1 );
- }
- msg << "] }";
-
- return msg.str();
-}
-
-std::string GetActorTree()
-{
- Dali::Actor actor = Dali::Stage::GetCurrent().GetRootLayer();
- std::string str = DumpJson( actor, 0 );
- return str;
-}
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Automation
-{
-
-void SetProperty( const std::string& message )
-{
- // check the set property length is within range
- if( message.length() > MAX_SET_PROPERTY_STRING_LENGTH )
- {
- DALI_LOG_ERROR("SetProperty message length too long, size = %ul\n", message.length());
- return;
- }
-
- SetProperties( message );
-}
-
-void DumpScene( unsigned int clientId, ClientSendDataInterface* sendData )
-{
- char buf[32];
- std::string json = GetActorTree();
- int length = json.length();
- snprintf( buf, 32, "%d\n", length );
- std::string header( buf );
- json = buf + json;
- sendData->SendData( json.c_str(), json.length(), clientId );
-}
-
-} // namespace Automation
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_AUTOMATION_H__
-#define __DALI_INTERNAL_ADAPTOR_AUTOMATION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// EXTERNAL INCLUDES
-#include <string>
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/networking/client-send-data-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief The automation functions allow a way to control Dali via a network socket.
- *
- * The functions must be called from the event thread only.
- *
- * Any functions which require a response to be sent back to the network client
- * use the ClientSendDataInterface interface.
-
- * E.g.
- * Dali network client thread <---- "dump_scene" from network
- * Dali main thread "json data" -----> network
- *
- */
-namespace Automation
-{
-
-/**
- * @brief Sets properties on an Actor.
- * No ClientSendDataInterface required, as no response is sent back
- * @param[in] message set property message
- */
-void SetProperty( const std::string& message );
-
-
-/**
- * @brief Dumps the actor tree to the client
- * @param[in] clientId unique network client id
- * @param[in] sendData interface to transmit data to the client
- */
-void DumpScene( unsigned int clientId, ClientSendDataInterface* sendData );
-
-
-} // namespace Automation
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "network-performance-client.h"
-
-// EXTERNAL INCLUDES
-#include <stdio.h>
-#include <string>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/socket-interface.h>
-#include <base/performance-logging/networking/network-performance-protocol.h>
-#include <base/performance-logging/networking/event/automation.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const float MICROSECONDS_TO_SECOND = 1e-6;
-const char UNKNOWN_CMD[]= "Command or parameter invalid, type help for list of commands\n";
-
-
-/**
- * helper class to store data along with the automation callback.
- */
-class AutomationCallback: public CallbackBase
-{
-public:
-
- /**
- * instead of using templates, or having different callback classes for each callback
- * we use a command id that decides which static function to call on the Automation class.
- */
- enum CommandId
- {
- UNKNOWN_COMMAND,
- SET_PROPERTY,
- DUMP_SCENE
- };
-
- AutomationCallback( unsigned int clientId, ClientSendDataInterface& sendDataInterface )
- :CallbackBase( reinterpret_cast< void* >( this ),
- NULL, // we get the dispatcher to call function directly
- reinterpret_cast< CallbackBase::Dispatcher>( &AutomationCallback::Dispatcher) ),
- mSendDataInterface( sendDataInterface ),
- mCommandId( UNKNOWN_COMMAND ),
- mClientId( clientId )
- {}
-
- void AssignSetPropertyCommand( std::string setPropertyCommand )
- {
- mCommandId = SET_PROPERTY;
- mPropertyCommand = setPropertyCommand;
- }
- void AssignDumpSceneCommand()
- {
- mCommandId = DUMP_SCENE;
- }
-
- void RunCallback()
- {
- switch( mCommandId )
- {
- case SET_PROPERTY:
- {
- Automation::SetProperty( mPropertyCommand );
- break;
- }
- case DUMP_SCENE:
- {
- Automation::DumpScene( mClientId, &mSendDataInterface);
- break;
- }
- default:
- {
- DALI_ASSERT_DEBUG( 0 && "Unknown command");
- break;
- }
- }
- }
- static void Dispatcher( CallbackBase& base )
- {
- AutomationCallback& automationCallback( static_cast< AutomationCallback& >( base) );
- automationCallback.RunCallback();
- }
-
-private:
-
- std::string mPropertyCommand; ///< property command
- ClientSendDataInterface& mSendDataInterface; ///< Abstract client send data interface
- CommandId mCommandId; ///< command id
- const unsigned int mClientId; ///< client id
-};
-
-} // unnamed namespace
-
-NetworkPerformanceClient::NetworkPerformanceClient( pthread_t* thread,
- SocketInterface *socket,
- unsigned int clientId,
- TriggerEventFactoryInterface& triggerEventFactory,
- ClientSendDataInterface& sendDataInterface,
- SocketFactoryInterface& socketFactory )
-: mThread( thread ),
- mSocket( socket ),
- mMarkerBitmask( PerformanceMarker::FILTERING_DISABLED ),
- mTriggerEventFactory( triggerEventFactory ),
- mSendDataInterface( sendDataInterface ),
- mSocketFactoryInterface( socketFactory ),
- mClientId( clientId ),
- mConsoleClient(false)
-{
-
-}
-
-NetworkPerformanceClient::~NetworkPerformanceClient()
-{
- if( mSocket->SocketIsOpen() )
- {
- mSocket->CloseSocket();
- }
- mSocketFactoryInterface.DestroySocket( mSocket );
-}
-
-unsigned int NetworkPerformanceClient::GetId() const
-{
- return mClientId;
-}
-
-SocketInterface& NetworkPerformanceClient::GetSocket()
-{
- return *mSocket;
-}
-
-bool NetworkPerformanceClient::WriteSocket( const void* buffer, unsigned int bufferSizeInBytes )
-{
- return mSocket->Write( buffer, bufferSizeInBytes );
-}
-
-bool NetworkPerformanceClient::TransmitMarker( const PerformanceMarker& marker, const char* const description )
-{
- if( ! marker.IsFilterEnabled( mMarkerBitmask ) )
- {
- return true;
- }
- if( mConsoleClient )
- {
- // write out the time stamp
- char buffer[64];
- double usec = marker.GetTimeStamp().microseconds;
- int size = snprintf( buffer, sizeof(buffer),"%.6f (seconds), %s\n",
- usec * MICROSECONDS_TO_SECOND,
- description );
-
- return mSocket->Write( buffer, size );
-
- }
-
-
- // todo serialize the data
- return false;
-}
-
-void NetworkPerformanceClient::ExitSelect()
-{
- mSocket->ExitSelect();
-}
-
-pthread_t* NetworkPerformanceClient::GetThread()
-{
- return mThread;
-}
-
-void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int bufferSizeInBytes )
-{
- // if connected via console, then strip off the carriage return, and switch to console mode
- if( buffer[ bufferSizeInBytes - 1] == '\n')
- {
- buffer[ bufferSizeInBytes - 1] = 0;
- mConsoleClient = true;
- }
- unsigned int param(0);
- std::string stringParam;
- PerformanceProtocol::CommandId commandId( PerformanceProtocol::UNKNOWN_COMMAND );
-
- bool ok = PerformanceProtocol::GetCommandId( buffer, bufferSizeInBytes, commandId, param, stringParam );
- if( !ok )
- {
- WriteSocket( UNKNOWN_CMD, sizeof(UNKNOWN_CMD) );
- return;
- }
- std::string response;
-
- switch( commandId )
- {
- case PerformanceProtocol::HELP_MESSAGE:
- {
- response = PerformanceProtocol::GetHelpMessage();
- break;
- }
-
- case PerformanceProtocol::ENABLE_TIME_MARKER_BIT_MASK:
- {
- mMarkerBitmask = static_cast< PerformanceMarker::MarkerFilter >( param );
- response = "enable time marker ";
- break;
- }
-
- case PerformanceProtocol::DUMP_SCENE_GRAPH:
- {
- // this needs to be run on the main thread, use the trigger event....
- AutomationCallback* callback = new AutomationCallback( mClientId, mSendDataInterface );
- callback->AssignDumpSceneCommand();
-
- // create a trigger event that automatically deletes itself after the callback has run in the main thread
- TriggerEventInterface *interface = mTriggerEventFactory.CreateTriggerEvent( callback, TriggerEventInterface::DELETE_AFTER_TRIGGER );
-
- // asynchronous call, the call back will be run sometime later on the main thread
- interface->Trigger();
- break;
- }
-
- case PerformanceProtocol::SET_PROPERTIES:
- {
- // this needs to be run on the main thread, use the trigger event....
- AutomationCallback* callback = new AutomationCallback( mClientId, mSendDataInterface );
- callback->AssignSetPropertyCommand( stringParam );
-
- // create a trigger event that automatically deletes itself after the callback has run in the main thread
- TriggerEventInterface *interface = mTriggerEventFactory.CreateTriggerEvent( callback, TriggerEventInterface::DELETE_AFTER_TRIGGER );
-
- // asynchronous call, the call back will be run sometime later on the main thread
- interface->Trigger();
- break;
- }
-
- case PerformanceProtocol::LIST_METRICS_AVAILABLE:
- case PerformanceProtocol::ENABLE_METRIC:
- case PerformanceProtocol::DISABLE_METRIC:
- {
- response="Metrics currently not supported";
- break;
- }
- default:
- {
- response = UNKNOWN_CMD;
- break;
- }
- }
- if( ! response.empty() )
- {
- // add a carriage return for console clients
- if( mConsoleClient )
- {
- response+="\n";
- }
- WriteSocket( response.c_str(), response.length() );
- }
-}
-
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H__
-#define __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <pthread.h>
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/performance-marker.h>
-#include <trigger-event-factory-interface.h>
-#include <base/performance-logging/networking/client-send-data-interface.h>
-#include <base/interfaces/socket-factory-interface.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief Network Performance client
- *
- * Every time a client connects to Dali, a NetworkPerformanceClient object is created.
- * It is responsible for processing incoming commands, and storing the client state
- * (e.g. what performance markers it wants).
- *
- * Certain commands such as dump-scene need to be run on the main Dali event thread.
- * To achieve this, a trigger event is used which executes a function on the main thread.
- * The sendDataInterface is then used with the client id to transmit the data to the client.
- * The reason for using a client id is because the client
- * can be deleted in between receiving a command and sending a response.
- * E.g.
- * NetworkPerformanceClient (own thread, id 5) <--- Dump Scene Command
- * delete NetworkPerformanceClient <--- Connection closed
- * MainThread. Send scene data to client 5. Client 5 has been deleted so don't send the data.
- *
- */
-class NetworkPerformanceClient
-{
-public:
-
- /**
- * @brief Constructor
- * @param thread thread pointer
- * @param socket socket interface
- * @param clientId unique client id
- * @param triggerEventFactory used to create trigger events
- * @param sendDataInterface used to send data to the socket from main thread
- * @param SocketFactoryInterface used to delete the socket when the client is destroyed
- */
- NetworkPerformanceClient( pthread_t* thread,
- SocketInterface *socket,
- unsigned int clientId,
- TriggerEventFactoryInterface& triggerEventFactory,
- ClientSendDataInterface& sendDataInterface,
- SocketFactoryInterface& socketFactory );
-
- /**
- * @brief Destructor
- */
- ~NetworkPerformanceClient();
-
- /**
- * @return client unique id
- */
- unsigned int GetId() const;
-
- /**
- * @return socket interface
- */
- SocketInterface& GetSocket();
-
- /**
- * @brief Write data to a socket. Can be called from any thread
- * @copydoc Dali::SocketInterface::Send
- */
- bool WriteSocket( const void* buffer, unsigned int bufferSizeInBytes );
-
- /**
- * @brief Process a command
- * @param buffer pointer to command data
- * @param bufferSizeInBytes how big the buffer is in bytes
- */
- void ProcessCommand( char* buffer, unsigned int bufferSizeInBytes );
-
- /**
- * @brief Write a marker to the socket, if this client is filtering this marker.
- * @param marker
- */
- bool TransmitMarker( const PerformanceMarker& marker, const char* const description );
-
- /**
- * @brief If the client is waiting inside a select statement, this will cause it
- * to break out.
- */
- void ExitSelect();
-
- /**
- * @brief get the thread running the client
- * @return thread pointer
- */
- pthread_t* GetThread();
-
-private:
-
- pthread_t* mThread; ///< thread for the client
- SocketInterface* mSocket; ///< socket interface
- PerformanceMarker::MarkerFilter mMarkerBitmask; ///< What markers are currently filtered
- TriggerEventFactoryInterface& mTriggerEventFactory; ///< Trigger event factory
- ClientSendDataInterface& mSendDataInterface; ///< used to send data to a client from the main event thread
- SocketFactoryInterface& mSocketFactoryInterface; ///< used to delete the socket
- unsigned int mClientId; ///< unique client id
- bool mConsoleClient; ///< if connected via a console then all responses are in ASCII, not binary packed data.
-
-};
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-
-// CLASS HEADER
-#include "network-performance-protocol.h"
-
-// EXTERNAL INCLUDES
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-namespace Dali
-{
-
-namespace PerformanceProtocol
-{
-
-namespace
-{
-
-/**
- * Command parameter type
- */
-enum PARAMETER_TYPE
-{
- NO_PARAMS,
- UNSIGNED_INT,
- STRING
-};
-
-/**
- * Command information structure
- */
-struct CommandInfo
-{
- CommandId cmdId;
- CommandString cmdString;
- PARAMETER_TYPE paramType;
-};
-
-/**
- * Command lookup table
- */
-CommandInfo CommandLookup[]=
-{
- { HELP_MESSAGE , "help" ,NO_PARAMS },
- { ENABLE_METRIC , "enable_metric" ,UNSIGNED_INT },
- { DISABLE_METRIC , "disable_metric" ,UNSIGNED_INT },
- { LIST_METRICS_AVAILABLE , "list_metrics" ,NO_PARAMS },
- { ENABLE_TIME_MARKER_BIT_MASK, "set_marker", UNSIGNED_INT },
- { DUMP_SCENE_GRAPH , "dump_scene" ,NO_PARAMS },
- { SET_PROPERTIES , "set_properties" ,STRING },
- { UNKNOWN_COMMAND , "unknown" ,NO_PARAMS }
-};
-const unsigned int CommandLookupLength = sizeof( CommandLookup ) /sizeof( CommandInfo );
-
-#define GREEN "\033[01;32m"
-#define NORMAL "\e[m"
-#define PARAM "\033[22;32m"
-#define YELLOW "\033[01;33m"
-
-const char* const helpMsg =
- YELLOW
- "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
- " Dali performance console \n"
- "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" NORMAL
- GREEN " list_metrics " NORMAL " - list available metrics\n"
- GREEN " enable_metric " PARAM " metricId" NORMAL " - enable a metric \n"
- GREEN " disable_metric " PARAM " metricId" NORMAL " - disable a metric\n\n"
- GREEN " set_marker " PARAM " value " NORMAL "-output Dali markers\n"
- " : Bit 0 = V_SYNC (1)\n"
- " : Bit 1 = Update task (2)\n"
- " : Bit 2 = Render task (4) \n"
- " : Bit 3 = Event Processing task (8)\n"
- " : Bit 4 = SwapBuffers (16)\n"
- " : Bit 5 = Life cycle events (32)\n"
- " : Bit 6 = Resource event (64)\n"
- "\n"
- GREEN " set_properties " NORMAL " - set an actor property command. Format:\n\n"
- GREEN " set_properties " PARAM "|ActorIndex;Property;Value|" NORMAL ", e.g: \n"
- GREEN " set_properties " PARAM "|178;Size;[ 144.0, 144.0, 144.0 ]|178;Color;[ 1.0, 1,0, 1.0 ]|\n"
- "\n"
- GREEN " dump_scene" NORMAL " - dump the current scene in json format\n";
-
-} // un-named namespace
-
-bool GetCommandId( const char* const commandString, unsigned int lengthInBytes, CommandId& commandId, unsigned int& intParam, std::string& stringParam )
-{
- commandId = UNKNOWN_COMMAND;
- intParam = 0;
-
- // the command list is small so just do a O(n) search for the commandID.
- for( unsigned int i = 0 ; i < CommandLookupLength; ++i )
- {
- if( strncmp( commandString, CommandLookup[i].cmdString ,strlen(CommandLookup[i].cmdString )) == 0 )
- {
- commandId = CommandLookup[i].cmdId;
-
- // if the command has a parameter read it
- if( CommandLookup[i].paramType == UNSIGNED_INT)
- {
- int count = sscanf(commandString,"%*s %d",&intParam);
- if( count != 1 )
- {
- // missing parameter
- return false;
- }
- }
- else if (CommandLookup[i].paramType == STRING )
- {
- char* charParam( NULL );
- // allocates the character array
- int count = sscanf(commandString,"%*s %ms",&charParam);
- if( count != 1 )
- {
- // missing parameter
- return false;
- }
- stringParam = std::string( charParam);
- free(charParam);
- }
- return true;
- }
- }
- // not found
- return false;
-}
-
-bool GetCommandString( CommandId commandId, CommandString& commandString )
-{
- for( unsigned int i = 0; i < CommandLookupLength; ++i)
- {
- if( CommandLookup[ i ].cmdId == commandId )
- {
- strncpy( commandString, CommandLookup[ i ].cmdString, strlen(CommandLookup[ i ].cmdString) );
- return true;
- }
- }
- strncpy( commandString, CommandLookup[ UNKNOWN_COMMAND ].cmdString, MAX_COMMAND_STRING_LENGTH);
- return false;
-}
-
-const char* const GetHelpMessage()
-{
- return helpMsg;
-}
-
-
-} // namespace PerformanceProtocol
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "network-performance-server.h"
-
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/performance-marker.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // un-named namespace
-{
-const unsigned int SERVER_PORT = 3031;
-const unsigned int MAXIMUM_PORTS_TO_TRY = 10; ///< if port in use, try up to SERVER_PORT + 10
-const unsigned int CONNECTION_BACKLOG = 2; ///< maximum length of the queue of pending connections.
-const unsigned int SOCKET_READ_BUFFER_SIZE = 4096;
-typedef Vector< NetworkPerformanceClient*> ClientList;
-
-/**
- * POD passed to client thread on startup
- */
-struct ClientThreadInfo
-{
- NetworkPerformanceServer* server;
- NetworkPerformanceClient* client;
-};
-}
-
-NetworkPerformanceServer::NetworkPerformanceServer( AdaptorInternalServices& adaptorServices,
- const EnvironmentOptions& logOptions )
-: mTriggerEventFactory( adaptorServices.GetTriggerEventFactoryInterface() ),
- mSocketFactory( adaptorServices.GetSocketFactoryInterface() ),
- mLogOptions( logOptions ),
- mServerThread( 0 ),
- mListeningSocket( NULL ),
- mClientUniqueId( 0 ),
- mClientCount( 0 ),
- mLogFunctionInstalled( false )
-{
-}
-
-NetworkPerformanceServer::~NetworkPerformanceServer()
-{
- Stop();
-
- if( mLogFunctionInstalled )
- {
- mLogOptions.UnInstallLogFunction();
- }
-}
-
-void NetworkPerformanceServer::Start()
-{
- // start a thread to listen for incoming connection requests
- if (! mServerThread )
- {
- if( mListeningSocket )
- {
- mSocketFactory.DestroySocket( mListeningSocket );
- }
- mListeningSocket = mSocketFactory.NewSocket( SocketInterface::TCP);
- mListeningSocket->ReuseAddress( true );
-
- bool bound = false;
- unsigned int basePort = 0;
-
- // try a small range of ports, so if multiple Dali apps are running you can select
- // which one to connect to
- while( !bound && ( basePort < MAXIMUM_PORTS_TO_TRY ))
- {
- bound = mListeningSocket->Bind( SERVER_PORT + basePort );
- if( !bound )
- {
- basePort++;
- }
- }
- if(!bound )
- {
- DALI_LOG_ERROR("Failed to bind to a port \n");
- return;
- }
-
- mListeningSocket->Listen( CONNECTION_BACKLOG );
-
- // start a thread which will block waiting for new connections
- int error = pthread_create( &mServerThread, NULL, ConnectionListenerFunc, this );
- DALI_ASSERT_ALWAYS( !error && "pthread create failed" );
-
- Dali::Integration::Log::LogMessage(Integration::Log::DebugInfo, "~~~ NetworkPerformanceServer started on port %d ~~~ \n", SERVER_PORT + basePort);
-
- }
-}
-void NetworkPerformanceServer::Stop()
-{
- if( !mServerThread )
- {
- return;
- }
-
- if( mListeningSocket )
- {
- // close the server thread to prevent any new connections
- mListeningSocket->ExitSelect();
- }
-
- // wait for the thread to exit.
- void* exitValue;
- pthread_join( mServerThread, &exitValue );
-
- if( mListeningSocket )
- {
- // close the socket
- mListeningSocket->CloseSocket();
- }
-
- mSocketFactory.DestroySocket( mListeningSocket );
-
- mListeningSocket = NULL;
-
- // this will tell all client threads to quit
- StopClients();
-
-}
-
-bool NetworkPerformanceServer::IsRunning() const
-{
- if (mServerThread )
- {
- return true;
- }
- return false;
-}
-
-void NetworkPerformanceServer::ClientThread( NetworkPerformanceClient* client )
-{
- mClientCount++;
-
- SocketInterface& socket( client->GetSocket() );
-
- for( ;; )
- {
- SocketInterface::SelectReturn ret = socket.Select();
-
- if( ret == SocketInterface::DATA_AVAILABLE )
- {
- // Read
- char buffer[ SOCKET_READ_BUFFER_SIZE ];
- unsigned int bytesRead;
-
- bool ok = socket.Read( buffer, sizeof( buffer ) , bytesRead);
- if( ok && ( bytesRead > 0) )
- {
- client->ProcessCommand( buffer, bytesRead );
- }
- else // if bytesRead == 0, then client closed connection, if ok == false then an error
- {
- DeleteClient( client );
- return;
- }
- }
- else // ret == QUIT or ERROR
- {
- DeleteClient( client);
- return;
- }
- }
-}
-
-void NetworkPerformanceServer::ConnectionListener()
-{
- // install Dali logging function for this thread
- if( !mLogFunctionInstalled )
- {
- mLogOptions.InstallLogFunction();
- mLogFunctionInstalled = true;
- }
-
- for( ;; )
- {
- // this will block, waiting for a client to connect
- // or for mListeningSocket->ExitSelect() to be called
-
- SocketInterface::SelectReturn ret = mListeningSocket->Select();
-
- if( ret == SocketInterface::DATA_AVAILABLE )
- {
- SocketInterface* clientSocket = mListeningSocket->Accept();
-
- // new connection made, spawn a thread to handle it
- pthread_t* clientThread = new pthread_t();
-
- NetworkPerformanceClient* client = AddClient( clientSocket, clientThread );
-
- ClientThreadInfo* info = new ClientThreadInfo;
- info->client = client;
- info->server = this;
-
- int error = pthread_create( clientThread, NULL, ClientThreadFunc, info );
- DALI_ASSERT_ALWAYS( !error && "pthread create failed" );
-
- }
- else // ret == SocketInterface::QUIT or SocketInterface::ERROR
- {
- return;
- }
- }
-}
-
-void* NetworkPerformanceServer::ClientThreadFunc( void* data )
-{
- ClientThreadInfo* info = static_cast<ClientThreadInfo*>( data );
- info->server->ClientThread( info->client );
- delete info;
- return NULL;
-}
-
-NetworkPerformanceClient* NetworkPerformanceServer::AddClient( SocketInterface* clientSocket, pthread_t* clientThread )
-{
- // This function is only called from the listening thread
- NetworkPerformanceClient* client= new NetworkPerformanceClient( clientThread,
- clientSocket,
- mClientUniqueId++,
- mTriggerEventFactory,
- *this,
- mSocketFactory);
-
- // protect the mClients list which can be accessed from multiple threads.
- Mutex::ScopedLock lock( mClientListMutex );
-
- mClients.PushBack( client );
-
- return client;
-}
-
-void NetworkPerformanceServer::DeleteClient( NetworkPerformanceClient* client )
-{
- // protect the mClients list while modifying
- Mutex::ScopedLock lock( mClientListMutex );
-
- // remove from the list, and delete it
- for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter )
- {
- if( (*iter) == client )
- {
- mClients.Erase( iter );
- delete client;
-
- // if there server is shutting down, it waits for client count to hit zero
- mClientCount--;
-
- return;
- }
- }
-}
-
-void NetworkPerformanceServer::SendData( const char* const data, unsigned int bufferSizeInBytes,unsigned int clientId )
-{
- if( ! mClientCount )
- {
- return;
- }
-
- // prevent clients been added / deleted while transmiting data
- Mutex::ScopedLock lock( mClientListMutex );
-
- for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter )
- {
- NetworkPerformanceClient* client = (*iter);
- if( client->GetId() == clientId )
- {
- client->WriteSocket(data ,bufferSizeInBytes);
- return;
- }
- }
-}
-
-void NetworkPerformanceServer::TransmitMarker( const PerformanceMarker& marker, const char* const description )
-{
- if( ! IsRunning() )
- {
- return;
- }
- // prevent clients been added / deleted while transmiting data
- Mutex::ScopedLock lock( mClientListMutex );
-
- for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter )
- {
- NetworkPerformanceClient* client = (*iter);
- client->TransmitMarker( marker, description );
- }
-}
-
-
-void NetworkPerformanceServer::StopClients()
-{
- // prevent clients been added / deleted while stopping all clients
- Mutex::ScopedLock lock( mClientListMutex );
-
- for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter )
- {
- NetworkPerformanceClient* client = (*iter);
- // stop the client from waiting for new commands, and exit from it's thread
- client->ExitSelect();
- }
-}
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
-#define __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <pthread.h>
-#include <dali/devel-api/threading/mutex.h>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-#include <base/performance-logging/networking/network-performance-client.h>
-#include <base/interfaces/adaptor-internal-services.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class SocketInterface;
-class PerformanceMarker;
-
-/**
- * @brief The class listens for incoming connections on a dedicated thread.
- *
- * When a new connection is established a client thread is spawned to
- * handle that connection, along with a NetworkPerformanceClient object.
- * The NetworkPerformanceClient object performs processing of incoming
- * commands and holds the per-client state information for performance monitoring.
- *
- * Server->Start()
- * - Open socket
- * - Spawns a thread to listen for incoming connections
- * <---- New connection
- * - Spawns a client thread to communicate with new client
- *
- * Server->Stop()
- * - Stops listening thread
- * - Stops all client threads
- */
-class NetworkPerformanceServer : public ClientSendDataInterface
-{
-
-public:
-
- /**
- * @brief Constructor
- * @param[in] adaptorServices adaptor internal services
- * @param[in] logOptions log options
- */
- NetworkPerformanceServer( AdaptorInternalServices& adaptorServices, const EnvironmentOptions& logOptions );
-
-
- /**
- * @brief Start the server, to be called form Dali main thread
- * @pre Can only be called form Dali main thread
- */
- void Start();
-
- /**
- * @brief Stop the server
- * @pre Can only be called form Dali main thread
- */
- void Stop();
-
- /**
- * @return true if the server is running
- */
- bool IsRunning() const;
-
- /**
- * @brief Transmit a marker to any clients are listening for this marker.
- * @param[in] marker performance marker
- * @param[in] description marker description
- * @pre Can be called from any thread
- *
- */
- void TransmitMarker( const PerformanceMarker& marker, const char* const description );
-
- /**
- * Destructor
- */
- ~NetworkPerformanceServer();
-
-protected: // ClientSendDataInterface
-
- /**
- * @copydoc ClientSendDataInterface::ClientSendDataInterface()
- */
- virtual void SendData( const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId );
-
-private:
-
- /**
- * Helper for the thread calling the entry function.
- * @param[in] This A pointer to the current RenderThread object
- */
- static void* ConnectionListenerFunc( void* This )
- {
- ( static_cast<NetworkPerformanceServer*>( This ) )->ConnectionListener();
- return NULL;
- }
-
- /**
- * Helper for the thread calling the entry function.
- * @param[in] This A pointer to the current RenderThread object
- */
- static void* ClientThreadFunc( void* data );
-
- /**
- * @brief Client thread function
- * @param client network client object
- */
- void ClientThread( NetworkPerformanceClient* client );
-
- /**
- * @brief Stop all client threads
- */
- void StopClients();
-
- /**
- * @brief Waits for new connections to be made
- */
- void ConnectionListener();
-
- /**
- * @brief Add a new client to the client list
- * @param clientSocket client socket
- * @param clientThread client thread
- * @return client
- */
- NetworkPerformanceClient* AddClient( SocketInterface* clientSocket, pthread_t* clientThread );
-
- /**
- * @brief Delete a client from the client list
- * @param client network client
- */
- void DeleteClient( NetworkPerformanceClient* client );
-
- NetworkPerformanceServer( const NetworkPerformanceServer& ); ///< undefined copy constructor
- NetworkPerformanceServer& operator=( const NetworkPerformanceServer& ); ///< undefined assignment operator
-
-
- TriggerEventFactoryInterface& mTriggerEventFactory; ///< used to create trigger events
- SocketFactoryInterface& mSocketFactory; ///< used to create sockets
- const EnvironmentOptions& mLogOptions; ///< log options
- Dali::Vector< NetworkPerformanceClient* > mClients; ///< list of connected clients
- pthread_t mServerThread; ///< thread that listens for new connections
- SocketInterface* mListeningSocket; ///< socket used to listen for new connections
- Dali::Mutex mClientListMutex; ///< mutex
- unsigned int mClientUniqueId; ///< increments for every client connection
- volatile unsigned int mClientCount; ///< client count
- bool mLogFunctionInstalled; ///< whether the log function is installed
-
-};
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif //__DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "performance-interface-factory.h"
-
-// INTERNAL INCLUDES
-#include "performance-server.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-PerformanceInterface* PerformanceInterfaceFactory::CreateInterface(
- AdaptorInternalServices& adaptorServices,
- const EnvironmentOptions& environmentOptions )
-{
- return new PerformanceServer( adaptorServices, environmentOptions );
-}
-
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
-#define __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/adaptor-internal-services.h>
-#include <base/environment-options.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Performance interface factory class
- *
- */
-class PerformanceInterfaceFactory
-{
-public:
-
- /**
- * Create a new concrete implementation of the performance interface.
- * @param adaptorServices adaptor internal services
- * @param environmentOptions environment options
- * @return pointer to a new performance interface
- */
- static PerformanceInterface* CreateInterface( AdaptorInternalServices& adaptorServices,
- const EnvironmentOptions& environmentOptions );
-
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "performance-marker.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-struct NamePair
-{
- PerformanceInterface::MarkerType type;
- const char* const name;
- PerformanceMarker::MarkerFilter group;
- PerformanceMarker::MarkerEventType eventType;
-};
-
-const NamePair MARKER_LOOKUP[] =
-{
- // timed event names must be postfixed with with _START and _END
- // this is to allow tracers to extract the event name by removing the _START, _END strings
- //
- { PerformanceInterface::VSYNC , "V_SYNC" , PerformanceMarker::V_SYNC_EVENTS, PerformanceMarker::SINGLE_EVENT },
- { PerformanceInterface::UPDATE_START , "UPDATE_START" , PerformanceMarker::UPDATE, PerformanceMarker::START_TIMED_EVENT },
- { PerformanceInterface::UPDATE_END , "UPDATE_END" , PerformanceMarker::UPDATE, PerformanceMarker::END_TIMED_EVENT },
- { PerformanceInterface::RENDER_START , "RENDER_START" , PerformanceMarker::RENDER, PerformanceMarker::START_TIMED_EVENT },
- { PerformanceInterface::RENDER_END , "RENDER_END" , PerformanceMarker::RENDER, PerformanceMarker::END_TIMED_EVENT },
- { PerformanceInterface::SWAP_START , "SWAP_START" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::START_TIMED_EVENT },
- { PerformanceInterface::SWAP_END , "SWAP_END" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::END_TIMED_EVENT },
- { PerformanceInterface::PROCESS_EVENTS_START, "PROCESS_EVENT_START" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::START_TIMED_EVENT },
- { PerformanceInterface::PROCESS_EVENTS_END, "PROCESS_EVENT_END" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::END_TIMED_EVENT },
- { PerformanceInterface::PAUSED , "PAUSED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT },
- { PerformanceInterface::RESUME , "RESUMED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT },
- { PerformanceInterface::START , "START" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::START_TIMED_EVENT },
- { PerformanceInterface::END , "END" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::END_TIMED_EVENT }
-};
-} // un-named namespace
-
-
-
-PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type )
-:mType(type)
-{
-}
-
-PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp frameInfo )
-:mType(type),
- mTimeStamp(frameInfo)
-{
-}
-
-const char* PerformanceMarker::GetName( ) const
-{
- return MARKER_LOOKUP[ mType ].name;
-}
-
-PerformanceMarker::MarkerEventType PerformanceMarker::GetEventType() const
-{
- return MARKER_LOOKUP[ mType ].eventType;
-}
-
-PerformanceMarker::MarkerFilter PerformanceMarker::GetFilterType() const
-{
- return MARKER_LOOKUP[ mType ].group;
-}
-
-unsigned int PerformanceMarker::MicrosecondDiff( const PerformanceMarker& start,const PerformanceMarker& end )
-{
- return FrameTimeStamp::MicrosecondDiff( start.mTimeStamp, end.mTimeStamp );
-}
-
-bool PerformanceMarker::IsFilterEnabled( MarkerFilter filter ) const
-{
- return (filter & MARKER_LOOKUP[ mType ].group);
-}
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
-#define __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <base/interfaces/performance-interface.h>
-#include <base/performance-logging/frame-time-stamp.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Marker used to record an event with a time stamp in Dali
- */
-class PerformanceMarker
-{
-public:
-
-
- /**
- * Bitmask used to filter different types of markers based
- * on what group they belong to.
- */
- enum MarkerFilter
- {
- FILTERING_DISABLED = 0, ///< disabled
- V_SYNC_EVENTS = 1 << 0, ///< v-sync
- UPDATE = 1 << 1, ///< update start / end
- RENDER = 1 << 2, ///< render start / end
- EVENT_PROCESS = 1 << 3, ///< process events start / end
- SWAP_BUFFERS = 1 << 4, ///< swap buffers start / end
- LIFE_CYCLE_EVENTS = 1 << 5, ///< pause / resume
- RESOURCE_EVENTS = 1 << 6, ///< resource events
- CUSTOM_EVENTS = 1 << 7
- };
-
- /**
- * Marker event type
- */
- enum MarkerEventType
- {
- SINGLE_EVENT, ///< event is something that has no duration associated with it
- START_TIMED_EVENT, ///< start of a timed event
- END_TIMED_EVENT ///< end of a timed event
-
- };
-
-
- /**
- * @brief Constructor
- * @param[in] type marker type
- */
- PerformanceMarker( PerformanceInterface::MarkerType type );
-
- /**
- * @brief Constructor
- * @param[in] type marker type
- * @param[in] time time stamp
- */
- PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp time );
-
- /**
- * @return the time stamp
- */
- const FrameTimeStamp& GetTimeStamp() const
- {
- return mTimeStamp;
- }
-
- /**
- * @return the type of marker
- */
- PerformanceInterface::MarkerType GetType() const
- {
- return mType;
- }
-
- /**
- * @return the event type of marker
- */
- MarkerEventType GetEventType() const;
-
- /**
- * @return the filter type of marker
- */
- MarkerFilter GetFilterType() const;
-
-
- /**
- * @return marker name
- */
- const char* GetName( ) const;
-
- /**
- * @param start the start marker
- * @param end the end marker
- * @return difference in microseconds between two markers
- */
- static unsigned int MicrosecondDiff( const PerformanceMarker& start, const PerformanceMarker& end );
-
- /**
- * @return if a marker is enabled as part of a group
- */
- bool IsFilterEnabled( MarkerFilter filter ) const;
-private:
-
- PerformanceInterface::MarkerType mType; ///< marker type
- FrameTimeStamp mTimeStamp; ///< frame time stamp
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "performance-server.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/platform-abstraction.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-#include <base/time-service.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int NANOSECONDS_PER_MICROSECOND = 1000u;
-const float MICROSECONDS_TO_SECOND = 1e-6;
-} // unnamed namespace
-
-PerformanceServer::PerformanceServer( AdaptorInternalServices& adaptorServices,
- const EnvironmentOptions& environmentOptions)
-: mEnvironmentOptions( environmentOptions ),
- mKernelTrace( adaptorServices.GetKernelTraceInterface() ),
- mSystemTrace( adaptorServices.GetSystemTraceInterface() ),
- mLogMutex(),
-#if defined(NETWORK_LOGGING_ENABLED)
- mNetworkServer( adaptorServices, environmentOptions ),
- mNetworkControlEnabled( mEnvironmentOptions.GetNetworkControlMode()),
-#endif
- mStatContextManager( *this ),
- mStatisticsLogBitmask( 0 ),
- mPerformanceOutputBitmask( 0 ),
- mLoggingEnabled( false ),
- mLogFunctionInstalled( false )
-{
- SetLogging( mEnvironmentOptions.GetPerformanceStatsLoggingOptions(),
- mEnvironmentOptions.GetPerformanceTimeStampOutput(),
- mEnvironmentOptions.GetPerformanceStatsLoggingFrequency());
-
-#if defined(NETWORK_LOGGING_ENABLED)
- if( mNetworkControlEnabled )
- {
- mLoggingEnabled = true;
- mNetworkServer.Start();
- }
-#endif
-}
-
-PerformanceServer::~PerformanceServer()
-{
-#if defined(NETWORK_LOGGING_ENABLED)
- if( mNetworkControlEnabled )
- {
- mNetworkServer.Stop();
- }
-#endif
-
- if( mLogFunctionInstalled )
- {
- mEnvironmentOptions.UnInstallLogFunction();
- }
-}
-
-void PerformanceServer::SetLogging( unsigned int statisticsLogOptions,
- unsigned int timeStampOutput,
- unsigned int logFrequency )
-{
- mStatisticsLogBitmask = statisticsLogOptions;
- mPerformanceOutputBitmask = timeStampOutput;
-
- mStatContextManager.SetLoggingLevel( mStatisticsLogBitmask, logFrequency);
-
- if( ( mStatisticsLogBitmask == 0) && ( mPerformanceOutputBitmask == 0 ))
- {
- mLoggingEnabled = false;
- }
- else
- {
- mLoggingEnabled = true;
- }
-}
-
-void PerformanceServer::SetLoggingFrequency( unsigned int logFrequency, ContextId contextId )
-{
- mStatContextManager.SetLoggingFrequency( logFrequency, contextId );
-}
-
-void PerformanceServer::EnableLogging( bool enable, ContextId contextId )
-{
- mStatContextManager.EnableLogging( enable, contextId );
-}
-
-PerformanceInterface::ContextId PerformanceServer::AddContext( const char* name )
-{
- // for adding custom contexts
- return mStatContextManager.AddContext( name, PerformanceMarker::CUSTOM_EVENTS );
-}
-
-void PerformanceServer::RemoveContext( ContextId contextId )
-{
- mStatContextManager.RemoveContext( contextId );
-}
-
-void PerformanceServer::AddMarker( MarkerType markerType, ContextId contextId )
-{
- // called only for custom markers
-
- if( !mLoggingEnabled )
- {
- return;
- }
-
- // Get the time stamp
- uint64_t timeStamp = 0;
- TimeService::GetNanoseconds( timeStamp );
- timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds
-
- // Create a marker
- PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) );
-
- // get the marker description for this context, e.g SIZE_NEGOTIATION_START
- const char* const description = mStatContextManager.GetMarkerDescription( markerType, contextId );
-
- // log it
- LogMarker( marker, description );
-
- // Add custom marker to statistics context manager
- mStatContextManager.AddCustomMarker( marker, contextId );
-}
-
-void PerformanceServer::AddMarker( MarkerType markerType )
-{
- // called only for internal markers
-
- if( !mLoggingEnabled )
- {
- return;
- }
-
- if( markerType == VSYNC )
- {
- // make sure log function is installed, note this will be called only from v-sync thread
- // if the v-sync thread has already installed one, it won't make any difference.
- if( ! mLogFunctionInstalled )
- {
- mEnvironmentOptions.InstallLogFunction();
- mLogFunctionInstalled = true;
- }
- }
-
- // Get the time
- uint64_t timeStamp = 0;
- TimeService::GetNanoseconds( timeStamp );
- timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds
-
- // Create a marker
- PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) );
-
- // log it
- LogMarker(marker, marker.GetName() );
-
- // Add internal marker to statistics context manager
- mStatContextManager.AddInternalMarker( marker );
-
-}
-
-void PerformanceServer::LogContextStatistics( const char* const text )
-{
- Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, text );
-}
-
-void PerformanceServer::LogMarker( const PerformanceMarker& marker, const char* const description )
-{
-#if defined(NETWORK_LOGGING_ENABLED)
- // log to the network ( this is thread safe )
- if( mNetworkControlEnabled )
- {
- mNetworkServer.TransmitMarker( marker, description );
- }
-#endif
-
- // log to kernel trace
- if( mPerformanceOutputBitmask & OUTPUT_KERNEL_TRACE )
- {
- // Kernel tracing implementation may not be thread safe
- Mutex::ScopedLock lock( mLogMutex );
- // description will be something like UPDATE_START or UPDATE_END
- mKernelTrace.Trace( marker, description );
- }
-
- // log to system trace
- if( mPerformanceOutputBitmask & OUTPUT_SYSTEM_TRACE )
- {
- // System tracing implementation may not be thread safe
- Mutex::ScopedLock lock( mLogMutex );
-
- mSystemTrace.Trace( marker, description );
- }
-
- // log to Dali log ( this is thread safe )
- if ( mPerformanceOutputBitmask & OUTPUT_DALI_LOG )
- {
- Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo,
- "%.6f (seconds), %s\n",
- float( marker.GetTimeStamp().microseconds ) * MICROSECONDS_TO_SECOND,
- description );
-
- }
-}
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H__
-#define __DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLDUES
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/devel-api/threading/mutex.h>
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/frame-time-stats.h>
-#include <base/performance-logging/networking/network-performance-server.h>
-#include <base/interfaces/adaptor-internal-services.h>
-#include <base/performance-logging/performance-marker.h>
-#include <base/performance-logging/statistics/stat-context-manager.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class EnvironmentOptions;
-class StatContext;
-/**
- * Concrete implementation of performance interface.
- * Adaptor classes should never include this file, they
- * just need to include the abstract class performance-interface.h
- */
-class PerformanceServer : public PerformanceInterface, public StatContextLogInterface
-{
-public:
-
- /**
- * @brief Constructor
- * @param[in] adaptorServices adaptor internal services
- * @param[in] environmentOptions environment options
- */
- PerformanceServer( AdaptorInternalServices& adaptorServices,
- const EnvironmentOptions& environmentOptions );
-
- /**
- * Destructor
- */
- virtual ~PerformanceServer();
-
- /**
- * @copydoc PerformanceLogger::AddContext()
- */
- virtual ContextId AddContext( const char* name );
-
- /**
- * @copydoc PerformanceLogger::RemoveContext()
- */
- virtual void RemoveContext( ContextId contextId );
-
- /**
- * @copydoc PerformanceInterface::AddMarker( MarkerType markerType )
- */
- virtual void AddMarker( MarkerType markerType );
-
- /**
- * @copydoc PerformanceLogger::AddMarker( MarkerType markerType, ContextId contextId )
- */
- virtual void AddMarker( MarkerType markerType, ContextId contextId );
-
- /**
- * @copydoc PerformanceInterface::SetLogging()
- */
- virtual void SetLogging( unsigned int statisticsLogOptions,
- unsigned int timeStampOutput,
- unsigned int logFrequency );
-
- /**
- * @copydoc PerformanceLogger::SetLoggingFrequency()
- */
- virtual void SetLoggingFrequency( unsigned int logFrequency, ContextId contextId );
-
- /**
- * @copydoc PerformanceLogger::EnableLogging()
- */
- virtual void EnableLogging( bool enable, ContextId contextId );
-
-public: //StatLogInterface
-
- /**
- * @copydoc StatLogInterface::LogContextStatistics()
- */
- virtual void LogContextStatistics( const char* const text );
-
-private:
-
- /**
- * @brief log the marker out to kernel/ DALi log
- * @param[in] marker performance marker
- * @param[in] description marker description
- */
- void LogMarker( const PerformanceMarker& marker, const char* const description );
-
-private:
-
- const EnvironmentOptions& mEnvironmentOptions; ///< environment options
- TraceInterface& mKernelTrace; ///< kernel trace interface
- TraceInterface& mSystemTrace; ///< system trace interface
- Dali::Mutex mLogMutex; ///< mutex
-
-#if defined(NETWORK_LOGGING_ENABLED)
- NetworkPerformanceServer mNetworkServer; ///< network server
- bool mNetworkControlEnabled; ///< Whether network control is enabled
-#endif
-
- StatContextManager mStatContextManager; ///< Stat context manager
- unsigned int mStatisticsLogBitmask; ///< statistics log level
- unsigned int mPerformanceOutputBitmask; ///< performance marker output
-
- bool mLoggingEnabled:1; ///< whether logging update / render to a log is enabled
- bool mLogFunctionInstalled:1; ///< whether the log function is installed
-};
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "stat-context-manager.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const char* const UPDATE_CONTEXT_NAME = "Update";
-const char* const RENDER_CONTEXT_NAME = "Render";
-const char* const EVENT_CONTEXT_NAME = "Event";
-const unsigned int DEFAULT_LOG_FREQUENCY = 2;
-}
-
-StatContextManager::StatContextManager( StatContextLogInterface& logInterface )
-: mLogInterface( logInterface ),
- mNextContextId( 0 ),
- mStatisticsLogBitmask(0),
- mLogFrequency( DEFAULT_LOG_FREQUENCY )
-{
-
- mStatContexts.Reserve(4); // intially reserve enough for 3 internal + 1 custom
-
- // Add defaults
- mUpdateStats = AddContext( UPDATE_CONTEXT_NAME, PerformanceMarker::UPDATE );
- mRenderStats = AddContext( RENDER_CONTEXT_NAME, PerformanceMarker::RENDER );
- mEventStats = AddContext( EVENT_CONTEXT_NAME, PerformanceMarker::EVENT_PROCESS );
-
-}
-
-StatContextManager::~StatContextManager()
-{
- for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
- {
- StatContext* context = *it;
- delete context;
- }
- mStatContexts.Clear();
-}
-PerformanceInterface::ContextId StatContextManager::AddContext( const char* const name,
- PerformanceMarker::MarkerFilter type )
-{
- unsigned int contextId = mNextContextId++;
-
- DALI_ASSERT_DEBUG( NULL == GetContext( contextId ) );
-
- // logging enabled by default
- StatContext* statContext = new StatContext( contextId, name, type, mLogFrequency , mLogInterface );
-
- // check to see if custom markers are enabled
- if( ! ( mStatisticsLogBitmask & PerformanceInterface::LOG_CUSTOM_MARKERS ) )
- {
- statContext->EnableLogging( false );
- }
-
- mStatContexts.PushBack( statContext );
-
- return contextId;
-}
-
-void StatContextManager::AddInternalMarker( const PerformanceMarker& marker )
-{
- // log to the stat contexts, can be called from multiple threads so we
- // protect the data
- Mutex::ScopedLock lock( mDataMutex );
- for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
- {
- StatContext* context = *it;
- context->ProcessInternalMarker( marker );
- }
-}
-
-void StatContextManager::AddCustomMarker( const PerformanceMarker& marker, PerformanceInterface::ContextId contextId )
-{
- // log to the stat contexts, can be called from multiple threads so we
- // protect the data
- Mutex::ScopedLock lock( mDataMutex );
- StatContext* context = GetContext( contextId );
- if( context )
- {
- context->ProcessCustomMarker( marker );
- }
-}
-
-void StatContextManager::RemoveContext(PerformanceInterface::ContextId contextId )
-{
- for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
- {
- StatContext* context = *it;
-
- if( context->GetId() == contextId )
- {
- delete context;
- mStatContexts.Erase( it );
- return;
- }
- }
-}
-
-
-void StatContextManager::EnableLogging( bool enable, PerformanceInterface::ContextId contextId )
-{
- StatContext* context = GetContext( contextId );
- if( context )
- {
- context->EnableLogging( enable );
- }
-}
-
-void StatContextManager::SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency)
-{
- mStatisticsLogBitmask = statisticsLogOptions;
-
- if( mStatisticsLogBitmask == PerformanceInterface::LOG_EVERYTHING )
- {
- mStatisticsLogBitmask = 0xFFFFFFFF; // enable everything
- }
-
- mLogFrequency = logFrequency;
-
- // currently uses DALI_LOG_PERFORMANCE_STATS_FREQ environment variable to determine to log frequency
- // if it's not set it will be zero
- if( mLogFrequency == 0 )
- {
- mLogFrequency = DEFAULT_LOG_FREQUENCY;
- }
- EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mUpdateStats );
- EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mRenderStats );
- EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_EVENT_PROCESS, mEventStats );
-
- for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
- {
- StatContext* context = *it;
- context->SetLogFrequency( mLogFrequency );
- }
-}
-
-void StatContextManager::SetLoggingFrequency( unsigned int logFrequency,
- PerformanceInterface::ContextId contextId )
-{
- StatContext* context = GetContext( contextId );
- if( context )
- {
- if( logFrequency == 0 )
- {
- logFrequency = DEFAULT_LOG_FREQUENCY;
- }
- context->SetLogFrequency( logFrequency );
- }
-}
-const char* StatContextManager::GetContextName(PerformanceInterface::ContextId contextId) const
-{
- StatContext* context = GetContext(contextId);
- if( context )
- {
- return context->GetName();
- }
- return "context not found";
-}
-
-const char* StatContextManager::GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const
-{
- StatContext* context = GetContext(contextId);
- if( context )
- {
- return context->GetMarkerDescription( type );
- }
- return "context not found";
-}
-
-
-StatContext* StatContextManager::GetContext( PerformanceInterface::ContextId contextId ) const
-{
- for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
- {
- StatContext* context = *it;
-
- if( context->GetId() == contextId )
- {
- return context;
- }
- }
-
- return NULL;
-}
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
-#define __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/devel-api/threading/mutex.h>
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/performance-marker.h>
-#include <base/performance-logging/statistics/stat-context.h>
-#include <base/interfaces/performance-interface.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Class to manage StatContext objects.
- *
- * Contains 3 built in contexts for event, update, render.
- * The application developer can add more using the PerformanceLogger public API
- *
- * Example output of 4 contexts ( event, update, render and a custom one):
- *
- * Event, min 0.04 ms, max 5.27 ms, total (0.1 secs), avg 0.28 ms, std dev 0.73 ms
- * Update, min 0.29 ms, max 0.91 ms, total (0.5 secs), avg 0.68 ms, std dev 0.15 ms
- * Render, min 0.33 ms, max 0.97 ms, total (0.6 secs), avg 0.73 ms, std dev 0.17 ms
- * MyAppTask, min 76.55 ms, max 76.55 ms, total (0.1 secs), avg 76.55 ms, std dev 0.00 ms (CUSTOM CONTEXT)
- *
- */
-class StatContextManager
-{
-
-public:
-
- /**
- * @brief Constructor
- * @param[in] logInterface interface to log statistics to
- */
- StatContextManager( StatContextLogInterface& logInterface );
-
- /**
- * @brief destructor, not intended as a bass class
- */
- ~StatContextManager();
-
- /**
- * @brief Add a context
- * @param[in] name Name of the context to print in console
- * @param[in] type the type of events to filter ( e.g. event, update, render or custom)
- * @return The ID to give the context
- */
- PerformanceInterface::ContextId AddContext( const char* const name, PerformanceMarker::MarkerFilter type );
-
- /**
- * @brief Remove a context
- * @param[in] contextId id of the context to remove
- */
- void RemoveContext(PerformanceInterface::ContextId contextId );
-
- /**
- * @brief Add an internal marker (e.g. v-sync, update, render markers)
- * @param[in] marker the marker to add
- */
- void AddInternalMarker( const PerformanceMarker& marker );
-
- /**
- * @brief Add a custom marker defined by the application
- * @param[in] marker the marker to add
- * @param[in] contextId the context the custom marker is designed for
- */
- void AddCustomMarker( const PerformanceMarker& marker , PerformanceInterface::ContextId contextId );
-
- /**
- * @brief Get the nane of a context
- * @param[in] contextId id of the context to get the name
- * @return context name
- */
- const char* GetContextName( PerformanceInterface::ContextId contextId ) const;
-
- /**
- * @brief Get the full description of a marker for this context
- * @param[in] type marker type, for a customer marker this will be either START or END
- * @param[in] contextId id of the context to get the name
- * @return marker description in relation to this context
- */
- const char* GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const;
-
-
- /**
- * @brief enable / disable logging for a context
- * @param[in] enable whether to enable logging
- * @param[in] contextId the context to configure
- */
- void EnableLogging( bool enable, PerformanceInterface::ContextId contextId );
-
- /**
- * @brief set global logging level and frequency.
- * @param[in] statisticsLogOptions log options
- * @param[in] logFrequency frequency in seconds
- */
- void SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency);
-
- /**
- * @brief Set the frequency of logging for an individual context
- * @param[in] logFrequency log frequency in seconds
- * @param[in] contextId the context to configure
- */
- void SetLoggingFrequency( unsigned int logFrequency, PerformanceInterface::ContextId contextId );
-
- private:
-
- StatContextManager( const StatContextManager& ); ///< Undefined
- StatContextManager& operator=( const StatContextManager& ); ///< Undefined
-
- typedef Dali::Vector< StatContext* > StatContexts;
-
- /**
- * @brief helper
- * @param[in] contextId the context to get
- * @return context
- */
- StatContext* GetContext( PerformanceInterface::ContextId contextId ) const;
-
- Dali::Mutex mDataMutex; ///< mutex
- StatContexts mStatContexts; ///< The list of stat contexts
- StatContextLogInterface& mLogInterface; ///< Log interface
-
- PerformanceInterface::ContextId mNextContextId; ///< The next valid context ID
-
- // Some defaults contexts
- PerformanceInterface::ContextId mUpdateStats; ///< update time statistics
- PerformanceInterface::ContextId mRenderStats; ///< render time statistics
- PerformanceInterface::ContextId mEventStats; ///< event time statistics
-
- unsigned int mStatisticsLogBitmask; ///< statistics log bitmask
- unsigned int mLogFrequency; ///< log frequency
-};
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
-
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// CLASS HEADER
-#include "stat-context.h"
-
-// EXTERNAL INCLUDES
-#include <cstdio>
-
-// INTERNAL INCLUDES
-#include <dali/integration-api/platform-abstraction.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#define TIME_FMT "%0.2f ms" // 2 decimal places, e.g. 5.34 ms
-#define TOTAL_TIME_FMT "%0.1f secs" // 1 decimal place, e.g. 4.5 seconds
-
-namespace
-{
-const unsigned int MILLISECONDS_PER_SECOND = 1000; ///< 1000 milliseconds per second
-const char* const UNKNOWN_CONTEXT_NAME = "UNKNOWN_CONTEXT_NAME";
-const unsigned int MICROSECONDS_PER_SECOND = 1000000; ///< 1000000 microseconds per second
-const unsigned int CONTEXT_LOG_SIZE = 120;
-
-}
-
-StatContext::StatContext( unsigned int id,
- const char* const contextName,
- PerformanceMarker::MarkerFilter contextType,
- unsigned int logFrequencySeconds,
- StatContextLogInterface& logInterface )
-: mInitialMarker(PerformanceInterface::VSYNC),
- mName( contextName ),
- mLogInterface( logInterface ),
- mNamePlusStart( std::string(contextName) + "_START" ),
- mNamePlusEnd( std::string(contextName) + "_END" ),
- mId( id ),
- mLogFrequencyMicroseconds( logFrequencySeconds * MICROSECONDS_PER_SECOND ),
- mFilterType( contextType ),
- mLoggingEnabled( true ),
- mInitialMarkerSet( false )
-{
- mTempLogBuffer = new char[ CONTEXT_LOG_SIZE ];
-}
-
-StatContext::~StatContext()
-{
- delete []mTempLogBuffer;
-}
-unsigned int StatContext::GetId() const
-{
- return mId;
-}
-
-const char* StatContext::GetName() const
-{
- return mName;
-}
-
-const char* StatContext::GetMarkerDescription( PerformanceInterface::MarkerType type ) const
-{
- if( type == PerformanceInterface::START )
- {
- return mNamePlusStart.c_str();
- }
- else if( type == PerformanceInterface::END )
- {
- return mNamePlusEnd.c_str();
- }
- return UNKNOWN_CONTEXT_NAME;
-}
-void StatContext::SetLogFrequency( unsigned int logFrequencySeconds )
-{
- mLogFrequencyMicroseconds = logFrequencySeconds * MICROSECONDS_PER_SECOND;
-}
-
-void StatContext::EnableLogging( bool enableLogging )
-{
- mLoggingEnabled = enableLogging;
-}
-
-void StatContext::ProcessCustomMarker( const PerformanceMarker& marker )
-{
- // this marker has come from the application PerformanceLogger API
- RecordMarker( marker);
-}
-
-void StatContext::ProcessInternalMarker( const PerformanceMarker& marker )
-{
- // this marker has come from DALi internal not the application
- // see if this context is for update, render or event
- if( marker.IsFilterEnabled( mFilterType ))
- {
- RecordMarker( marker );
- }
- // V_SYNC is always processed
- if( marker.GetType() == PerformanceInterface::VSYNC )
- {
- FrameTick( marker );
- }
-}
-
-void StatContext::RecordMarker( const PerformanceMarker& marker )
-{
- if( marker.GetEventType() == PerformanceMarker::START_TIMED_EVENT )
- {
- mStats.StartTime( marker.GetTimeStamp() );
- }
- else if( marker.GetEventType() == PerformanceMarker::END_TIMED_EVENT )
- {
- mStats.EndTime( marker.GetTimeStamp() );
- }
-}
-
-void StatContext::FrameTick( const PerformanceMarker& marker )
-{
- // wait until we've got some data
- if( ! mInitialMarkerSet )
- {
- mInitialMarker = marker;
- mInitialMarkerSet = true;
- return;
- }
- // log out every mLogFrequency.
- // check difference between first and last frame
- unsigned int microseconds = PerformanceMarker::MicrosecondDiff( mInitialMarker, marker );
-
- if( microseconds < mLogFrequencyMicroseconds )
- {
- return;
- }
-
- if( mLoggingEnabled )
- {
- LogMarker();
- }
- mStats.Reset(); // reset data for statistics
- mInitialMarkerSet = false; // need to restart the timer
-
-}
-
-void StatContext::LogMarker()
-{
- float mean, standardDeviation;
- mStats.CalculateMean( mean, standardDeviation );
-
- snprintf( mTempLogBuffer, CONTEXT_LOG_SIZE, "%s, min " TIME_FMT ", max " TIME_FMT ", total (" TOTAL_TIME_FMT "), avg " TIME_FMT ", std dev " TIME_FMT "\n",
- mName ? mName : UNKNOWN_CONTEXT_NAME,
- mStats.GetMinTime() * MILLISECONDS_PER_SECOND,
- mStats.GetMaxTime() * MILLISECONDS_PER_SECOND,
- mStats.GetTotalTime(),
- mean * MILLISECONDS_PER_SECOND,
- standardDeviation * MILLISECONDS_PER_SECOND );
-
- mLogInterface.LogContextStatistics( mTempLogBuffer );
-
-}
-
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H__
-#define __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-// INTERNAL INCLUDES
-#include <base/performance-logging/performance-marker.h>
-#include <base/performance-logging/frame-time-stats.h>
-#include <base/interfaces/performance-interface.h>
-#include <base/performance-logging/statistics/stat-context-log-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Stores and prints statistics for a particular logging context.
- *
- */
-class StatContext
-{
-
-public:
-
- /**
- * @brief Constructor
- *
- * @param[in] id The ID to give the context
- * @param[in] contextName Name of the context to print in console
- * @param[in] contextType the type of events to filter ( e.g. event, update, render or custom)
- * @param[in] logFrequencySeconds frequency to log in seconds
- * @param[in] logInterface interface to log out to
- *
- */
- StatContext( unsigned int id,
- const char* const contextName,
- PerformanceMarker::MarkerFilter contextType,
- unsigned int logFrequencySeconds,
- StatContextLogInterface& logInterface );
-
-
- /**
- * @brief Non-virtual destructor, not intended as a base class
- */
- ~StatContext();
-
- /**
- * @return Return the context ID
- */
- unsigned int GetId() const;
-
- /**
- * @return the context name
- */
- const char* GetName() const;
-
- /**
- *
- * For logging we want to output the name of the context with either
- * START / END appended to the end. E.g. MY_MARKER_START
- * @param[in] type marker type, for a customer marker this will be either START or END
- * @return the full description for a marker
- */
- const char* GetMarkerDescription( PerformanceInterface::MarkerType type ) const;
-
- /**
- * @brief Set the frequency for logging
- *
- * @param[in] logFrequencySeconds The log frequency to set in seconds
- */
- void SetLogFrequency( unsigned int logFrequencySeconds );
-
- /**
- * @brief enable/disable logging
- *
- * @param[in] enableLogging Flag to spePerformancecify enabling/disabling
- */
- void EnableLogging( bool enableLogging );
-
- /**
- * @brief Process a custom marker from the application
- *
- * @param[in] marker The marker to log
- */
- void ProcessCustomMarker( const PerformanceMarker& marker );
-
- /**
- * @brief Process a internal marker from DALi (V_SYNC/ UPDATE /RENDER/ EVENT )
- *
- * @param[in] marker The marker to log
- */
- void ProcessInternalMarker( const PerformanceMarker& marker );
-
- private:
-
- /**
- * @brief Record marker
- *
- * @param[in] marker to record
- */
- void RecordMarker( const PerformanceMarker& marker );
-
- /**
- * @brief Called when V-SYNC occurs to indicate a frame tick
- * @param[in] marker the marker containing a v-sync
- */
- void FrameTick( const PerformanceMarker& marker );
-
- /**
- * @brief Helper to print to console
- */
- void LogMarker();
-
-
- private:
-
- StatContext(); ///< undefined default constructor
-
- StatContext( const StatContext& ); ///< undefined copy constructor
-
- StatContext& operator=( const StatContext& ); ///< undefined assignment operator
-
- private:
-
- PerformanceMarker mInitialMarker; ///< Used to store initial time
- FrameTimeStats mStats; ///< Frame time stats to accumulate
- const char* const mName; ///< Name of the context
- char* mTempLogBuffer; ///< Temporary log buffer
- StatContextLogInterface& mLogInterface; ///< Log interface
- const std::string mNamePlusStart; ///< Name of the context + _START
- const std::string mNamePlusEnd; ///< Name of the context + _END
- unsigned int mId; ///< The ID of the context
- unsigned int mLogFrequencyMicroseconds; ///< if logging is enabled, what frequency to log out at in micro-seconds
- PerformanceMarker::MarkerFilter mFilterType; ///< type of events the context is filtering
- bool mLoggingEnabled:1; ///< Whether to print the log for this context or not
- bool mInitialMarkerSet:1; ///< Whether the initial marker has been set
-
-};
-
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "render-helper.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/adaptor-internal-services.h>
-#include <base/display-connection.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-RenderHelper::RenderHelper( AdaptorInternalServices& adaptorInterfaces )
-: mGLES( adaptorInterfaces.GetGlesInterface() ),
- mEglFactory( &adaptorInterfaces.GetEGLFactoryInterface()),
- mEGL( NULL ),
- mSurfaceReplaced( false ),
- mSurfaceResized( false )
-{
- // set the initial values before render thread starts
- mSurface = adaptorInterfaces.GetRenderSurfaceInterface();
-
- if( mSurface )
- {
- mDisplayConnection = Dali::DisplayConnection::New( mSurface->GetSurfaceType() );
- }
- else
- {
- mDisplayConnection = Dali::DisplayConnection::New();
- }
-}
-
-RenderHelper::~RenderHelper()
-{
- if (mDisplayConnection)
- {
- delete mDisplayConnection;
- mDisplayConnection = NULL;
- }
-
- mEglFactory->Destroy();
-}
-
-void RenderHelper::Start()
-{
- if( mSurface )
- {
- mSurface->StartRender();
- }
-}
-
-void RenderHelper::Stop()
-{
- if( mSurface )
- {
- // Tell surface we have stopped rendering
- mSurface->StopRender();
- }
-}
-
-void RenderHelper::ConsumeEvents()
-{
- mDisplayConnection->ConsumeEvents();
-}
-
-void RenderHelper::InitializeEgl()
-{
- mEGL = mEglFactory->Create();
-
- DALI_ASSERT_ALWAYS( mSurface && "NULL surface" );
-
- // Initialize EGL & OpenGL
- mDisplayConnection->InitializeEgl( *mEGL );
- mSurface->InitializeEgl( *mEGL );
-
- // create the OpenGL context
- mEGL->CreateContext();
-
- // create the OpenGL surface
- mSurface->CreateEglSurface(*mEGL);
-
- // Make it current
- mEGL->MakeContextCurrent();
-}
-
-void RenderHelper::ReplaceSurface( RenderSurface* newSurface )
-{
- mSurface->DestroyEglSurface(*mEGL);
-
- // This is designed for replacing pixmap surfaces, but should work for window as well
- // we need to delete the egl surface and renderable (pixmap / window)
- // Then create a new pixmap/window and new egl surface
- // If the new surface has a different display connection, then the context will be lost
- DALI_ASSERT_ALWAYS(newSurface && "NULL surface");
-
- mDisplayConnection->InitializeEgl(*mEGL);
-
- newSurface->ReplaceEGLSurface(*mEGL);
-
- // use the new surface from now on
- mSurface = newSurface;
- mSurfaceReplaced = true;
-}
-
-void RenderHelper::ResizeSurface()
-{
- mSurfaceResized = true;
-}
-
-void RenderHelper::ShutdownEgl()
-{
- if( mSurface )
- {
- // give a chance to destroy the OpenGL surface that created externally
- mSurface->DestroyEglSurface( *mEGL );
-
- mSurface = NULL;
- }
-
- // delete the GL context / egl surface
- mEGL->TerminateGles();
-}
-
-bool RenderHelper::PreRender()
-{
- if( mSurface )
- {
- mSurface->PreRender( *mEGL, mGLES, mSurfaceResized );
- }
- mGLES.PreRender();
- return true;
-}
-
-void RenderHelper::PostRender( bool renderToFbo )
-{
- // Inform the gl implementation that rendering has finished before informing the surface
- mGLES.PostRender();
-
- if( renderToFbo )
- {
- mGLES.Flush();
- mGLES.Finish();
- }
- else
- {
- if( mSurface )
- {
- // Inform the surface that rendering this frame has finished.
- mSurface->PostRender( *mEGL, mGLES, mDisplayConnection, mSurfaceReplaced, mSurfaceResized );
- }
- }
- mSurfaceReplaced = false;
- mSurfaceResized = false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_RENDER_HELPER_H
-#define DALI_INTERNAL_RENDER_HELPER_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <egl-interface.h>
-#include <render-surface.h> // needed for Dali::RenderSurface
-
-namespace Dali
-{
-
-class RenderSurface;
-class DisplayConnection;
-
-namespace Integration
-{
-class GlAbstraction;
-}
-
-namespace Internal
-{
-namespace Adaptor
-{
-
-class AdaptorInternalServices;
-class EglFactoryInterface;
-
-/**
- * Helper class for EGL, surface, pre & post rendering
- */
-class RenderHelper
-{
-public:
-
- /**
- * Create a RenderHelper.
- * @param[in] adaptorInterfaces base adaptor interface
- */
- RenderHelper( AdaptorInternalServices& adaptorInterfaces );
-
- /**
- * Non-virtual Destructor
- */
- ~RenderHelper();
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Called on the Event Thread
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Sets up all render related objects to start rendering.
- */
- void Start();
-
- /**
- * Sets up all render related objects to stop rendering.
- */
- void Stop();
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Called on the Rendering Thread
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Consumes any pending events to avoid memory leaks
- *
- * @note Called from rendering thread
- */
- void ConsumeEvents();
-
- /**
- * Initializes EGL.
- *
- * @note Called from rendering thread
- */
- void InitializeEgl();
-
- /**
- * Replaces the rendering surface
- *
- * Used for replacing pixmaps due to resizing
- * @param newSurface to use
- *
- * @note Called from render thread
- */
- void ReplaceSurface( RenderSurface* newSurface );
-
- /**
- * Resize the rendering surface.
- *
- * @note Called from render thread
- */
- void ResizeSurface();
-
- /**
- * Shuts down EGL.
- *
- * @note Called from render thread
- */
- void ShutdownEgl();
-
- /**
- * Called before core renders the scene
- *
- * @return true if successful and Core::Render should be called.
- *
- * @note Called from render thread
- */
- bool PreRender();
-
- /**
- * Called after core has rendered the scene
- *
- * @note Called from render thread
- *
- * @param[in] renderToFbo Whether to render to a Frame Buffer Object.
- */
- void PostRender( bool renderToFbo );
-
-private:
-
- // Undefined
- RenderHelper( const RenderHelper& RenderHelper );
-
- // Undefined
- RenderHelper& operator=( const RenderHelper& RenderHelper );
-
-private: // Data
-
- Integration::GlAbstraction& mGLES; ///< GL abstraction reference
- EglFactoryInterface* mEglFactory; ///< Factory class to create EGL implementation
- EglInterface* mEGL; ///< Interface to EGL implementation
- RenderSurface* mSurface; ///< Current surface
- Dali::DisplayConnection* mDisplayConnection; ///< Display connection
- bool mSurfaceReplaced; ///< True when new surface has been initialized.
- bool mSurfaceResized; ///< True when the surface is resized.
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_INTERNAL_RENDER_HELPER_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "thread-controller.h"
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-#include <base/thread-controller-interface.h>
-#include <base/combined-update-render/combined-update-render-controller.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-ThreadController::ThreadController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions )
-: mThreadControllerInterface( NULL )
-{
- switch( environmentOptions.GetThreadingMode() )
- {
- case ThreadingMode::COMBINED_UPDATE_RENDER:
- {
- mThreadControllerInterface = new CombinedUpdateRenderController( adaptorInterfaces, environmentOptions );
- break;
- }
- }
-}
-
-ThreadController::~ThreadController()
-{
- delete mThreadControllerInterface;
-}
-
-void ThreadController::Initialize()
-{
- mThreadControllerInterface->Initialize();
-}
-
-void ThreadController::Start()
-{
- mThreadControllerInterface->Start();
-}
-
-void ThreadController::Pause()
-{
- mThreadControllerInterface->Pause();
-}
-
-void ThreadController::Resume()
-{
- mThreadControllerInterface->Resume();
-}
-
-void ThreadController::Stop()
-{
- mThreadControllerInterface->Stop();
-}
-
-void ThreadController::RequestUpdate()
-{
- mThreadControllerInterface->RequestUpdate();
-}
-
-void ThreadController::RequestUpdateOnce()
-{
- mThreadControllerInterface->RequestUpdateOnce();
-}
-
-void ThreadController::ReplaceSurface( RenderSurface* newSurface )
-{
- mThreadControllerInterface->ReplaceSurface( newSurface );
-}
-
-void ThreadController::ResizeSurface()
-{
- mThreadControllerInterface->ResizeSurface();
-}
-
-void ThreadController::SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender )
-{
- mThreadControllerInterface->SetRenderRefreshRate( numberOfVSyncsPerRender );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// HEADER
-#include "base/time-service.h"
-
-// EXTERNAL INCLUDES
-#include <ctime>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace TimeService
-{
-
-namespace
-{
-const uint64_t NANOSECONDS_PER_SECOND = 1e+9;
-}
-
-void GetNanoseconds( uint64_t& timeInNanoseconds )
-{
- timespec timeSpec;
- clock_gettime( CLOCK_MONOTONIC, &timeSpec );
-
- // Convert all values to uint64_t to match our return type
- timeInNanoseconds = ( static_cast< uint64_t >( timeSpec.tv_sec ) * NANOSECONDS_PER_SECOND ) + static_cast< uint64_t >( timeSpec.tv_nsec );
-}
-
-void SleepUntil( uint64_t timeInNanoseconds )
-{
- timespec timeSpec;
- timeSpec.tv_sec = timeInNanoseconds / NANOSECONDS_PER_SECOND;
- timeSpec.tv_nsec = timeInNanoseconds % NANOSECONDS_PER_SECOND;
-
- // clock_nanosleep returns 0 if it sleeps for the period specified, otherwise it returns an error value
- // If an error value is returned, just sleep again till the absolute time specified
- while( clock_nanosleep( CLOCK_MONOTONIC, TIMER_ABSTIME, &timeSpec, NULL ) )
- {
- }
-}
-
-} // namespace TimeService
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "update-status-logger.h"
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/integration-api/core.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-UpdateStatusLogger::UpdateStatusLogger( const EnvironmentOptions& environmentOptions )
-: mStatusLogInterval( environmentOptions.GetUpdateStatusLoggingFrequency() ),
- mStatusLogCount( 0u )
-{
-}
-
-UpdateStatusLogger::~UpdateStatusLogger()
-{
-}
-
-void UpdateStatusLogger::Log( unsigned int keepUpdatingStatus )
-{
- if ( mStatusLogInterval )
- {
- std::string oss;
-
- if ( !(++mStatusLogCount % mStatusLogInterval) )
- {
- oss = "UpdateStatusLogging keepUpdating: ";
- oss += (keepUpdatingStatus ? "true":"false");
-
- if ( keepUpdatingStatus )
- {
- oss += " because: ";
- }
-
- if ( keepUpdatingStatus & Integration::KeepUpdating::STAGE_KEEP_RENDERING )
- {
- oss += "<Stage::KeepRendering() used> ";
- }
-
- if ( keepUpdatingStatus & Integration::KeepUpdating::ANIMATIONS_RUNNING )
- {
- oss += "<Animations running> ";
- }
-
- if ( keepUpdatingStatus & Integration::KeepUpdating::MONITORING_PERFORMANCE )
- {
- oss += "<Monitoring performance> ";
- }
-
- if ( keepUpdatingStatus & Integration::KeepUpdating::RENDER_TASK_SYNC )
- {
- oss += "<Render task waiting for completion> ";
- }
-
- DALI_LOG_UPDATE_STATUS( "%s\n", oss.c_str());
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "abort-handler.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-AbortHandler* AbortHandler::gInstance(NULL);
-
-AbortHandler::AbortHandler( CallbackBase* callback )
-: mSignalMask( 0 ),
- mCallback( callback )
-{
- DALI_ASSERT_ALWAYS( gInstance == NULL && "Only one instance of abort handler allowed" );
- gInstance = this;
-
- memset( mSignalOldHandlers, 0, sizeof(SignalHandlerFuncPtr) * (_NSIG-1));
-}
-
-AbortHandler::~AbortHandler()
-{
- delete mCallback;
-
- int signum;
- for ( signum = 1; signum < _NSIG; signum++ )
- {
- if ( mSignalMask & (1 << (signum-1) ) )
- {
- // set signals back to default handling
- signal( signum, mSignalOldHandlers[signum-1] );
- }
- }
- gInstance = NULL;
-}
-
-bool AbortHandler::AbortOnSignal( int signum )
-{
- bool status = false;
-
- if ( signum < _NSIG )
- {
- SignalHandlerFuncPtr signalHandlerPrevious = signal( signum, &AbortHandler::SignalHandler );
-
-// SIG_ERR is a macro with C cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
- if ( SIG_ERR != signalHandlerPrevious )
- {
- mSignalOldHandlers[signum-1] = signalHandlerPrevious;
- mSignalMask |= ( 1 << (signum-1) );
- status = true;
- }
- }
-#pragma GCC diagnostic pop
- return status;
-}
-
-void AbortHandler::SignalHandler( int signum )
-{
- if( gInstance )
- {
- if( gInstance->mCallback )
- {
- CallbackBase::Execute( *gInstance->mCallback );
- }
- }
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
-#define __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <signal.h>
-#include <dali/public-api/signals/callback.h>
-
-// INTERNAL INCLUDES
-#include "application.h"
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * Class to listen to system signals and trigger an abort callback
- * when they occur.
- *
- * This class maintains a process wide singleton, as the signal(2) system
- * call is process specific, not thread specific.
- *
- * Currently, this precludes having multiple DALi instances in the same process.
- */
-class AbortHandler
-{
-public:
- /**
- * Constructor
- * @param[in] callback The function to call when abort signals occur
- * @note The ownership of callback is passed onto this class.
- */
- AbortHandler( CallbackBase* callback );
-
- /**
- * Destructor
- */
- ~AbortHandler();
-
- /**
- * Add a signal you want to be handled by this abort handler.
- * @param[in] signum The signal number (from signum.h)
- * @return true if the signal handler was installed ok
- */
- bool AbortOnSignal( int signum );
-
-private:
- /**
- * Signal handler - Called when signal is received.
- * Stops the application.
- */
- static void SignalHandler( int signum );
-
- /**
- * Default constructor - undefined
- */
- AbortHandler();
-
- /**
- * Copy constructor - undefined
- */
- AbortHandler(const AbortHandler& rhs);
-
- /**
- * Assignment operator - undefined
- */
- AbortHandler& operator=(const AbortHandler& rhs);
-
-private:
- typedef void (*SignalHandlerFuncPtr )( int );
-
- // _NSIG comes from the signal.h linux system header, defining the number of signals.
- SignalHandlerFuncPtr mSignalOldHandlers[_NSIG-1];
- unsigned long long mSignalMask;
-
- CallbackBase* mCallback;
-
- static AbortHandler* gInstance;
-};
-
-} // Namespace Adaptor
-} // Namespace Internal
-} // Namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "accessibility-adaptor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <dali/integration-api/events/hover-event-integ.h>
-#include <dali/integration-api/events/gesture-requests.h>
-
-// INTERNAL INCLUDES
-#include "system-settings.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
-#endif
-
-} // unnamed namespace
-
-AccessibilityAdaptor::AccessibilityAdaptor()
-: mReadPosition(),
- mActionHandler( NULL ),
- mIndicator( NULL ),
- mIsEnabled( false ),
- mIndicatorFocused( false )
-{
- mAccessibilityGestureDetector = new AccessibilityGestureDetector();
-}
-
-void AccessibilityAdaptor::EnableAccessibility()
-{
- if(mIsEnabled == false)
- {
- mIsEnabled = true;
-
- if( mActionHandler )
- {
- mActionHandler->ChangeAccessibilityStatus();
- }
- }
-}
-
-void AccessibilityAdaptor::DisableAccessibility()
-{
- if(mIsEnabled == true)
- {
- mIsEnabled = false;
-
- if( mActionHandler )
- {
- mActionHandler->ChangeAccessibilityStatus();
- }
-
- // Destroy the TtsPlayer if exists.
- if ( Adaptor::IsAvailable() )
- {
- Dali::Adaptor& adaptor = Dali::Adaptor::Get();
- Adaptor& adaptorImpl = Adaptor::GetImplementation( adaptor );
- adaptorImpl.DestroyTtsPlayer( Dali::TtsPlayer::SCREEN_READER );
- }
- }
-}
-
-bool AccessibilityAdaptor::IsEnabled() const
-{
- return mIsEnabled;
-}
-
-Vector2 AccessibilityAdaptor::GetReadPosition() const
-{
- return mReadPosition;
-}
-
-void AccessibilityAdaptor::SetActionHandler(AccessibilityActionHandler& handler)
-{
- mActionHandler = &handler;
-}
-
-void AccessibilityAdaptor::SetGestureHandler(AccessibilityGestureHandler& handler)
-{
- if( mAccessibilityGestureDetector )
- {
- mAccessibilityGestureDetector->SetGestureHandler(handler);
- }
-}
-
-void AccessibilityAdaptor::SetIndicator(IndicatorInterface* indicator)
-{
- mIndicator = indicator;
-}
-
-bool AccessibilityAdaptor::HandleActionNextEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionPreviousEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionActivateEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionActivate();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
-{
- bool ret = false;
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
-
- mReadPosition.x = x;
- mReadPosition.y = y;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionRead( allowReadAgain );
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
- }
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadNextEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadPreviousEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionUpEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionUp();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionDownEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionDown();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionClearFocusEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->ClearAccessibilityFocus();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp)
-{
- bool ret = false;
-
- // We always need to emit a scroll signal, whether it's only a hover or not,
- // so always send the action to the action handler.
- if( mActionHandler )
- {
- Dali::TouchEvent event(timeStamp);
- event.points.push_back(point);
- ret = mActionHandler->AccessibilityActionScroll( event );
- }
-
- Integration::TouchEvent touchEvent;
- Integration::HoverEvent hoverEvent;
- Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent( Integration::Point( point ), timeStamp, touchEvent, hoverEvent );
- if( type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth ) // hover event is ignored
- {
- // Process the touch event in accessibility gesture detector
- if( mAccessibilityGestureDetector )
- {
- mAccessibilityGestureDetector->SendEvent( touchEvent );
- ret = true;
- }
- }
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp)
-{
- bool ret = false;
-
- Dali::TouchEvent touchEvent(timeStamp);
- touchEvent.points.push_back(point);
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionTouch(touchEvent);
- }
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionBackEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionBack();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-void AccessibilityAdaptor::HandleActionEnableEvent()
-{
- EnableAccessibility();
-}
-
-void AccessibilityAdaptor::HandleActionDisableEvent()
-{
- DisableAccessibility();
-}
-
-bool AccessibilityAdaptor::HandleActionScrollUpEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionScrollUp();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-
-bool AccessibilityAdaptor::HandleActionScrollDownEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionScrollDown();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionPageLeftEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionPageLeft();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionPageRightEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionPageRight();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionPageUpEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionPageUp();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionPageDownEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionPageDown();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionMoveToFirstEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionMoveToFirst();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionMoveToLastEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionMoveToLast();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadFromTopEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadFromTop();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadFromNextEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadFromNext();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionZoomEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionZoom();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadIndicatorInformation();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionReadPauseResume();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptor::HandleActionStartStopEvent()
-{
- bool ret = false;
-
- if( mActionHandler )
- {
- ret = mActionHandler->AccessibilityActionStartStop();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-AccessibilityAdaptor::~AccessibilityAdaptor()
-{
- // Do any platform specific clean-up in OnDestroy()
- OnDestroy();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
-#define __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/math/vector2.h>
-#include <dali/public-api/events/touch-point.h>
-#include <dali/integration-api/events/touch-event-combiner.h>
-
-// INTERNAL INCLUDES
-#include <accessibility-adaptor.h>
-#include <accessibility-action-handler.h>
-#include <accessibility-gesture-handler.h>
-#include <indicator-interface.h>
-#include <accessibility-gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * This class detects to accessibility action
- */
-class AccessibilityAdaptor : public Dali::BaseObject
-{
-public:
-
- /**
- * Constructor.
- */
- AccessibilityAdaptor();
-
- /**
- * @brief Get an instance of the AccessibilityAdaptor.
- *
- * @note This singleton-style getter can be reimplemented for different platforms.
- * @return The instance of the AccessibilityAdaptor.
- */
- static Dali::AccessibilityAdaptor Get();
-
- /**
- * Turn on accessibility action
- * This method should be called by vconf callback
- */
- void EnableAccessibility();
-
- /**
- * Turn off accessibility action
- * This method should be called by vconf callback
- */
- void DisableAccessibility();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::IsEnabled()
- */
- bool IsEnabled() const;
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::GetReadPosition() const
- */
- Vector2 GetReadPosition() const;
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::SetActionHandler()
- */
- void SetActionHandler(AccessibilityActionHandler& handler);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::SetGestureHandler()
- */
- void SetGestureHandler(AccessibilityGestureHandler& handler);
-
- /**
- * @brief Set the Indicator
- * @param[in] Indiciator interface
- */
- void SetIndicator( IndicatorInterface* indicator );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionNextEvent()
- */
- virtual bool HandleActionNextEvent( bool allowEndFeedback = true);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPreviousEvent()
- */
- virtual bool HandleActionPreviousEvent( bool allowEndFeedback = true);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionActivateEvent()
- */
- virtual bool HandleActionActivateEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadEvent()
- */
- virtual bool HandleActionReadEvent( unsigned int x, unsigned int y, bool allowReadAgain );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadNextEvent()
- */
- virtual bool HandleActionReadNextEvent( bool allowEndFeedback = true);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPreviousEvent()
- */
- virtual bool HandleActionReadPreviousEvent( bool allowEndFeedback = true);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionUpEvent()
- */
- virtual bool HandleActionUpEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionDownEvent()
- */
- virtual bool HandleActionDownEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionClearFocusEvent()
- */
- bool HandleActionClearFocusEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollEvent()
- */
- bool HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionTouchEvent()
- */
- bool HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp);
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionBackEvent()
- */
- bool HandleActionBackEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionEnableEvent()
- */
- void HandleActionEnableEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionDisableEvent()
- */
- void HandleActionDisableEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollUpEvent()
- */
- bool HandleActionScrollUpEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollDownEvent()
- */
- bool HandleActionScrollDownEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPageLeftEvent()
- */
- bool HandleActionPageLeftEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPageRightEvent()
- */
- bool HandleActionPageRightEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPageUpEvent()
- */
- bool HandleActionPageUpEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPageDownEvent()
- */
- bool HandleActionPageDownEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionMoveToFirstEvent()
- */
- bool HandleActionMoveToFirstEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionMoveToLastEvent()
- */
- bool HandleActionMoveToLastEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadFromTopEvent()
- */
- bool HandleActionReadFromTopEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadFromNextEvent()
- */
- bool HandleActionReadFromNextEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionZoomEvent()
- */
- bool HandleActionZoomEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
- */
- bool HandleActionReadIndicatorInformationEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
- */
- bool HandleActionReadPauseResumeEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionStartStopEvent()
- */
- bool HandleActionStartStopEvent();
-
-protected:
-
- /**
- * Destructor.
- */
- virtual ~AccessibilityAdaptor();
-
-private:
-
- /**
- * @brief Called when the singleton is destroyed.
- *
- * @note This can be reimplemented for different platforms.
- * @return The instance of the AccessibilityAdaptor.
- */
- static void OnDestroy();
-
- // Undefined
- AccessibilityAdaptor( const AccessibilityAdaptor& );
- AccessibilityAdaptor& operator=( AccessibilityAdaptor& );
-
-protected:
-
- Dali::Integration::TouchEventCombiner mCombiner; ///< Combines multi-touch events.
-
- Vector2 mReadPosition; ///< ActionRead position
-
- AccessibilityActionHandler* mActionHandler; ///< The pointer of accessibility action handler
-
- AccessibilityGestureDetectorPtr mAccessibilityGestureDetector; ///< The accessibility gesture detector
-
- IndicatorInterface* mIndicator; ///< The indicator
-
- bool mIsEnabled : 1; ///< enable/disable the accessibility action
- bool mIndicatorFocused : 1; ///< Whether the Indicator is focused
-
-public:
-
- // Helpers for public-api forwarding methods
-
- inline static Internal::Adaptor::AccessibilityAdaptor& GetImplementation(Dali::AccessibilityAdaptor& adaptor)
- {
- DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptor handle is empty" );
-
- BaseObject& handle = adaptor.GetBaseObject();
-
- return static_cast<Internal::Adaptor::AccessibilityAdaptor&>(handle);
- }
-
- inline static const Internal::Adaptor::AccessibilityAdaptor& GetImplementation(const Dali::AccessibilityAdaptor& adaptor)
- {
- DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptor handle is empty" );
-
- const BaseObject& handle = adaptor.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::AccessibilityAdaptor&>(handle);
- }
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "accessibility-gesture-detector.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/events/gesture-requests.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-AccessibilityGestureDetector::AccessibilityGestureDetector()
-: PanGestureDetectorBase(Vector2::ZERO, Integration::PanGestureRequest(), NULL),
- mGestureHandler(NULL),
- mPanning(false)
-{
-}
-
-AccessibilityGestureDetector::~AccessibilityGestureDetector()
-{
-}
-
-void AccessibilityGestureDetector::SetGestureHandler(AccessibilityGestureHandler& handler)
-{
- mGestureHandler = &handler;
-}
-
-void AccessibilityGestureDetector::EmitPan(const Integration::PanGestureEvent gesture)
-{
- if( mGestureHandler )
- {
- if(gesture.state == Gesture::Started)
- {
- mPanning = true;
- }
-
- if( mPanning )
- {
- mGestureHandler->HandlePanGesture(gesture);
-
- if( (gesture.state == Gesture::Finished) ||
- (gesture.state == Gesture::Cancelled) )
- {
- mPanning = false;
- }
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
-#define __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-
-// INTERNAL INCLUDES
-#include <events/pan-gesture-detector-base.h>
-#include <adaptor-impl.h>
-#include <accessibility-gesture-handler.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-class Core;
-struct TouchEvent;
-struct PanGestureRequest;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Detects an accessibility pan gesture and sends it to the gesture handler.
- */
-class AccessibilityGestureDetector : public PanGestureDetectorBase
-{
-public:
-
- /**
- * Constructor
- */
- AccessibilityGestureDetector();
-
- /**
- * Virtual destructor.
- */
- virtual ~AccessibilityGestureDetector();
-
- /**
- * Set the handler to handle accessibility gestures.
- * @param[in] handler The Accessibility gesture handler.
- * @note Handlers should remove themselves when they are destroyed.
- */
- void SetGestureHandler(AccessibilityGestureHandler& handler);
-
-private:
-
- /**
- * Emits the pan gesture event to the gesture handler.
- * @param[in] gesture The pan gesture event.
- */
- virtual void EmitPan(const Integration::PanGestureEvent gesture);
-
-private:
-
- AccessibilityGestureHandler* mGestureHandler; ///< The pointer of accessibility gesture handler
- bool mPanning; ///< Keep track of panning state, when panning is occuring, this is true.
-};
-
-typedef IntrusivePtr<AccessibilityGestureDetector> AccessibilityGestureDetectorPtr;
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "adaptor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/common/stage.h>
-#include <dali/public-api/actors/layer.h>
-#include <dali/devel-api/actors/actor-devel.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/core.h>
-#include <dali/integration-api/context-notifier.h>
-#include <dali/integration-api/profiling.h>
-#include <dali/integration-api/input-options.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <base/thread-controller.h>
-#include <base/performance-logging/performance-interface-factory.h>
-#include <base/lifecycle-observer.h>
-
-#include <dali/devel-api/text-abstraction/font-client.h>
-
-#include <callback-manager.h>
-#include <render-surface.h>
-#include <tts-player-impl.h>
-#include <accessibility-adaptor-impl.h>
-#include <events/gesture-manager.h>
-#include <events/event-handler.h>
-#include <gl/gl-proxy-implementation.h>
-#include <gl/gl-implementation.h>
-#include <gl/egl-sync-implementation.h>
-#include <gl/egl-image-extensions.h>
-#include <gl/egl-factory.h>
-#include <imf-manager-impl.h>
-#include <clipboard-impl.h>
-#include <vsync-monitor.h>
-#include <object-profiler.h>
-#include <base/display-connection.h>
-#include <window-impl.h>
-
-#include <tizen-logging.h>
-#include <image-loading.h>
-
-#include <locale-utils.h>
-
-using Dali::TextAbstraction::FontClient;
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-thread_local Adaptor* gThreadLocalAdaptor = NULL; // raw thread specific pointer to allow Adaptor::Get
-} // unnamed namespace
-
-Dali::Adaptor* Adaptor::New( Any nativeWindow, RenderSurface *surface, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions )
-{
- Dali::Adaptor* adaptor = new Dali::Adaptor;
- Adaptor* impl = new Adaptor( nativeWindow, *adaptor, surface, environmentOptions );
- adaptor->mImpl = impl;
-
- impl->Initialize(configuration);
-
- return adaptor;
-}
-
-Dali::Adaptor* Adaptor::New( Dali::Window window, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions )
-{
- Any winId = window.GetNativeHandle();
-
- Window& windowImpl = Dali::GetImplementation(window);
- Dali::Adaptor* adaptor = New( winId, windowImpl.GetSurface(), configuration, environmentOptions );
- windowImpl.SetAdaptor(*adaptor);
- return adaptor;
-}
-
-void Adaptor::Initialize( Dali::Configuration::ContextLoss configuration )
-{
- // all threads here (event, update, and render) will send their logs to TIZEN Platform's LogMessage handler.
- Dali::Integration::Log::LogFunction logFunction( Dali::TizenPlatform::LogMessage );
- mEnvironmentOptions->SetLogFunction( logFunction );
- mEnvironmentOptions->InstallLogFunction(); // install logging for main thread
-
- mPlatformAbstraction = new TizenPlatform::TizenPlatformAbstraction;
-
- std::string path;
- GetDataStoragePath( path );
- mPlatformAbstraction->SetDataStoragePath( path );
-
- ResourcePolicy::DataRetention dataRetentionPolicy = ResourcePolicy::DALI_DISCARDS_ALL_DATA;
- if( configuration == Dali::Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS )
- {
- dataRetentionPolicy = ResourcePolicy::DALI_DISCARDS_ALL_DATA;
- }
- // Note, Tizen does not use DALI_RETAINS_ALL_DATA, as it can reload images from
- // files automatically.
-
- if( mEnvironmentOptions->PerformanceServerRequired() )
- {
- mPerformanceInterface = PerformanceInterfaceFactory::CreateInterface( *this, *mEnvironmentOptions );
- }
-
- mCallbackManager = CallbackManager::New();
-
- PositionSize size = mSurface->GetPositionSize();
-
- mGestureManager = new GestureManager(*this, Vector2(size.width, size.height), mCallbackManager, *mEnvironmentOptions);
-
- if( mEnvironmentOptions->GetGlesCallTime() > 0 )
- {
- mGLES = new GlProxyImplementation( *mEnvironmentOptions );
- }
- else
- {
- mGLES = new GlImplementation();
- }
-
- const Integration::DepthBufferAvailable depthBufferAvailable = static_cast< Integration::DepthBufferAvailable >( mEnvironmentOptions->DepthBufferRequired() );
- const Integration::StencilBufferAvailable stencilBufferAvailable = static_cast< Integration::StencilBufferAvailable >( mEnvironmentOptions->StencilBufferRequired() );
-
- mEglFactory = new EglFactory( mEnvironmentOptions->GetMultiSamplingLevel(), depthBufferAvailable, stencilBufferAvailable );
-
- EglSyncImplementation* eglSyncImpl = mEglFactory->GetSyncImplementation();
-
- mCore = Integration::Core::New( *this,
- *mPlatformAbstraction,
- *mGLES,
- *eglSyncImpl,
- *mGestureManager,
- dataRetentionPolicy ,
- ( 0u != mEnvironmentOptions->GetRenderToFboInterval() ) ? Integration::RenderToFrameBuffer::TRUE : Integration::RenderToFrameBuffer::FALSE,
- depthBufferAvailable,
- stencilBufferAvailable );
-
- const unsigned int timeInterval = mEnvironmentOptions->GetObjectProfilerInterval();
- if( 0u < timeInterval )
- {
- mObjectProfiler = new ObjectProfiler( timeInterval );
- }
-
- mNotificationTrigger = mTriggerEventFactory.CreateTriggerEvent( MakeCallback( this, &Adaptor::ProcessCoreEvents ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER);
-
- mVSyncMonitor = new VSyncMonitor;
-
- mThreadController = new ThreadController( *this, *mEnvironmentOptions );
-
- // Should be called after Core creation
- if( mEnvironmentOptions->GetPanGestureLoggingLevel() )
- {
- Integration::EnableProfiling( Dali::Integration::PROFILING_TYPE_PAN_GESTURE );
- }
- if( mEnvironmentOptions->GetPanGesturePredictionMode() >= 0 )
- {
- Integration::SetPanGesturePredictionMode(mEnvironmentOptions->GetPanGesturePredictionMode());
- }
- if( mEnvironmentOptions->GetPanGesturePredictionAmount() >= 0 )
- {
- Integration::SetPanGesturePredictionAmount(mEnvironmentOptions->GetPanGesturePredictionAmount());
- }
- if( mEnvironmentOptions->GetPanGestureMaximumPredictionAmount() >= 0 )
- {
- Integration::SetPanGestureMaximumPredictionAmount(mEnvironmentOptions->GetPanGestureMaximumPredictionAmount());
- }
- if( mEnvironmentOptions->GetPanGestureMinimumPredictionAmount() >= 0 )
- {
- Integration::SetPanGestureMinimumPredictionAmount(mEnvironmentOptions->GetPanGestureMinimumPredictionAmount());
- }
- if( mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment() >= 0 )
- {
- Integration::SetPanGesturePredictionAmountAdjustment(mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment());
- }
- if( mEnvironmentOptions->GetPanGestureSmoothingMode() >= 0 )
- {
- Integration::SetPanGestureSmoothingMode(mEnvironmentOptions->GetPanGestureSmoothingMode());
- }
- if( mEnvironmentOptions->GetPanGestureSmoothingAmount() >= 0.0f )
- {
- Integration::SetPanGestureSmoothingAmount(mEnvironmentOptions->GetPanGestureSmoothingAmount());
- }
- if( mEnvironmentOptions->GetPanGestureUseActualTimes() >= 0 )
- {
- Integration::SetPanGestureUseActualTimes( mEnvironmentOptions->GetPanGestureUseActualTimes() == 0 ? true : false );
- }
- if( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() >= 0 )
- {
- Integration::SetPanGestureInterpolationTimeRange( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() );
- }
- if( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() >= 0 )
- {
- Integration::SetPanGestureScalarOnlyPredictionEnabled( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() == 0 ? true : false );
- }
- if( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() >= 0 )
- {
- Integration::SetPanGestureTwoPointPredictionEnabled( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() == 0 ? true : false );
- }
- if( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() >= 0 )
- {
- Integration::SetPanGestureTwoPointInterpolatePastTime( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() );
- }
- if( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() >= 0.0f )
- {
- Integration::SetPanGestureTwoPointVelocityBias( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() );
- }
- if( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() >= 0.0f )
- {
- Integration::SetPanGestureTwoPointAccelerationBias( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() );
- }
- if( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() >= 0 )
- {
- Integration::SetPanGestureMultitapSmoothingRange( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() );
- }
-
- // Set max texture size
- if( mEnvironmentOptions->GetMaxTextureSize() > 0 )
- {
- Dali::SetMaxTextureSize( mEnvironmentOptions->GetMaxTextureSize() );
- }
-
- SetupSystemInformation();
-}
-
-Adaptor::~Adaptor()
-{
- // Ensure stop status
- Stop();
-
- // set to NULL first as we do not want any access to Adaptor as it is being destroyed.
- gThreadLocalAdaptor = NULL;
-
- for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
- {
- (*iter)->OnDestroy();
- }
-
- delete mThreadController; // this will shutdown render thread, which will call Core::ContextDestroyed before exit
- delete mVSyncMonitor;
- delete mEventHandler;
- delete mObjectProfiler;
-
- delete mCore;
- delete mEglFactory;
- delete mGLES;
- delete mGestureManager;
- delete mPlatformAbstraction;
- delete mCallbackManager;
- delete mPerformanceInterface;
-
- // uninstall it on this thread (main actor thread)
- Dali::Integration::Log::UninstallLogFunction();
-
- // Delete environment options if we own it
- if( mEnvironmentOptionsOwned )
- {
- delete mEnvironmentOptions;
- }
-}
-
-void Adaptor::Start()
-{
- // it doesn't support restart after stop at this moment
- // to support restarting, need more testing
- if( READY != mState )
- {
- return;
- }
-
- // Start the callback manager
- mCallbackManager->Start();
-
- // create event handler
- mEventHandler = new EventHandler( mSurface, *this, *mGestureManager, *this, mDragAndDropDetector );
-
- if( mDeferredRotationObserver != NULL )
- {
- mEventHandler->SetRotationObserver(mDeferredRotationObserver);
- mDeferredRotationObserver = NULL;
- }
-
- unsigned int dpiHor, dpiVer;
- dpiHor = dpiVer = 0;
- Dali::DisplayConnection::GetDpi(dpiHor, dpiVer);
-
- // tell core about the DPI value
- mCore->SetDpi(dpiHor, dpiVer);
-
- // set the DPI value for font rendering
- FontClient fontClient = FontClient::Get();
- fontClient.SetDpi( dpiHor, dpiVer );
-
- // Tell the core the size of the surface just before we start the render-thread
- PositionSize size = mSurface->GetPositionSize();
- mCore->SurfaceResized( size.width, size.height );
-
- // Initialize the thread controller
- mThreadController->Initialize();
-
- ProcessCoreEvents(); // Ensure any startup messages are processed.
-
- for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
- {
- (*iter)->OnStart();
- }
-}
-
-// Dali::Internal::Adaptor::Adaptor::Pause
-void Adaptor::Pause()
-{
- // Only pause the adaptor if we're actually running.
- if( RUNNING == mState )
- {
- // Inform observers that we are about to be paused.
- for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
- {
- (*iter)->OnPause();
- }
-
- // Reset the event handler when adaptor paused
- if( mEventHandler )
- {
- mEventHandler->Pause();
- }
-
- mThreadController->Pause();
- mState = PAUSED;
-
- // Ensure any messages queued during pause callbacks are processed by doing another update.
- RequestUpdateOnce();
- }
-}
-
-// Dali::Internal::Adaptor::Adaptor::Resume
-void Adaptor::Resume()
-{
- // Only resume the adaptor if we are in the suspended state.
- if( PAUSED == mState )
- {
- mState = RUNNING;
-
- // Reset the event handler when adaptor resumed
- if( mEventHandler )
- {
- mEventHandler->Resume();
- }
-
- // Inform observers that we have resumed.
- for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
- {
- (*iter)->OnResume();
- }
-
- // trigger processing of events queued up while paused
- mCore->ProcessEvents();
-
- // Do at end to ensure our first update/render after resumption includes the processed messages as well
- mThreadController->Resume();
- }
-}
-
-void Adaptor::Stop()
-{
- if( RUNNING == mState ||
- PAUSED == mState ||
- PAUSED_WHILE_HIDDEN == mState )
- {
- for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
- {
- (*iter)->OnStop();
- }
-
- mThreadController->Stop();
-
- // Delete the TTS player
- for(int i =0; i < Dali::TtsPlayer::MODE_NUM; i++)
- {
- if(mTtsPlayers[i])
- {
- mTtsPlayers[i].Reset();
- }
- }
-
- delete mEventHandler;
- mEventHandler = NULL;
-
- delete mNotificationTrigger;
- mNotificationTrigger = NULL;
-
- mCallbackManager->Stop();
-
- mState = STOPPED;
- }
-}
-
-void Adaptor::ContextLost()
-{
- mCore->GetContextNotifier()->NotifyContextLost(); // Inform stage
-}
-
-void Adaptor::ContextRegained()
-{
- // Inform core, so that texture resources can be reloaded
- mCore->RecoverFromContextLoss();
-
- mCore->GetContextNotifier()->NotifyContextRegained(); // Inform stage
-}
-
-void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp )
-{
- mEventHandler->FeedTouchPoint( point, timeStamp );
-}
-
-void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent )
-{
- mEventHandler->FeedWheelEvent( wheelEvent );
-}
-
-void Adaptor::FeedKeyEvent( KeyEvent& keyEvent )
-{
- mEventHandler->FeedKeyEvent( keyEvent );
-}
-
-void Adaptor::ReplaceSurface( Any nativeWindow, RenderSurface& surface )
-{
- PositionSize positionSize = surface.GetPositionSize();
-
- // let the core know the surface size has changed
- mCore->SurfaceResized( positionSize.width, positionSize.height );
-
- mResizedSignal.Emit( mAdaptor );
-
- mNativeWindow = nativeWindow;
- mSurface = &surface;
-
- // flush the event queue to give the update-render thread chance
- // to start processing messages for new camera setup etc as soon as possible
- ProcessCoreEvents();
-
- // this method blocks until the render thread has completed the replace.
- mThreadController->ReplaceSurface(mSurface);
-}
-
-RenderSurface& Adaptor::GetSurface() const
-{
- return *mSurface;
-}
-
-void Adaptor::ReleaseSurfaceLock()
-{
- mSurface->ReleaseLock();
-}
-
-Dali::TtsPlayer Adaptor::GetTtsPlayer(Dali::TtsPlayer::Mode mode)
-{
- if(!mTtsPlayers[mode])
- {
- // Create the TTS player when it needed, because it can reduce launching time.
- mTtsPlayers[mode] = TtsPlayer::New(mode);
- }
-
- return mTtsPlayers[mode];
-}
-
-bool Adaptor::AddIdle( CallbackBase* callback, bool forceAdd )
-{
- bool idleAdded(false);
-
- // Only add an idle if the Adaptor is actually running
- if( RUNNING == mState || READY == mState || forceAdd )
- {
- idleAdded = mCallbackManager->AddIdleCallback( callback );
- }
-
- return idleAdded;
-}
-
-void Adaptor::RemoveIdle( CallbackBase* callback )
-{
- mCallbackManager->RemoveIdleCallback( callback );
-}
-
-Dali::Adaptor& Adaptor::Get()
-{
- DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" );
- return gThreadLocalAdaptor->mAdaptor;
-}
-
-bool Adaptor::IsAvailable()
-{
- return gThreadLocalAdaptor != NULL;
-}
-
-void Adaptor::SceneCreated()
-{
- mCore->SceneCreated();
-}
-
-Dali::Integration::Core& Adaptor::GetCore()
-{
- return *mCore;
-}
-
-void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender )
-{
- mThreadController->SetRenderRefreshRate( numberOfVSyncsPerRender );
-}
-
-void Adaptor::SetUseHardwareVSync( bool useHardware )
-{
- mVSyncMonitor->SetUseHardwareVSync( useHardware );
-}
-
-EglFactory& Adaptor::GetEGLFactory() const
-{
- DALI_ASSERT_DEBUG( mEglFactory && "EGL Factory not created" );
- return *mEglFactory;
-}
-
-EglFactoryInterface& Adaptor::GetEGLFactoryInterface() const
-{
- return *mEglFactory;
-}
-
-Integration::GlAbstraction& Adaptor::GetGlAbstraction() const
-{
- DALI_ASSERT_DEBUG( mGLES && "GLImplementation not created" );
- return *mGLES;
-}
-
-Dali::Integration::PlatformAbstraction& Adaptor::GetPlatformAbstractionInterface()
-{
- return *mPlatformAbstraction;
-}
-
-Dali::Integration::GlAbstraction& Adaptor::GetGlesInterface()
-{
- return *mGLES;
-}
-
-TriggerEventInterface& Adaptor::GetProcessCoreEventsTrigger()
-{
- return *mNotificationTrigger;
-}
-
-TriggerEventFactoryInterface& Adaptor::GetTriggerEventFactoryInterface()
-{
- return mTriggerEventFactory;
-}
-
-SocketFactoryInterface& Adaptor::GetSocketFactoryInterface()
-{
- return mSocketFactory;
-}
-
-RenderSurface* Adaptor::GetRenderSurfaceInterface()
-{
- return mSurface;
-}
-
-VSyncMonitorInterface* Adaptor::GetVSyncMonitorInterface()
-{
- return mVSyncMonitor;
-}
-
-TraceInterface& Adaptor::GetKernelTraceInterface()
-{
- return mKernelTracer;
-}
-
-TraceInterface& Adaptor::GetSystemTraceInterface()
-{
- return mSystemTracer;
-}
-
-PerformanceInterface* Adaptor::GetPerformanceInterface()
-{
- return mPerformanceInterface;
-}
-
-Integration::PlatformAbstraction& Adaptor::GetPlatformAbstraction() const
-{
- DALI_ASSERT_DEBUG( mPlatformAbstraction && "PlatformAbstraction not created" );
- return *mPlatformAbstraction;
-}
-
-void Adaptor::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
-{
- mDragAndDropDetector = detector;
-
- if ( mEventHandler )
- {
- mEventHandler->SetDragAndDropDetector( detector );
- }
-}
-
-void Adaptor::SetRotationObserver( RotationObserver* observer )
-{
- if( mEventHandler )
- {
- mEventHandler->SetRotationObserver( observer );
- }
- else if( mState == READY )
- {
- // Set once event handler exists
- mDeferredRotationObserver = observer;
- }
-}
-
-void Adaptor::DestroyTtsPlayer(Dali::TtsPlayer::Mode mode)
-{
- if(mTtsPlayers[mode])
- {
- mTtsPlayers[mode].Reset();
- }
-}
-
-void Adaptor::SetMinimumPinchDistance(float distance)
-{
- if( mGestureManager )
- {
- mGestureManager->SetMinimumPinchDistance(distance);
- }
-}
-
-Any Adaptor::GetNativeWindowHandle()
-{
- return mNativeWindow;
-}
-
-void Adaptor::SetUseRemoteSurface(bool useRemoteSurface)
-{
- mUseRemoteSurface = useRemoteSurface;
-}
-
-void Adaptor::AddObserver( LifeCycleObserver& observer )
-{
- ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
-
- if ( match == mObservers.end() )
- {
- mObservers.push_back( &observer );
- }
-}
-
-void Adaptor::RemoveObserver( LifeCycleObserver& observer )
-{
- ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
-
- if ( match != mObservers.end() )
- {
- mObservers.erase( match );
- }
-}
-
-void Adaptor::QueueCoreEvent(const Dali::Integration::Event& event)
-{
- if( mCore )
- {
- mCore->QueueEvent(event);
- }
-}
-
-void Adaptor::ProcessCoreEvents()
-{
- if( mCore )
- {
- if( mPerformanceInterface )
- {
- mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_START );
- }
-
- mCore->ProcessEvents();
-
- if( mPerformanceInterface )
- {
- mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_END );
- }
- }
-}
-
-void Adaptor::RequestUpdate( bool forceUpdate )
-{
- switch( mState )
- {
- case RUNNING:
- {
- mThreadController->RequestUpdate();
- break;
- }
- case PAUSED:
- case PAUSED_WHILE_HIDDEN:
- {
- // When Dali applications are partially visible behind the lock-screen,
- // the indicator must be updated (therefore allow updates in the PAUSED state)
- if( forceUpdate )
- {
- mThreadController->RequestUpdateOnce();
- }
- break;
- }
- default:
- {
- // Do nothing
- break;
- }
- }
-}
-
-void Adaptor::RequestProcessEventsOnIdle( bool forceProcess )
-{
- // Only request a notification if the Adaptor is actually running
- // and we haven't installed the idle notification
- if( ( ! mNotificationOnIdleInstalled ) && ( RUNNING == mState || READY == mState || forceProcess ) )
- {
- mNotificationOnIdleInstalled = AddIdle( MakeCallback( this, &Adaptor::ProcessCoreEventsFromIdle ), forceProcess );
- }
-}
-
-void Adaptor::OnWindowShown()
-{
- if ( PAUSED_WHILE_HIDDEN == mState )
- {
- // Adaptor can now be resumed
- mState = PAUSED;
-
- Resume();
-
- // Force a render task
- RequestUpdateOnce();
- }
-}
-
-void Adaptor::OnWindowHidden()
-{
- if ( RUNNING == mState )
- {
- Pause();
-
- // Adaptor cannot be resumed until the window is shown
- mState = PAUSED_WHILE_HIDDEN;
- }
-}
-
-// Dali::Internal::Adaptor::Adaptor::OnDamaged
-void Adaptor::OnDamaged( const DamageArea& area )
-{
- // This is needed for the case where Dali window is partially obscured
- RequestUpdate( false );
-}
-
-void Adaptor::SurfaceResizePrepare( SurfaceSize surfaceSize )
-{
- // let the core know the surface size has changed
- mCore->SurfaceResized( surfaceSize.GetWidth(), surfaceSize.GetHeight() );
-
- mResizedSignal.Emit( mAdaptor );
-}
-
-void Adaptor::SurfaceResizeComplete( SurfaceSize surfaceSize )
-{
- // flush the event queue to give the update-render thread chance
- // to start processing messages for new camera setup etc as soon as possible
- ProcessCoreEvents();
-
- // this method blocks until the render thread has completed the resizing.
- mThreadController->ResizeSurface();
-}
-
-void Adaptor::NotifySceneCreated()
-{
- GetCore().SceneCreated();
-
- // Start thread controller after the scene has been created
- mThreadController->Start();
-
- // process after surface is created (registering to remote surface provider if required)
- SurfaceInitialized();
-
- mState = RUNNING;
-}
-
-void Adaptor::NotifyLanguageChanged()
-{
- mLanguageChangedSignal.Emit( mAdaptor );
-}
-
-void Adaptor::RenderOnce()
-{
- RequestUpdateOnce();
-}
-
-void Adaptor::RequestUpdateOnce()
-{
- if( mThreadController )
- {
- mThreadController->RequestUpdateOnce();
- }
-}
-
-void Adaptor::IndicatorSizeChanged(int height)
-{
- // let the core know the indicator height is changed
- mCore->SetTopMargin(height);
-}
-
-void Adaptor::ProcessCoreEventsFromIdle()
-{
- ProcessCoreEvents();
-
- // the idle handle automatically un-installs itself
- mNotificationOnIdleInstalled = false;
-}
-
-Adaptor::Adaptor(Any nativeWindow, Dali::Adaptor& adaptor, RenderSurface* surface, EnvironmentOptions* environmentOptions)
-: mResizedSignal(),
- mLanguageChangedSignal(),
- mAdaptor( adaptor ),
- mState( READY ),
- mCore( NULL ),
- mThreadController( NULL ),
- mVSyncMonitor( NULL ),
- mGLES( NULL ),
- mGlSync( NULL ),
- mEglFactory( NULL ),
- mNativeWindow( nativeWindow ),
- mSurface( surface ),
- mPlatformAbstraction( NULL ),
- mEventHandler( NULL ),
- mCallbackManager( NULL ),
- mNotificationOnIdleInstalled( false ),
- mNotificationTrigger( NULL ),
- mGestureManager( NULL ),
- mDaliFeedbackPlugin(),
- mFeedbackController( NULL ),
- mTtsPlayers(),
- mObservers(),
- mDragAndDropDetector(),
- mDeferredRotationObserver( NULL ),
- mEnvironmentOptions( environmentOptions ? environmentOptions : new EnvironmentOptions /* Create the options if not provided */),
- mPerformanceInterface( NULL ),
- mKernelTracer(),
- mSystemTracer(),
- mTriggerEventFactory(),
- mObjectProfiler( NULL ),
- mSocketFactory(),
- mEnvironmentOptionsOwned( environmentOptions ? false : true /* If not provided then we own the object */ ),
- mUseRemoteSurface( false )
-{
- DALI_ASSERT_ALWAYS( !IsAvailable() && "Cannot create more than one Adaptor per thread" );
- gThreadLocalAdaptor = this;
-}
-
-// Stereoscopy
-
-void Adaptor::SetViewMode( ViewMode viewMode )
-{
- mSurface->SetViewMode( viewMode );
- mCore->SetViewMode( viewMode );
-}
-
-ViewMode Adaptor::GetViewMode() const
-{
- return mCore->GetViewMode();
-}
-
-void Adaptor::SetStereoBase( float stereoBase )
-{
- mCore->SetStereoBase( stereoBase );
-}
-
-float Adaptor::GetStereoBase() const
-{
- return mCore->GetStereoBase();
-}
-
-void Adaptor::SetRootLayoutDirection( std::string locale )
-{
- Dali::Stage stage = Dali::Stage::GetCurrent();
-
- stage.GetRootLayer().SetProperty( Dali::Actor::Property::LAYOUT_DIRECTION,
- static_cast< LayoutDirection::Type >( Internal::Adaptor::Locale::GetDirection( std::string( locale ) ) ) );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_IMPL_H__
-#define __DALI_INTERNAL_ADAPTOR_IMPL_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/common/view-mode.h>
-#include <dali/public-api/math/rect.h>
-#include <dali/public-api/signals/callback.h>
-#include <dali/public-api/math/uint-16-pair.h>
-#include <dali/integration-api/render-controller.h>
-
-// INTERNAL INCLUDES
-#include <adaptor.h>
-#include <render-surface.h>
-#include <tts-player.h>
-#include <imf-manager.h>
-#include <clipboard.h>
-
-#include <tizen-platform-abstraction.h>
-#include <base/interfaces/adaptor-internal-services.h>
-#include <base/environment-options.h>
-#include <base/core-event-interface.h>
-#include <drag-and-drop-detector-impl.h>
-#include <damage-observer.h>
-#include <window-visibility-observer.h>
-#include <kernel-trace.h>
-#include <system-trace.h>
-#include <trigger-event-factory.h>
-#include <networking/socket-factory.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-class Window;
-
-namespace Integration
-{
-class Core;
-class GlAbstraction;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-class EventHandler;
-class EglFactory;
-class GestureManager;
-class GlImplementation;
-class GlSyncImplementation;
-class ThreadController;
-class TriggerEvent;
-class CallbackManager;
-class FeedbackPluginProxy;
-class FeedbackController;
-class RotationObserver;
-class VSyncMonitor;
-class PerformanceInterface;
-class LifeCycleObserver;
-class ObjectProfiler;
-
-/**
- * Implementation of the Adaptor class.
- */
-class Adaptor : public Integration::RenderController,
- public AdaptorInternalServices,
- public CoreEventInterface,
- public DamageObserver,
- public WindowVisibilityObserver
-{
-public:
-
- typedef Dali::Adaptor::AdaptorSignalType AdaptorSignalType;
-
- typedef Uint16Pair SurfaceSize; ///< Surface size type
-
- /**
- * Creates a New Adaptor
- * @param[in] nativeWindow Native window handle
- * @param[in] surface A render surface can be one of the following
- * - Pixmap, adaptor will use existing Pixmap to draw on to
- * - Window, adaptor will use existing Window to draw on to
- * @param[in] configuration The context loss configuration ( to choose resource discard policy )
- * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
- */
- static Dali::Adaptor* New( Any nativeWindow,
- RenderSurface* surface,
- Dali::Configuration::ContextLoss configuration,
- EnvironmentOptions* environmentOptions );
-
- /**
- * Creates a New Adaptor
- * @param[in] nativeWindow native window handle
- * @param[in] configuration The context loss configuration ( to choose resource discard policy )
- * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
- */
- static Dali::Adaptor* New( Dali::Window window, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions );
-
- /**
- * 2-step initialisation, this should be called after creating an adaptor instance.
- */
- void Initialize(Dali::Configuration::ContextLoss configuration);
-
- /**
- * Virtual destructor.
- */
- virtual ~Adaptor();
-
- /**
- * @copydoc Dali::Adaptor::Get()
- */
- static Dali::Adaptor& Get();
-
- /**
- * @copydoc Dali::Adaptor::IsAvailable()
- */
- static bool IsAvailable();
-
- /**
- * @copydoc Dali::Core::SceneCreated();
- */
- void SceneCreated();
-
-public: // AdaptorInternalServices implementation
- /**
- * @copydoc Dali::Adaptor::Start()
- */
- virtual void Start();
-
- /**
- * @copydoc Dali::Adaptor::Pause()
- */
- virtual void Pause();
-
- /**
- * @copydoc Dali::Adaptor::Resume()
- */
- virtual void Resume();
-
- /**
- * @copydoc Dali::Adaptor::Stop()
- */
- virtual void Stop();
-
- /**
- * @copydoc Dali::Adaptor::ContextLost()
- */
- virtual void ContextLost();
-
- /**
- * @copydoc Dali::Adaptor::ContextRegained()
- */
- virtual void ContextRegained();
-
- /**
- * @copydoc Dali::EventFeeder::FeedTouchPoint()
- */
- virtual void FeedTouchPoint( TouchPoint& point, int timeStamp );
-
- /**
- * @copydoc Dali::EventFeeder::FeedWheelEvent()
- */
- virtual void FeedWheelEvent( WheelEvent& wheelEvent );
-
- /**
- * @copydoc Dali::EventFeeder::FeedKeyEvent()
- */
- virtual void FeedKeyEvent( KeyEvent& keyEvent );
-
- /**
- * @copydoc AdaptorInterface::ReplaceSurface()
- */
- virtual void ReplaceSurface( Any nativeWindow, RenderSurface& surface );
-
- /**
- * @copydoc Dali::Adaptor::GetSurface()
- */
- virtual RenderSurface& GetSurface() const;
-
- /**
- * @copydoc Dali::Adaptor::ReleaseSurfaceLock()
- */
- virtual void ReleaseSurfaceLock();
-
- /**
- * Retrieve the TtsPlayer.
- * @param[in] mode The mode of TtsPlayer
- * @return A handle to the TtsPlayer.
- */
- virtual Dali::TtsPlayer GetTtsPlayer(Dali::TtsPlayer::Mode mode);
-
- /**
- * @copydoc Dali::Adaptor::AddIdle()
- */
- virtual bool AddIdle( CallbackBase* callback, bool forceAdd );
-
- /**
- * @copydoc Dali::Adaptor::RemoveIdle()
- */
- virtual void RemoveIdle( CallbackBase* callback );
-
-public:
-
- /**
- * @return the Core instance
- */
- virtual Dali::Integration::Core& GetCore();
-
- /**
- * @copydoc Dali::Adaptor::SetRenderRefreshRate()
- */
- void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender );
-
- /**
- * @copydoc Dali::Adaptor::SetUseHardwareVSync()
- */
- void SetUseHardwareVSync(bool useHardware);
-
- /**
- * @return reference to EglFactory class
- */
- EglFactory& GetEGLFactory() const;
-
- /**
- * Return GlAbstraction.
- * @return the GlAbstraction.
- */
- Integration::GlAbstraction& GetGlAbstraction() const;
-
- /**
- * Return the PlatformAbstraction.
- * @return The PlatformAbstraction.
- */
- Integration::PlatformAbstraction& GetPlatformAbstraction() const;
-
- /**
- * Sets the Drag & Drop Listener.
- * @param[in] detector The detector to send Drag & Drop events to.
- */
- void SetDragAndDropDetector( DragAndDropDetectorPtr detector );
-
- /**
- * Sets a rotation observer, or set to NULL to remove.
- * @pre Adaptor::Start() has been called ( to create EventHandler )
- * @param[in] observer The observer to listen for window rotation events
- */
- void SetRotationObserver( RotationObserver* observer );
-
- /**
- * Destroy the TtsPlayer of sepcific mode.
- * @param[in] mode The mode of TtsPlayer to destroy
- */
- void DestroyTtsPlayer(Dali::TtsPlayer::Mode mode);
-
- /**
- * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
- * trigger a pinch gesture
- *
- * @param[in] distance The minimum pinch distance in pixels
- */
- void SetMinimumPinchDistance(float distance);
-
- /**
- * Gets native window handle
- *
- * @return native window handle
- */
- Any GetNativeWindowHandle();
-
- /**
- * Sets use remote surface for eglSurface output
- * @param[in] useRemoteSurface True if the remote surface is used
- */
- void SetUseRemoteSurface(bool useRemoteSurface);
-
-public:
-
- /**
- * Adds an adaptor observer so that we can observe the adaptor's lifetime events.
- * @param[in] observer The observer.
- * @note Observers should remove themselves when they are destroyed.
- */
- void AddObserver( LifeCycleObserver& observer );
-
- /**
- * Removes the observer from the adaptor.
- * @param[in] observer The observer to remove.
- * @note Observers should remove themselves when they are destroyed.
- */
- void RemoveObserver( LifeCycleObserver& observer );
-
- /**
- * Emits the Notification event to the Dali core.
- */
- void SendNotificationEvent();
-
- /**
- * Request adaptor to update once
- */
- void RequestUpdateOnce();
-
- /**
- * Request adaptor to update indicator's height
- */
- void IndicatorSizeChanged(int height);
-
- /**
- * @copydoc Dali::Adaptor::NotifySceneCreated()
- */
- void NotifySceneCreated();
-
- /**
- * @copydoc Dali::Adaptor::NotifyLanguageChanged()
- */
- void NotifyLanguageChanged();
-
- /**
- * Gets AppId of current application
- */
- void GetAppId( std::string& appId );
-
- /**
- * Informs core the surface size has changed
- */
- void SurfaceResizePrepare( SurfaceSize surfaceSize );
-
- /**
- * Informs ThreadController the surface size has changed
- */
- void SurfaceResizeComplete( SurfaceSize surfaceSize );
-
- /**
- * Sets layout direction of root by system language
- * @param[in] locale System locale
- */
- void SetRootLayoutDirection( std::string locale );
-
- /**
- * @copydoc Dali::Adaptor::RenderOnce
- */
- void RenderOnce();
-
-public: //AdaptorInternalServices
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetPlatformAbstractionInterface()
- */
- virtual Dali::Integration::PlatformAbstraction& GetPlatformAbstractionInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetGlesInterface()
- */
- virtual Dali::Integration::GlAbstraction& GetGlesInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetEGLFactoryInterface()
- */
- virtual EglFactoryInterface& GetEGLFactoryInterface() const;
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetTriggerEventInterface()
- */
- virtual TriggerEventInterface& GetProcessCoreEventsTrigger();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetTriggerEventFactoryInterface()
- */
- virtual TriggerEventFactoryInterface& GetTriggerEventFactoryInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetSocketFactoryInterface()
- */
- virtual SocketFactoryInterface& GetSocketFactoryInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetRenderSurfaceInterface()
- */
- virtual RenderSurface* GetRenderSurfaceInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetVSyncMonitorInterface()
- */
- virtual VSyncMonitorInterface* GetVSyncMonitorInterface();
-
- /**
- * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetPerformanceInterface()
- */
- virtual PerformanceInterface* GetPerformanceInterface();
-
- /**
- * copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetKernelTraceInterface()
- */
- virtual TraceInterface& GetKernelTraceInterface();
-
- /**
- * copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetSystemTraceInterface()
- */
- virtual TraceInterface& GetSystemTraceInterface();
-
-public: // Stereoscopy
-
- /**
- * @copydoc Dali::Integration::Core::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::Integration::Core::GetViewMode()
- */
- ViewMode GetViewMode() const;
-
- /**
- * @copydoc Dali::Integration::Core::SetStereoBase()
- */
- void SetStereoBase( float stereoBase );
-
- /**
- * @copydoc Dali::Integration::Core::GetStereoBase()
- */
- float GetStereoBase() const;
-
-public: // Signals
-
- /**
- * @copydoc Dali::Adaptor::SignalResized
- */
- AdaptorSignalType& ResizedSignal()
- {
- return mResizedSignal;
- }
-
- /**
- * @copydoc Dali::Adaptor::LanguageChangedSignal
- */
- AdaptorSignalType& LanguageChangedSignal()
- {
- return mLanguageChangedSignal;
- }
-
-private: // From Dali::Internal::Adaptor::CoreEventInterface
-
- /**
- * @copydoc Dali::Internal::Adaptor::CoreEventInterface::QueueCoreEvent()
- */
- virtual void QueueCoreEvent(const Dali::Integration::Event& event);
-
- /**
- * @copydoc Dali::Internal::Adaptor:CoreEventInterface:::ProcessCoreEvents()
- */
- virtual void ProcessCoreEvents();
-
-private: // From Dali::Integration::RenderController
-
- /**
- * @copydoc Dali::Integration::RenderController::RequestUpdate()
- */
- virtual void RequestUpdate( bool forceUpdate );
-
- /**
- * @copydoc Dali::Integration::RenderController::RequestProcessEventsOnIdle()
- */
- virtual void RequestProcessEventsOnIdle( bool forceProcess );
-
-private: // From Dali::Internal::Adaptor::WindowVisibilityObserver
-
- /**
- * Called when the window becomes fully or partially visible.
- */
- virtual void OnWindowShown();
-
- /**
- * Called when the window is fully hidden.
- */
- virtual void OnWindowHidden();
-
-private: // From Dali::Internal::Adaptor::DamageObserver
-
- /**
- * @copydoc Dali::Internal::Adaptor::DamageObserver::OnDamaged()
- */
- void OnDamaged( const DamageArea& area );
-
-private:
-
- // Undefined
- Adaptor(const Adaptor&);
- Adaptor& operator=(Adaptor&);
-
-private:
-
- /**
- * Assigns the render surface to the adaptor
- *
- */
- void SetSurface(RenderSurface *surface);
-
- /**
- * called after surface is created
- */
- void SurfaceInitialized();
-
- /**
- * Sends an notification message from main loop idle handler
- */
- void ProcessCoreEventsFromIdle();
-
- /**
- * Gets path for data/resource storage.
- * @param[out] path Path for data/resource storage
- */
- void GetDataStoragePath(std::string& path);
-
- /**
- * Sets up system information if needs
- */
- void SetupSystemInformation();
-
-private:
-
- /**
- * Constructor
- * @param[in] nativeWindow native window handle
- * @param[in] adaptor The public adaptor
- * @param[in] surface A render surface can be one of the following
- * - Pixmap, adaptor will use existing Pixmap to draw on to
- * - Window, adaptor will use existing Window to draw on to
- * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
- */
- Adaptor( Any nativeWindow, Dali::Adaptor& adaptor, RenderSurface* surface, EnvironmentOptions* environmentOptions );
-
-private: // Types
-
- enum State
- {
- READY, ///< Initial state before Adaptor::Start is called.
- RUNNING, ///< Adaptor is running.
- PAUSED, ///< Adaptor has been paused.
- PAUSED_WHILE_HIDDEN, ///< Adaptor is paused while window is hidden (& cannot be resumed until window is shown).
- STOPPED, ///< Adaptor has been stopped.
- };
-
- typedef std::vector<LifeCycleObserver*> ObserverContainer;
-
-private: // Data
-
- AdaptorSignalType mResizedSignal; ///< Resized signal.
- AdaptorSignalType mLanguageChangedSignal; ///< Language changed signal.
-
- Dali::Adaptor& mAdaptor; ///< Reference to public adaptor instance.
- State mState; ///< Current state of the adaptor
- Dali::Integration::Core* mCore; ///< Dali Core
- ThreadController* mThreadController; ///< Controls the threads
- VSyncMonitor* mVSyncMonitor; ///< Monitors VSync events
- GlImplementation* mGLES; ///< GL implementation
- GlSyncImplementation* mGlSync; ///< GL Sync implementation
- EglFactory* mEglFactory; ///< EGL Factory
-
- Any mNativeWindow; ///< window identifier
- RenderSurface* mSurface; ///< Current surface
- TizenPlatform::TizenPlatformAbstraction* mPlatformAbstraction; ///< Platform abstraction
-
- EventHandler* mEventHandler; ///< event handler
- CallbackManager* mCallbackManager; ///< Used to install callbacks
- bool mNotificationOnIdleInstalled; ///< whether the idle handler is installed to send an notification event
- TriggerEventInterface* mNotificationTrigger; ///< Notification event trigger
- GestureManager* mGestureManager; ///< Gesture manager
- FeedbackPluginProxy* mDaliFeedbackPlugin; ///< Used to access feedback support
- FeedbackController* mFeedbackController; ///< Plays feedback effects for Dali-Toolkit UI Controls.
- Dali::TtsPlayer mTtsPlayers[Dali::TtsPlayer::MODE_NUM]; ///< Provides TTS support
- ObserverContainer mObservers; ///< A list of adaptor observer pointers
- DragAndDropDetectorPtr mDragAndDropDetector; ///< The Drag & Drop detector
- RotationObserver* mDeferredRotationObserver; ///< deferred Rotation observer needs event handler
- EnvironmentOptions* mEnvironmentOptions; ///< environment options
- PerformanceInterface* mPerformanceInterface; ///< Performance interface
- KernelTrace mKernelTracer; ///< Kernel tracer
- SystemTrace mSystemTracer; ///< System tracer
- TriggerEventFactory mTriggerEventFactory; ///< Trigger event factory
- ObjectProfiler* mObjectProfiler; ///< Tracks object lifetime for profiling
- SocketFactory mSocketFactory; ///< Socket factory
- const bool mEnvironmentOptionsOwned:1; ///< Whether we own the EnvironmentOptions (and thus, need to delete it)
- bool mUseRemoteSurface; ///< whether the remoteSurface is used or not
-public:
- inline static Adaptor& GetImplementation(Dali::Adaptor& adaptor) {return *adaptor.mImpl;}
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_IMPL_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <adaptor.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <accessibility-adaptor.h>
-#include <imf-manager.h>
-#include <style-monitor.h>
-#include <render-surface.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-Adaptor& Adaptor::New( Window window )
-{
- return New( window, Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS );
-}
-
-Adaptor& Adaptor::New( Window window, Configuration::ContextLoss configuration )
-{
- Adaptor* adaptor = Internal::Adaptor::Adaptor::New( window, configuration, NULL );
- return *adaptor;
-}
-
-Adaptor& Adaptor::New( Any nativeWindow, const Dali::RenderSurface& surface )
-{
- return New( nativeWindow, surface, Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS );
-}
-
-Adaptor& Adaptor::New( Any nativeWindow, const Dali::RenderSurface& surface, Configuration::ContextLoss configuration )
-{
- Dali::RenderSurface* pSurface = const_cast<Dali::RenderSurface *>(&surface);
- Adaptor* adaptor = Internal::Adaptor::Adaptor::New( nativeWindow, pSurface, configuration, NULL );
- return *adaptor;
-}
-
-Adaptor::~Adaptor()
-{
- delete mImpl;
-}
-
-void Adaptor::Start()
-{
- mImpl->Start();
-}
-
-void Adaptor::Pause()
-{
- mImpl->Pause();
-}
-
-void Adaptor::Resume()
-{
- mImpl->Resume();
-}
-
-void Adaptor::Stop()
-{
- mImpl->Stop();
-}
-
-bool Adaptor::AddIdle( CallbackBase* callback )
-{
- return mImpl->AddIdle( callback, false );
-}
-
-void Adaptor::RemoveIdle( CallbackBase* callback )
-{
- mImpl->RemoveIdle( callback );
-}
-
-void Adaptor::ReplaceSurface( Any nativeWindow, Dali::RenderSurface& surface )
-{
- mImpl->ReplaceSurface(nativeWindow, surface);
-}
-
-Adaptor::AdaptorSignalType& Adaptor::ResizedSignal()
-{
- return mImpl->ResizedSignal();
-}
-
-Adaptor::AdaptorSignalType& Adaptor::LanguageChangedSignal()
-{
- return mImpl->LanguageChangedSignal();
-}
-
-RenderSurface& Adaptor::GetSurface()
-{
- return mImpl->GetSurface();
-}
-
-Any Adaptor::GetNativeWindowHandle()
-{
- return mImpl->GetNativeWindowHandle();
-}
-
-void Adaptor::ReleaseSurfaceLock()
-{
- mImpl->ReleaseSurfaceLock();
-}
-
-void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender )
-{
- mImpl->SetRenderRefreshRate( numberOfVSyncsPerRender );
-}
-
-void Adaptor::SetUseHardwareVSync(bool useHardware)
-{
- mImpl->SetUseHardwareVSync( useHardware );
-}
-
-Adaptor& Adaptor::Get()
-{
- return Internal::Adaptor::Adaptor::Get();
-}
-
-bool Adaptor::IsAvailable()
-{
- return Internal::Adaptor::Adaptor::IsAvailable();
-}
-
-void Adaptor::NotifySceneCreated()
-{
- mImpl->NotifySceneCreated();
-}
-
-void Adaptor::NotifyLanguageChanged()
-{
- mImpl->NotifyLanguageChanged();
-}
-
-void Adaptor::SetMinimumPinchDistance(float distance)
-{
- mImpl->SetMinimumPinchDistance(distance);
-}
-
-void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp )
-{
- mImpl->FeedTouchPoint(point, timeStamp);
-}
-
-void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent )
-{
- mImpl->FeedWheelEvent(wheelEvent);
-}
-
-void Adaptor::FeedKeyEvent( KeyEvent& keyEvent )
-{
- mImpl->FeedKeyEvent(keyEvent);
-}
-
-void Adaptor::SceneCreated()
-{
- mImpl->SceneCreated();
-}
-
-void Adaptor::SetViewMode( ViewMode mode )
-{
- mImpl->SetViewMode( mode );
-}
-
-void Adaptor::SetStereoBase( float stereoBase )
-{
- mImpl->SetStereoBase( stereoBase );
-}
-
-void Adaptor::RenderOnce()
-{
- mImpl->RenderOnce();
-}
-
-Adaptor::Adaptor()
-: mImpl( NULL )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "application-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <style-monitor.h>
-#include <command-line-options.h>
-#include <common/adaptor-impl.h>
-#include <common/framework.h>
-#include <singleton-service-impl.h>
-#include <lifecycle-controller-impl.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-class TizenPlatformAbstraction;
-}
-
-namespace Integration
-{
-class Core;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-ApplicationPtr Application::gPreInitializedApplication( NULL );
-
-ApplicationPtr Application::New(
- int* argc,
- char **argv[],
- const std::string& stylesheet,
- Dali::Application::WINDOW_MODE windowMode,
- const PositionSize& positionSize,
- Framework::Type applicationType)
-{
- ApplicationPtr application ( new Application (argc, argv, stylesheet, windowMode, positionSize, applicationType ) );
- return application;
-}
-
-void Application::PreInitialize( int* argc, char** argv[] )
-{
- if( !gPreInitializedApplication )
- {
- gPreInitializedApplication = new Application ( argc, argv, "", Dali::Application::OPAQUE, PositionSize(), Framework::NORMAL );
-
- gPreInitializedApplication->CreateWindow(); // Only create window
-
- gPreInitializedApplication->mLaunchpadState = Launchpad::PRE_INITIALIZED;
- }
-}
-
-Application::Application( int* argc, char** argv[], const std::string& stylesheet,
- Dali::Application::WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType )
-: mInitSignal(),
- mTerminateSignal(),
- mPauseSignal(),
- mResumeSignal(),
- mResetSignal(),
- mResizeSignal(),
- mAppControlSignal(),
- mLanguageChangedSignal(),
- mRegionChangedSignal(),
- mBatteryLowSignal(),
- mMemoryLowSignal(),
- mEventLoop( NULL ),
- mFramework( NULL ),
- mContextLossConfiguration( Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS ),
- mCommandLineOptions( NULL ),
- mSingletonService( SingletonService::New() ),
- mAdaptor( NULL ),
- mWindow(),
- mWindowMode( windowMode ),
- mName(),
- mStylesheet( stylesheet ),
- mEnvironmentOptions(),
- mWindowPositionSize( positionSize ),
- mLaunchpadState( Launchpad::NONE ),
- mSlotDelegate( this )
-{
- // Get mName from environment options
- mName = mEnvironmentOptions.GetWindowName();
- if( mName.empty() && argc && ( *argc > 0 ) )
- {
- // Set mName from command-line args if environment option not set
- mName = (*argv)[0];
- }
-
- mCommandLineOptions = new CommandLineOptions(argc, argv);
- mFramework = new Framework( *this, argc, argv, applicationType );
- mUseRemoteSurface = (applicationType == Framework::WATCH);
-}
-
-Application::~Application()
-{
- mSingletonService.UnregisterAll();
-
- mWindow.Reset();
- delete mAdaptor;
- delete mCommandLineOptions;
- delete mFramework;
-}
-
-void Application::CreateWindow()
-{
- if( mWindowPositionSize.width == 0 && mWindowPositionSize.height == 0 )
- {
- if( mCommandLineOptions->stageWidth > 0 && mCommandLineOptions->stageHeight > 0 )
- {
- // Command line options override environment options and full screen
- mWindowPositionSize.width = mCommandLineOptions->stageWidth;
- mWindowPositionSize.height = mCommandLineOptions->stageHeight;
- }
- else if( mEnvironmentOptions.GetWindowWidth() && mEnvironmentOptions.GetWindowHeight() )
- {
- // Environment options override full screen functionality if command line arguments not provided
- mWindowPositionSize.width = mEnvironmentOptions.GetWindowWidth();
- mWindowPositionSize.height = mEnvironmentOptions.GetWindowHeight();
- }
- }
-
- const std::string& windowClassName = mEnvironmentOptions.GetWindowClassName();
- mWindow = Dali::Window::New( mWindowPositionSize, mName, windowClassName, mWindowMode == Dali::Application::TRANSPARENT );
-
- int indicatorVisibleMode = mEnvironmentOptions.GetIndicatorVisibleMode();
- if( indicatorVisibleMode >= Dali::Window::INVISIBLE && indicatorVisibleMode <= Dali::Window::AUTO )
- {
- GetImplementation( mWindow ).SetIndicatorVisibleMode( static_cast< Dali::Window::IndicatorVisibleMode >( indicatorVisibleMode ) );
- }
-
- // Quit the application when the window is closed
- GetImplementation( mWindow ).DeleteRequestSignal().Connect( mSlotDelegate, &Application::Quit );
-}
-
-void Application::CreateAdaptor()
-{
- DALI_ASSERT_ALWAYS( mWindow && "Window required to create adaptor" );
-
- mAdaptor = Dali::Internal::Adaptor::Adaptor::New( mWindow, mContextLossConfiguration, &mEnvironmentOptions );
-
- mAdaptor->ResizedSignal().Connect( mSlotDelegate, &Application::OnResize );
-
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetUseRemoteSurface( mUseRemoteSurface );
-}
-
-void Application::MainLoop(Dali::Configuration::ContextLoss configuration)
-{
- mContextLossConfiguration = configuration;
-
- // Run the application
- mFramework->Run();
-}
-
-void Application::Lower()
-{
- // Lower the application without quitting it.
- mWindow.Lower();
-}
-
-void Application::Quit()
-{
- // Actually quit the application.
- // Force a call to Quit even if adaptor is not running.
- Internal::Adaptor::Adaptor::GetImplementation(*mAdaptor).AddIdle( MakeCallback( this, &Application::QuitFromMainLoop ), true );
-}
-
-void Application::QuitFromMainLoop()
-{
- mAdaptor->Stop();
-
- mFramework->Quit();
- // This will trigger OnTerminate(), below, after the main loop has completed.
-}
-
-void Application::DoInit()
-{
- // If an application was pre-initialized, a window was made in advance
- if( mLaunchpadState == Launchpad::NONE )
- {
- CreateWindow();
- }
-
- CreateAdaptor();
-
- // Run the adaptor
- mAdaptor->Start();
-
- // Check if user requires no vsyncing and set Adaptor
- if (mCommandLineOptions->noVSyncOnRender)
- {
- mAdaptor->SetUseHardwareVSync(false);
- }
-
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetStereoBase( mCommandLineOptions->stereoBase );
- if( mCommandLineOptions->viewMode != 0 )
- {
- ViewMode viewMode = MONO;
- if( mCommandLineOptions->viewMode <= STEREO_INTERLACED )
- {
- viewMode = static_cast<ViewMode>( mCommandLineOptions->viewMode );
- }
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetViewMode( viewMode );
- }
-
- if( ! mStylesheet.empty() )
- {
- Dali::StyleMonitor::Get().SetTheme( mStylesheet );
- }
-}
-
-void Application::DoStart()
-{
- mAdaptor->NotifySceneCreated();
-}
-
-void Application::DoTerminate()
-{
- if( mAdaptor )
- {
- // Ensure that the render-thread is not using the surface(window) after we delete it
- mAdaptor->Stop();
- }
-
- mWindow.Reset();
-}
-
-void Application::DoPause()
-{
- mAdaptor->Pause();
-}
-
-void Application::DoResume()
-{
- mAdaptor->Resume();
-}
-
-void Application::DoLanguageChange()
-{
- mAdaptor->NotifyLanguageChanged();
-}
-
-void Application::OnInit()
-{
- mFramework->AddAbortCallback( MakeCallback( this, &Application::QuitFromMainLoop ) );
-
- DoInit();
-
- // Wire up the LifecycleController
- Dali::LifecycleController lifecycleController = Dali::LifecycleController::Get();
-
- InitSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnInit );
- TerminateSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnTerminate );
- PauseSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnPause );
- ResumeSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnResume );
- ResetSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnReset );
- ResizeSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnResize );
- LanguageChangedSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnLanguageChanged );
-
- Dali::Application application(this);
- mInitSignal.Emit( application );
-
- DoStart();
-}
-
-void Application::OnTerminate()
-{
- // we've been told to quit by AppCore, ecore_x_destroy has been called, need to quit synchronously
- // delete the window as ecore_x has been destroyed by AppCore
-
- Dali::Application application(this);
- mTerminateSignal.Emit( application );
-
- DoTerminate();
-}
-
-void Application::OnPause()
-{
- // A DALi app should handle Pause/Resume events.
- // DALi just delivers the framework Pause event to the application, but not actually pause DALi core.
- // Pausing DALi core only occurs on the Window Hidden framework event
- Dali::Application application(this);
- mPauseSignal.Emit( application );
-}
-
-void Application::OnResume()
-{
- // Emit the signal first so the application can queue any messages before we do an update/render
- // This ensures we do not just redraw the last frame before pausing if that's not required
- Dali::Application application(this);
- mResumeSignal.Emit( application );
-
- // DALi just delivers the framework Resume event to the application.
- // Resuming DALi core only occurs on the Window Show framework event
-}
-
-void Application::OnReset()
-{
- /*
- * usually, reset callback was called when a caller request to launch this application via aul.
- * because Application class already handled initialization in OnInit(), OnReset do nothing.
- */
- Dali::Application application(this);
- mResetSignal.Emit( application );
-}
-
-void Application::OnAppControl(void *data)
-{
- Dali::Application application(this);
- mAppControlSignal.Emit( application , data );
-}
-
-void Application::OnLanguageChanged()
-{
- DoLanguageChange();
- Dali::Application application(this);
- mLanguageChangedSignal.Emit( application );
-}
-
-void Application::OnRegionChanged()
-{
- Dali::Application application(this);
- mRegionChangedSignal.Emit( application );
-}
-
-void Application::OnBatteryLow( Dali::DeviceStatus::Battery::Status status )
-{
- Dali::Application application(this);
- mBatteryLowSignal.Emit( application );
-
- mLowBatterySignal.Emit( status );
-}
-
-void Application::OnMemoryLow( Dali::DeviceStatus::Memory::Status status )
-{
- Dali::Application application(this);
- mMemoryLowSignal.Emit( application );
-
- mLowMemorySignal.Emit( status );
-}
-void Application::OnResize(Dali::Adaptor& adaptor)
-{
- Dali::Application application(this);
- mResizeSignal.Emit( application );
-}
-
-bool Application::AddIdle( CallbackBase* callback )
-{
- return mAdaptor->AddIdle( callback );
-}
-
-std::string Application::GetRegion() const
-{
- return mFramework->GetRegion();
-}
-
-std::string Application::GetLanguage() const
-{
- return mFramework->GetLanguage();
-}
-
-Dali::Adaptor& Application::GetAdaptor()
-{
- return *mAdaptor;
-}
-
-Dali::Window Application::GetWindow()
-{
- return mWindow;
-}
-
-// Stereoscopy
-
-void Application::SetViewMode( ViewMode viewMode )
-{
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetViewMode( viewMode );
-}
-
-ViewMode Application::GetViewMode() const
-{
- return Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).GetViewMode();
-}
-
-void Application::SetStereoBase( float stereoBase )
-{
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetStereoBase( stereoBase );
-}
-
-float Application::GetStereoBase() const
-{
- return Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).GetStereoBase();
-}
-
-
-void Application::ReplaceWindow( const PositionSize& positionSize, const std::string& name )
-{
- Dali::Window newWindow = Dali::Window::New( positionSize, name, mWindowMode == Dali::Application::TRANSPARENT );
- Window& windowImpl = GetImplementation(newWindow);
- windowImpl.SetAdaptor(*mAdaptor);
-
- int indicatorVisibleMode = mEnvironmentOptions.GetIndicatorVisibleMode();
- if( indicatorVisibleMode >= Dali::Window::INVISIBLE && indicatorVisibleMode <= Dali::Window::AUTO )
- {
- GetImplementation( newWindow ).SetIndicatorVisibleMode( static_cast< Dali::Window::IndicatorVisibleMode >( indicatorVisibleMode ) );
- }
-
- Dali::RenderSurface* renderSurface = windowImpl.GetSurface();
-
- Any nativeWindow = newWindow.GetNativeHandle();
- Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).ReplaceSurface(nativeWindow, *renderSurface);
- mWindow = newWindow;
- mWindowPositionSize = positionSize;
-}
-
-std::string Application::GetResourcePath()
-{
- return Internal::Adaptor::Framework::GetResourcePath();
-}
-
-void Application::SetStyleSheet( const std::string& stylesheet )
-{
- mStylesheet = stylesheet;
-}
-
-
-ApplicationPtr Application::GetPreInitializedApplication()
-{
- return gPreInitializedApplication;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_APPLICATION_H__
-#define __DALI_INTERNAL_APPLICATION_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/math/rect.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <application.h>
-#include <singleton-service.h>
-
-#include <framework.h>
-#include <window-impl.h>
-#include <base/environment-options.h>
-
-namespace Dali
-{
-class Adaptor;
-class Window;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Launchpad
-{
-
-/**
- * @brief Launchpad is used to improve application launch performance.
- * When an application is pre-initialized, so files are preloaded, some functions are initialized and a window is made in advance.
- */
-enum State
-{
- NONE, ///< The default state
- PRE_INITIALIZED ///< Application is pre-initialized.
-};
-
-} // namespace Launchpad
-
-class CommandLineOptions;
-class EventLoop;
-
-typedef Dali::Rect<int> PositionSize;
-
-class Application;
-typedef IntrusivePtr<Application> ApplicationPtr;
-
-/**
- * Implementation of the Application class.
- */
-class Application : public BaseObject, public Framework::Observer
-{
-public:
-
- typedef Dali::Application::LowBatterySignalType LowBatterySignalType;
- typedef Dali::Application::LowMemorySignalType LowMemorySignalType;
- typedef Dali::Application::AppSignalType AppSignalType;
- typedef Dali::Application::AppControlSignalType AppControlSignalType;
- typedef Dali::Application::WINDOW_MODE WINDOW_MODE;
-
- /**
- * Create a new application
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of Dali::Application::WINDOW_MODE
- * @param[in] positionSize A position and a size of the window
- * @param[in] applicationType A member of Dali::Framework::Type
- */
- static ApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet,
- WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType );
-
- /**
- * @copydoc Dali::DevelApplication::PreInitialize()
- */
- static void PreInitialize( int* argc, char** argv[] );
-
-public:
-
- /**
- * @copydoc Dali::Application::MainLoop()
- */
- void MainLoop(Dali::Configuration::ContextLoss configuration);
-
- /**
- * @copydoc Dali::Application::Lower()
- */
- void Lower();
-
- /**
- * @copydoc Dali::Application::Quit()
- */
- void Quit();
-
- /**
- * @copydoc Dali::Application::AddIdle()
- */
- bool AddIdle( CallbackBase* callback );
-
- /**
- * @copydoc Dali::Application::GetAdaptor();
- */
- Dali::Adaptor& GetAdaptor();
-
- /**
- * @copydoc Dali::Application::GetWindow();
- */
- Dali::Window GetWindow();
-
- /**
- * @copydoc Dali::Application::GetRegion();
- */
- std::string GetRegion() const;
-
- /**
- * @copydoc Dali::Application::GetLanguage();
- */
- std::string GetLanguage() const;
-
- /**
- * @copydoc Dali::Application::ReplaceWindow();
- */
- void ReplaceWindow( const PositionSize& positionSize, const std::string& name);
-
- /**
- * @copydoc Dali::Application::GetResourcePath();
- */
- static std::string GetResourcePath();
-
- /**
- * Retrieves the pre-initialized application.
- *
- * @return A pointer to the pre-initialized application
- */
- static ApplicationPtr GetPreInitializedApplication();
-
-public: // Stereoscopy
-
- /**
- * @copydoc Dali::Application::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::Application::GetViewMode()
- */
- ViewMode GetViewMode() const;
-
- /**
- * @copydoc Dali::Application::SetStereoBase()
- */
- void SetStereoBase( float stereoBase );
-
- /**
- * @copydoc Dali::Application::GetStereoBase()
- */
- float GetStereoBase() const;
-
-public: // Lifecycle functionality
-
- /**
- * Called when OnInit is called or the framework is initialised.
- */
- void DoInit();
-
- /**
- * Called after OnInit is called or the framework is started.
- */
- void DoStart();
-
- /**
- * Called when OnTerminate is called or the framework is terminated.
- */
- void DoTerminate();
-
- /**
- * Called when OnPause is called or the framework is paused.
- */
- void DoPause();
-
- /**
- * Called when OnResume is called or the framework resumes from a paused state.
- */
- void DoResume();
-
- /**
- * Called when OnLanguageChanged is called or the framework informs the application that the language of the device has changed.
- */
- void DoLanguageChange();
-
-public: // From Framework::Observer
-
- /**
- * Called when the framework is initialised.
- */
- virtual void OnInit();
-
- /**
- * Called when the framework is terminated.
- */
- virtual void OnTerminate();
-
- /**
- * Called when the framework is paused.
- */
- virtual void OnPause();
-
- /**
- * Called when the framework resumes from a paused state.
- */
- virtual void OnResume();
-
- /**
- * Called when the framework received AppControlSignal.
- * @param[in] The bundle data of AppControl event.
- */
- virtual void OnAppControl(void *data);
-
- /**
- * Called when the framework informs the application that it should reset itself.
- */
- virtual void OnReset();
-
- /**
- * Called when the framework informs the application that the language of the device has changed.
- */
- virtual void OnLanguageChanged();
-
- /**
- * Called when the framework informs the application that the region of the device has changed.
- */
- virtual void OnRegionChanged();
-
- /**
- * Called when the framework informs the application that the battery level of the device is low.
- */
- virtual void OnBatteryLow( Dali::DeviceStatus::Battery::Status status );
-
- /**
- * Called when the framework informs the application that the memory level of the device is low.
- */
- virtual void OnMemoryLow( Dali::DeviceStatus::Memory::Status status );
-
-public:
-
- /**
- * Signal handler when the adaptor's window resizes itself.
- * @param[in] adaptor The adaptor
- */
- void OnResize(Dali::Adaptor& adaptor);
-
- /**
- * Sets a user defined theme file.
- * This should be called before initialization.
- * @param[in] stylesheet The path to user defined theme file
- */
- void SetStyleSheet( const std::string& stylesheet );
-
-public: // Signals
-
- /**
- * @copydoc Dali::Application::InitSignal()
- */
- Dali::Application::AppSignalType& InitSignal() { return mInitSignal; }
-
- /**
- * @copydoc Dali::Application::TerminateSignal()
- */
- Dali::Application::AppSignalType& TerminateSignal() { return mTerminateSignal; }
-
- /**
- * @copydoc Dali::Application::PauseSignal()
- */
- Dali::Application::AppSignalType& PauseSignal() { return mPauseSignal; }
-
- /**
- * @copydoc Dali::Application::ResumeSignal()
- */
- Dali::Application::AppSignalType& ResumeSignal() { return mResumeSignal; }
-
- /**
- * @copydoc Dali::Application::ResetSignal()
- */
- Dali::Application::AppSignalType& ResetSignal() { return mResetSignal; }
-
- /**
- * @copydoc Dali::Application::AppControlSignal()
- */
- Dali::Application::AppControlSignalType& AppControlSignal() { return mAppControlSignal; }
-
- /**
- * @copydoc Dali::Application::ResizeSignal()
- */
- Dali::Application::AppSignalType& ResizeSignal() { return mResizeSignal; }
-
- /**
- * @copydoc Dali::Application::LanguageChangedSignal()
- */
- Dali::Application::AppSignalType& LanguageChangedSignal() { return mLanguageChangedSignal; }
-
- /**
- * @copydoc Dali::Application::RegionChangedSignal()
- */
- Dali::Application::AppSignalType& RegionChangedSignal() { return mRegionChangedSignal; }
-
- /**
- * @copydoc Dali::Application::BatteryLowSignal()
- */
- Dali::Application::AppSignalType& BatteryLowSignal() { return mBatteryLowSignal; }
-
- /**
- * @copydoc Dali::Application::MemoryLowSignal()
- */
- Dali::Application::AppSignalType& MemoryLowSignal() { return mMemoryLowSignal; }
-
- /**
- * @copydoc Dali::Application::LowBatterySignal()
- */
- Dali::Application::LowBatterySignalType& LowBatterySignal() { return mLowBatterySignal; }
-
- /**
- * @copydoc Dali::Application:::LowMemorySignal()
- */
- Dali::Application::LowMemorySignalType& LowMemorySignal() { return mLowMemorySignal; }
-
-protected:
-
- /**
- * Private Constructor
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of Dali::Application::WINDOW_MODE
- * @param[in] positionSize A position and a size of the window
- * @param[in] applicationType A member of Dali::Framework::Type
- */
- Application( int* argc, char **argv[], const std::string& stylesheet,
- WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType );
-
- /**
- * Destructor
- */
- virtual ~Application();
-
- // Undefined
- Application(const Application&);
- Application& operator=(Application&);
-
- /**
- * Creates the window
- */
- void CreateWindow();
-
- /**
- * Creates the adaptor
- */
- void CreateAdaptor();
-
- /**
- * Quits from the main loop
- */
- void QuitFromMainLoop();
-
-private:
-
- AppSignalType mInitSignal;
- AppSignalType mTerminateSignal;
- AppSignalType mPauseSignal;
- AppSignalType mResumeSignal;
- AppSignalType mResetSignal;
- AppSignalType mResizeSignal;
- AppControlSignalType mAppControlSignal;
- AppSignalType mLanguageChangedSignal;
- AppSignalType mRegionChangedSignal;
- AppSignalType mBatteryLowSignal;
- AppSignalType mMemoryLowSignal;
- LowBatterySignalType mLowBatterySignal;
- LowMemorySignalType mLowMemorySignal;
-
- EventLoop* mEventLoop;
- Framework* mFramework;
-
- Dali::Configuration::ContextLoss mContextLossConfiguration;
- CommandLineOptions* mCommandLineOptions;
-
- Dali::SingletonService mSingletonService;
- Dali::Adaptor* mAdaptor;
- Dali::Window mWindow;
- Dali::Application::WINDOW_MODE mWindowMode;
- std::string mName;
- std::string mStylesheet;
- EnvironmentOptions mEnvironmentOptions;
- PositionSize mWindowPositionSize;
- Launchpad::State mLaunchpadState;
- bool mUseRemoteSurface;
-
- SlotDelegate< Application > mSlotDelegate;
-
- static ApplicationPtr gPreInitializedApplication;
-};
-
-inline Application& GetImplementation(Dali::Application& application)
-{
- DALI_ASSERT_ALWAYS(application && "application handle is empty");
-
- BaseObject& handle = application.GetBaseObject();
-
- return static_cast<Internal::Adaptor::Application&>(handle);
-}
-
-inline const Application& GetImplementation(const Dali::Application& application)
-{
- DALI_ASSERT_ALWAYS(application && "Timre handle is empty");
-
- const BaseObject& handle = application.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::Application&>(handle);
-}
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_APPLICATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "clipboard-event-notifier-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::ClipboardEventNotifier ClipboardEventNotifier::New()
-{
- Dali::ClipboardEventNotifier notifier = Dali::ClipboardEventNotifier(new ClipboardEventNotifier());
-
- return notifier;
-}
-
-Dali::ClipboardEventNotifier ClipboardEventNotifier::Get()
-{
- Dali::ClipboardEventNotifier notifier;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ClipboardEventNotifier ) );
- if(handle)
- {
- // If so, downcast the handle
- notifier = Dali::ClipboardEventNotifier( dynamic_cast< ClipboardEventNotifier* >( handle.GetObjectPtr() ) );
- }
- else
- {
- notifier = Dali::ClipboardEventNotifier( ClipboardEventNotifier::New() );
- service.Register( typeid( notifier ), notifier );
- }
- }
-
- return notifier;
-}
-
-const std::string& ClipboardEventNotifier::GetContent() const
-{
- return mContent;
-}
-
-void ClipboardEventNotifier::SetContent( const std::string& content )
-{
- mContent = content;
-}
-
-void ClipboardEventNotifier::ClearContent()
-{
- mContent.clear();
-}
-
-void ClipboardEventNotifier::EmitContentSelectedSignal()
-{
- if ( !mContentSelectedSignal.Empty() )
- {
- Dali::ClipboardEventNotifier handle( this );
- mContentSelectedSignal.Emit( handle );
- }
-}
-
-ClipboardEventNotifier::ClipboardEventNotifier()
-: mContent()
-{
-}
-
-ClipboardEventNotifier::~ClipboardEventNotifier()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
-#define __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/math/vector2.h>
-
-// INTERNAL INCLUDES
-#include <clipboard-event-notifier.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * This class listens to Clipboard events.
- */
-class ClipboardEventNotifier : public Dali::BaseObject
-{
-public:
-
- typedef Dali::ClipboardEventNotifier::ClipboardEventSignalType ClipboardEventSignalType;
-
- // Creation
-
- /**
- * Create a ClipboardEventNotifier.
- * @return A newly allocated clipboard-event-notifier.
- */
- static Dali::ClipboardEventNotifier New();
-
- /**
- * @copydoc Dali::ClipboardEventNotifier::Get()
- */
- static Dali::ClipboardEventNotifier Get();
-
- // Public API
-
- /**
- * @copydoc Dali::ClipboardEventNotifier::GetContent() const
- */
- const std::string& GetContent() const;
-
- /**
- * Sets the selected content.
- * @param[in] content A string that represents the content that has been selected.
- */
- void SetContent( const std::string& content );
-
- /**
- * Clears the stored content.
- */
- void ClearContent();
-
- /**
- * Called when content is selected in the clipboard.
- */
- void EmitContentSelectedSignal();
-
-public: // Signals
-
- /**
- * @copydoc Dali::ClipboardEventNotifier::ContentSelectedSignal
- */
- ClipboardEventSignalType& ContentSelectedSignal()
- {
- return mContentSelectedSignal;
- }
-
-private:
-
- // Construction & Destruction
-
- /**
- * Constructor.
- */
- ClipboardEventNotifier();
-
- /**
- * Destructor.
- */
- virtual ~ClipboardEventNotifier();
-
- // Undefined
- ClipboardEventNotifier( const ClipboardEventNotifier& );
- ClipboardEventNotifier& operator=( ClipboardEventNotifier& );
-
-private:
-
- std::string mContent; ///< The current selected content.
-
- ClipboardEventSignalType mContentSelectedSignal;
-
-public:
-
- // Helpers for public-api forwarding methods
-
- inline static Internal::Adaptor::ClipboardEventNotifier& GetImplementation(Dali::ClipboardEventNotifier& detector)
- {
- DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" );
-
- BaseObject& handle = detector.GetBaseObject();
-
- return static_cast<Internal::Adaptor::ClipboardEventNotifier&>(handle);
- }
-
- inline static const Internal::Adaptor::ClipboardEventNotifier& GetImplementation(const Dali::ClipboardEventNotifier& detector)
- {
- DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" );
-
- const BaseObject& handle = detector.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::ClipboardEventNotifier&>(handle);
- }
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_CLIPBOARD_H__
-#define __DALI_INTERNAL_CLIPBOARD_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <clipboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Implementation of the Clip Board
- */
-
-class Clipboard : public Dali::BaseObject
-{
-public:
-
- // Hide the specific windowing system
- struct Impl;
-
- /**
- * @copydoc Dali::ClipboardEventNotifier::Get()
- */
- static Dali::Clipboard Get();
-
- /**
- * Constructor
- * @param[in] impl Some data from a specific windowing system.
- */
- Clipboard(Impl* impl);
-
- /**
- * Destructor
- */
- virtual ~Clipboard();
-
- /**
- * @copydoc Dali::Clipboard::SetItem()
- */
- bool SetItem(const std::string &itemData);
-
- /**
- * @copydoc Dali::Clipboard::RequestItem()
- */
- void RequestItem();
-
- /**
- * @copydoc Dali::Clipboard::NumberOfClipboardItems()
- */
- unsigned int NumberOfItems();
-
- /**
- * @copydoc Dali::Clipboard::ShowClipboard()
- */
- void ShowClipboard();
-
- /**
- * @copydoc Dali::Clipboard::HideClipboard()
- */
- void HideClipboard(bool skipFirstHide);
-
- /**
- * @copydoc Dali::Clipboard::IsVisible()
- */
- bool IsVisible() const;
-
- /**
- * @brief exchange either sending or receiving buffered data
- *
- * @param[in] type true for send buffered data, false for receive data to buffer
- * @param[in] event information pointer
- * @return The buffer pointer for send or receive data
- */
- char* ExcuteBuffered( bool type, void *event );
-
-private:
-
- // Undefined
- Clipboard( const Clipboard& );
- Clipboard& operator=( Clipboard& );
-
-private:
-
- Impl* mImpl;
-
-public:
-
-}; // class clipboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-inline static Internal::Adaptor::Clipboard& GetImplementation(Dali::Clipboard& clipboard)
-{
- DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" );
- BaseObject& handle = clipboard.GetBaseObject();
- return static_cast<Internal::Adaptor::Clipboard&>(handle);
-}
-
-inline static const Internal::Adaptor::Clipboard& GetImplementation(const Dali::Clipboard& clipboard)
-{
- DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" );
- const BaseObject& handle = clipboard.GetBaseObject();
- return static_cast<const Internal::Adaptor::Clipboard&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_CLIPBOARD_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "color-controller-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::ColorController ColorController::Get()
-{
- return Dali::ColorController( new ColorController() );
-}
-
-ColorController::ColorController()
-{
-}
-
-ColorController::~ColorController()
-{
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
-{
- return false;
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
-{
- return false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_COLOR_CONTROLLER_H__
-#define __DALI_INTERNAL_COLOR_CONTROLLER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <color-controller.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Implementation of ColorController
- */
-class ColorController : public BaseObject
-{
-public:
-
- /**
- * Constructor.
- */
- ColorController();
-
- /**
- * @copydoc Dali::ColorController::Get()
- */
- static Dali::ColorController Get();
-
- /**
- * @copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&)
- */
- bool RetrieveColor( const std::string& colorCode, Vector4& colorValue );
-
- /**
- *copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&, Vector4&, Vector4&)
- */
- bool RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor);
-
-protected:
- /**
- * Destructor.
- */
- virtual ~ColorController();
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Additional Helpers for public-api forwarding methods
-inline Internal::Adaptor::ColorController& GetImplementation(Dali::ColorController& controller)
-{
- DALI_ASSERT_ALWAYS(controller && "ColorController handle is empty");
- BaseObject& handle = controller.GetBaseObject();
- return static_cast<Internal::Adaptor::ColorController&>(handle);
-}
-
-inline const Internal::Adaptor::ColorController& GetImplementation(const Dali::ColorController& controller)
-{
- DALI_ASSERT_ALWAYS(controller && "ColorController handle is empty");
- const BaseObject& handle = controller.GetBaseObject();
- return static_cast<const Internal::Adaptor::ColorController&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_COLOR_CONTROLLER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "command-line-options.h"
-
-// EXTERNAL INCLUDES
-#include <getopt.h>
-#include <stdlib.h>
-#include <string.h>
-#include <iostream>
-
-#include <dali/public-api/common/dali-vector.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-struct Argument
-{
- const char * const opt;
- const char * const optDescription;
-
- void Print()
- {
- const std::ios_base::fmtflags flags = std::cout.flags();
- std::cout << std::left << " --";
- std::cout.width( 18 );
- std::cout << opt;
- std::cout << optDescription;
- std::cout << std::endl;
- std::cout.flags( flags );
- }
-};
-
-Argument EXPECTED_ARGS[] =
-{
- { "no-vsync", "Disable VSync on Render" },
- { "width", "Stage Width" },
- { "height", "Stage Height" },
- { "dpi", "Emulated DPI" },
- { "view", "Stereocopic 3D view mode ([0]=MONO, 1=STEREO_HORIZONTAL, 2=STEREO_VERTICAL, 3=STEREO_INTERLACED)" },
- { "stereo-base", "Distance in millimeters between left/right cameras [65.0]" },
- { "help", "Help" },
- { NULL, NULL }
-};
-
-enum Option
-{
- OPTION_NO_VSYNC = 0,
- OPTION_STAGE_WIDTH,
- OPTION_STAGE_HEIGHT,
- OPTION_DPI,
- OPTION_STEREO_MODE,
- OPTION_STEREO_BASE,
- OPTION_HELP
-};
-
-typedef Dali::Vector< int > UnhandledContainer;
-
-void ShowHelp()
-{
- std::cout << "Available options:" << std::endl;
- Argument* arg = EXPECTED_ARGS;
- while ( arg->opt )
- {
- arg->Print();
- ++arg;
- }
-}
-
-} // unnamed namespace
-
-CommandLineOptions::CommandLineOptions(int *argc, char **argv[])
-: noVSyncOnRender(0),
- stageWidth(0), stageHeight(0),
- viewMode(0),
- stereoBase(65)
-{
- // Exit gracefully if no arguments provided
- if ( !argc || !argv )
- {
- return;
- }
-
- if ( *argc > 1 )
- {
- // We do not want to print out errors.
- int origOptErrValue( opterr );
- opterr = 0;
-
- int help( 0 );
-
- const struct option options[]=
- {
- { EXPECTED_ARGS[OPTION_NO_VSYNC].opt, no_argument, &noVSyncOnRender, 1 }, // "--no-vsync"
- { EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w' }, // "--width"
- { EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h' }, // "--height"
- { EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd' }, // "--dpi"
- { EXPECTED_ARGS[OPTION_STEREO_MODE].opt, required_argument, NULL, 'v' }, // "--view"
- { EXPECTED_ARGS[OPTION_STEREO_BASE].opt, required_argument, NULL, 's' }, // "--stereo-base"
- { EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?' }, // "--help"
- { 0, 0, 0, 0 } // end of options
- };
-
- int shortOption( 0 );
- int optionIndex( 0 );
-
- const char* optString = "-w:h:d:v:s:"; // The '-' ensures that argv is NOT permuted
- bool optionProcessed( false );
-
- UnhandledContainer unhandledOptions; // We store indices of options we do not handle here
-
- do
- {
- shortOption = getopt_long( *argc, *argv, optString, options, &optionIndex );
-
- switch ( shortOption )
- {
- case 0:
- {
- // Check if we want help
- if ( help )
- {
- ShowHelp();
- optionProcessed = true;
- }
- break;
- }
-
- case 'w':
- {
- if ( optarg )
- {
- stageWidth = atoi( optarg );
- optionProcessed = true;
- }
- break;
- }
-
- case 'h':
- {
- if ( optarg )
- {
- stageHeight = atoi( optarg );
- optionProcessed = true;
- }
- break;
- }
-
- case 'd':
- {
- if ( optarg )
- {
- stageDPI.assign( optarg );
- optionProcessed = true;
- }
- break;
- }
-
- case 'v':
- {
- if ( optarg )
- {
- viewMode = atoi(optarg);
- optionProcessed = true;
- }
- break;
- }
-
- case 's':
- {
- if ( optarg )
- {
- stereoBase = atoi(optarg);
- optionProcessed = true;
- }
- break;
- }
-
- case -1:
- {
- // All command-line options have been parsed.
- break;
- }
-
- default:
- {
- unhandledOptions.PushBack( optind - 1 );
- break;
- }
- }
- } while ( shortOption != -1 );
-
- // Take out the options we have processed
- if ( optionProcessed )
- {
- if ( unhandledOptions.Count() > 0 )
- {
- int index( 1 );
-
- // Overwrite the argv with the values from the unhandled indices
- const UnhandledContainer::ConstIterator endIter = unhandledOptions.End();
- for ( UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter )
- {
- (*argv)[ index++ ] = (*argv)[ *iter ];
- }
- *argc = unhandledOptions.Count() + 1; // +1 for the program name
- }
- else
- {
- // There are no unhandled options, so we should just have the program name
- *argc = 1;
- }
-
- optind = 1; // Reset to start
- }
-
- opterr = origOptErrValue; // Reset opterr value.
- }
-}
-
-CommandLineOptions::~CommandLineOptions()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "drag-and-drop-detector-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::DragAndDropDetector DragAndDropDetector::New()
-{
- Dali::DragAndDropDetector detector = Dali::DragAndDropDetector(new DragAndDropDetector());
-
- return detector;
-}
-
-const std::string& DragAndDropDetector::GetContent() const
-{
- return mContent;
-}
-
-Vector2 DragAndDropDetector::GetCurrentScreenPosition() const
-{
- return mScreenPosition;
-}
-
-bool DragAndDropDetector::IsEnabled() const
-{
- return !mDroppedSignal.Empty() || !mEnteredSignal.Empty() || !mExitedSignal.Empty() || !mMovedSignal.Empty() ;
-}
-
-void DragAndDropDetector::SetContent( const std::string& content )
-{
- mContent = content;
-}
-
-void DragAndDropDetector::ClearContent()
-{
- mContent.clear();
-}
-
-void DragAndDropDetector::SetPosition( Vector2 screenPosition )
-{
- mScreenPosition = screenPosition;
-}
-
-void DragAndDropDetector::EmitEnteredSignal()
-{
- if ( !mEnteredSignal.Empty() )
- {
- Dali::DragAndDropDetector handle( this );
- mEnteredSignal.Emit( handle );
- }
-}
-
-void DragAndDropDetector::EmitExitedSignal()
-{
- if ( !mExitedSignal.Empty() )
- {
- Dali::DragAndDropDetector handle( this );
- mExitedSignal.Emit( handle );
- }
-}
-
-void DragAndDropDetector::EmitMovedSignal()
-{
- if ( !mMovedSignal.Empty() )
- {
- Dali::DragAndDropDetector handle( this );
- mMovedSignal.Emit( handle );
- }
-}
-
-void DragAndDropDetector::EmitDroppedSignal()
-{
- if ( !mDroppedSignal.Empty() )
- {
- Dali::DragAndDropDetector handle( this );
- mDroppedSignal.Emit( handle );
- }
-}
-
-DragAndDropDetector::DragAndDropDetector()
-: mContent(),
- mScreenPosition()
-{
-}
-
-DragAndDropDetector::~DragAndDropDetector()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
-#define __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/math/vector2.h>
-
-// INTERNAL INCLUDES
-#include <drag-and-drop-detector.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-typedef IntrusivePtr< DragAndDropDetector > DragAndDropDetectorPtr;
-
-/**
- * This class listens to Drag & Drop events.
- */
-class DragAndDropDetector : public Dali::BaseObject
-{
-public:
-
- typedef Dali::DragAndDropDetector::DragAndDropSignal DragAndDropSignal;
-
- // Creation
-
- /**
- * Create a DragAndDropDetector.
- * This should only be called once by the Window class.
- * @return A newly allocated drag-and-drop-detector.
- */
- static Dali::DragAndDropDetector New();
-
- // Public API
-
- /**
- * @copydoc Dali::DragAndDropDetector::GetContent() const
- */
- const std::string& GetContent() const;
-
- /**
- * @copydoc Dali::DragAndDropDetector::GetCurrentScreenPosition() const
- */
- Vector2 GetCurrentScreenPosition() const;
-
- // Called by Drag & Drop Event Handler
-
- /**
- * Queries whether drag & drop behaviour is really required.
- * @return true if drag & drop required, false otherwise.
- */
- bool IsEnabled() const;
-
- /**
- * Sets the dragged content.
- * @param[in] content A string that represents the content that has been dropped.
- */
- void SetContent( const std::string& content );
-
- /**
- * Clears the stored content.
- */
- void ClearContent();
-
- /**
- * Sets the position the drop occurred.
- */
- void SetPosition( Vector2 screenPosition );
-
- /**
- * Called when a draggable object enters our window.
- */
- void EmitEnteredSignal();
-
- /**
- * Called when a draggable object leaves our window.
- */
- void EmitExitedSignal();
-
- /**
- * Called when a draggable object leaves our window.
- */
- void EmitMovedSignal();
-
- /**
- * Is called when a drop actually occurs.
- */
- void EmitDroppedSignal();
-
-public: // Signals
-
- /**
- * @copydoc Dali::DragAndDropDetector::EnteredSignal
- */
- DragAndDropSignal& EnteredSignal()
- {
- return mEnteredSignal;
- }
-
- /**
- * @copydoc Dali::DragAndDropDetector::ExitedSignal
- */
- DragAndDropSignal& ExitedSignal()
- {
- return mExitedSignal;
- }
-
- /**
- * @copydoc Dali::DragAndDropDetector::MovedSignal
- */
- DragAndDropSignal& MovedSignal()
- {
- return mMovedSignal;
- }
-
- /**
- * @copydoc Dali::DragAndDropDetector::DroppedSignal
- */
- DragAndDropSignal& DroppedSignal()
- {
- return mDroppedSignal;
- }
-
-private:
-
- // Construction & Destruction
-
- /**
- * Constructor.
- */
- DragAndDropDetector();
-
- /**
- * Destructor.
- */
- virtual ~DragAndDropDetector();
-
- // Undefined
- DragAndDropDetector( const DragAndDropDetector& );
- DragAndDropDetector& operator=( DragAndDropDetector& );
-
-private:
-
- std::string mContent; ///< The current Drag & drop content.
- Vector2 mScreenPosition; ///< The screen position of the drop location.
-
- DragAndDropSignal mEnteredSignal;
- DragAndDropSignal mExitedSignal;
- DragAndDropSignal mMovedSignal;
- DragAndDropSignal mDroppedSignal;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::DragAndDropDetector& GetImplementation(Dali::DragAndDropDetector& detector)
-{
- DALI_ASSERT_ALWAYS( detector && "DragAndDropDetector handle is empty" );
-
- BaseObject& handle = detector.GetBaseObject();
-
- return static_cast<Internal::Adaptor::DragAndDropDetector&>(handle);
-}
-
-inline const Internal::Adaptor::DragAndDropDetector& GetImplementation(const Dali::DragAndDropDetector& detector)
-{
- DALI_ASSERT_ALWAYS( detector && "DragAndDropDetector handle is empty" );
-
- const BaseObject& handle = detector.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::DragAndDropDetector&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-callback-manager.h"
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Structure contains the callback function and control options
- */
-struct CallbackData
-{
-
- /**
- * Constructor
- */
- CallbackData( CallbackBase* callback )
- : mCallback(callback),
- mRemoveFromContainerFunction(NULL),
- mIdler(NULL)
- {
- }
- /**
- * Destructor
- */
- ~CallbackData()
- {
- delete mCallback;
- delete mRemoveFromContainerFunction;
- }
-
- CallbackBase* mCallback; ///< call back
- CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container
- Ecore_Idler* mIdler; ///< ecore idler
- };
-
-namespace
-{
-
-/**
- * Called from the main thread while idle.
- */
-Eina_Bool IdleCallback(void *data)
-{
- CallbackData *callbackData = static_cast< CallbackData * >( data );
-
- // remove callback data from the container
- CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData );
-
- // run the function
- CallbackBase::Execute( *callbackData->mCallback );
-
- // delete our data
- delete callbackData;
-
- // CALLBACK Cancel will delete the idler so we don't need to call ecore_idler_del
- return ECORE_CALLBACK_CANCEL;
-}
-
-} // unnamed namespace
-
-EcoreCallbackManager::EcoreCallbackManager()
-:mRunning(false)
-{
-}
-
-
-void EcoreCallbackManager::Start()
-{
- DALI_ASSERT_DEBUG( mRunning == false );
-
- mRunning = true;
-}
-
-void EcoreCallbackManager::Stop()
-{
- // make sure we're not called twice
- DALI_ASSERT_DEBUG( mRunning == true );
-
- RemoveAllCallbacks();
-
- mRunning = false;
-
-}
-
-bool EcoreCallbackManager::AddIdleCallback( CallbackBase* callback )
-{
- if( !mRunning )
- {
- return false;
- }
-
- CallbackData* callbackData = new CallbackData( callback );
-
- callbackData->mRemoveFromContainerFunction = MakeCallback( this, &EcoreCallbackManager::RemoveCallbackFromContainer );
-
- // add the call back to the container
- mCallbackContainer.push_front(callbackData);
-
- // add the idler
- callbackData->mIdler = ecore_idler_add( IdleCallback, callbackData);
-
- DALI_ASSERT_ALWAYS( ( callbackData->mIdler != NULL ) && "Idle method not created" );
-
- return true;
-}
-
-void EcoreCallbackManager::RemoveIdleCallback( CallbackBase* callback )
-{
- for( CallbackList::iterator it = mCallbackContainer.begin(),
- endIt = mCallbackContainer.end();
- it != endIt;
- ++it )
- {
- CallbackData* data = *it;
-
- if( data->mCallback == callback )
- {
- // remove callback data from the container.
- CallbackBase::Execute( *data->mRemoveFromContainerFunction, data );
-
- ecore_idler_del( data->mIdler );
- }
- }
-}
-
-void EcoreCallbackManager::RemoveCallbackFromContainer(CallbackData *callbackData)
-{
- mCallbackContainer.remove(callbackData);
-}
-
-void EcoreCallbackManager::RemoveAllCallbacks()
-{
- // always called from main thread
- for( CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter)
- {
- CallbackData* data = (*iter);
-
- ecore_idler_del( data->mIdler );
-
- delete data;
-
- }
- mCallbackContainer.clear();
-}
-
-// Creates a concrete interface for CallbackManager
-CallbackManager* CallbackManager::New()
-{
- return new EcoreCallbackManager;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_ECORE_CALLBACK_MANAGER_H__
-#define __DALI_ECORE_CALLBACK_MANAGER_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <list>
-
-// INTERNAL INCLUDES
-#include <callback-manager.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-struct CallbackData;
-
-/**
- * Ecore interface to install call backs in the applications main loop.
- */
-class EcoreCallbackManager : public CallbackManager
-{
-
-public:
-
- /**
- * @brief constructor
- */
- EcoreCallbackManager();
-
- /**
- * @brief destructor
- */
- ~EcoreCallbackManager()
- {
- }
-
- /**
- * @copydoc CallbackManager::AddIdleCallback()
- */
- virtual bool AddIdleCallback( CallbackBase* callback );
-
- /**
- * @copydoc CallbackManager::RemoveIdleCallback()
- */
- virtual void RemoveIdleCallback( CallbackBase* callback );
-
- /**
- * @copydoc CallbackManager::Start()
- */
- virtual void Start();
-
- /**
- * @copydoc CallbackManager::Stop()
- */
- virtual void Stop();
-
-private:
-
- /**
- * @brief Remove all idle call backs that are pending
- * Called by Stop()
- * Always called from the main thread
- */
- void RemoveAllCallbacks();
-
- /**
- * @brief Removes a single call back from the container
- * Always called from main thread
- * @param callbackData callback data
- */
- void RemoveCallbackFromContainer(CallbackData *callbackData);
-
- /**
- * @brief Remove a standard call back from ecore
- * Always called from main thread
- * @param callbackData callback data
- */
- void RemoveStandardCallback(CallbackData *callbackData);
-
-
- typedef std::list<CallbackData *> CallbackList;
-
- bool mRunning; ///< flag is set to true if when running
- CallbackList mCallbackContainer; ///< container of live idle callbacks
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_ECORE_CALLBACK_MANAGER_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "file-descriptor-monitor.h"
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-
-// INTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Using Impl to hide away EFL specific members
- */
-struct FileDescriptorMonitor::Impl
-{
- // Construction
- Impl( int fileDescriptor, CallbackBase* callback, int eventsToMonitor)
- : mFileDescriptor( fileDescriptor ),
- mEventsToMonitor( eventsToMonitor ),
- mCallback( callback ),
- mHandler( NULL )
- {
- }
-
- ~Impl()
- {
- delete mCallback;
- }
-
- // Data
- int mFileDescriptor;
- int mEventsToMonitor; ///< what file descriptor events to monitor
- CallbackBase* mCallback;
- Ecore_Fd_Handler* mHandler;
-
- // Static Methods
-
- /**
- * Called when the file descriptor receives an event.
- */
- static Eina_Bool EventDispatch(void* data, Ecore_Fd_Handler *handler)
- {
- Impl* impl = reinterpret_cast<Impl*>(data);
-
- // if we want read events, check to see if a read event is available
- int type = FileDescriptorMonitor::FD_NO_EVENT;
-
- if( ecore_main_fd_handler_active_get( handler, ECORE_FD_ERROR) )
- {
- CallbackBase::Execute( *impl->mCallback, FileDescriptorMonitor::FD_ERROR);
- DALI_LOG_ERROR("ECORE_FD_ERROR occurred on %d\n", impl->mFileDescriptor);
-
- return ECORE_CALLBACK_CANCEL;
- }
-
- if( impl->mEventsToMonitor & ECORE_FD_READ )
- {
- if (ecore_main_fd_handler_active_get( handler, ECORE_FD_READ))
- {
- type = FileDescriptorMonitor::FD_READABLE;
- }
- }
- // check if we want write events
- if( impl->mEventsToMonitor & ECORE_FD_WRITE )
- {
- if (ecore_main_fd_handler_active_get( handler, ECORE_FD_WRITE))
- {
- type |= FileDescriptorMonitor::FD_WRITABLE;
- }
- }
-
- // if there is an event, execute the callback
- if( type != FileDescriptorMonitor::FD_NO_EVENT )
- {
- CallbackBase::Execute( *impl->mCallback, static_cast< FileDescriptorMonitor::EventType >(type ) );
- }
-
- return ECORE_CALLBACK_RENEW;
- }
-};
-
-FileDescriptorMonitor::FileDescriptorMonitor( int fileDescriptor, CallbackBase* callback, int eventBitmask)
-{
- mImpl = new Impl(fileDescriptor, callback, eventBitmask);
-
- if (fileDescriptor < 1)
- {
- DALI_ASSERT_ALWAYS( 0 && "Invalid File descriptor");
- return;
- }
-
- int events = 0;
- if( eventBitmask & FD_READABLE)
- {
- events = ECORE_FD_READ;
- }
- if( eventBitmask & FD_WRITABLE)
- {
- events |= ECORE_FD_WRITE;
- }
- mImpl->mEventsToMonitor = events;
- mImpl->mHandler = ecore_main_fd_handler_add( fileDescriptor, static_cast<Ecore_Fd_Handler_Flags >( events ), &Impl::EventDispatch, mImpl, NULL, NULL );
-
-}
-
-FileDescriptorMonitor::~FileDescriptorMonitor()
-{
- if (mImpl->mHandler)
- {
- ecore_main_fd_handler_del(mImpl->mHandler);
- }
-
- delete mImpl;
- mImpl = NULL;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "timer-impl.h"
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-// LOCAL STUFF
-namespace
-{
-Eina_Bool TimerSourceFunc (void *data)
-{
- Timer* timer = static_cast<Timer*>(data);
-
- bool keepRunning = timer->Tick();
-
- return keepRunning ? EINA_TRUE : EINA_FALSE;
-}
-} // unnamed namespace
-
-/**
- * Struct to hide away Ecore implementation details
- */
-struct Timer::Impl
-{
- Impl( unsigned int milliSec )
- : mId(NULL),
- mInterval(milliSec)
- {
- }
-
- Ecore_Timer * mId;
- unsigned int mInterval;
-};
-
-TimerPtr Timer::New( unsigned int milliSec )
-{
- TimerPtr timer( new Timer( milliSec ) );
- return timer;
-}
-
-Timer::Timer( unsigned int milliSec )
-: mImpl(new Impl(milliSec))
-{
-}
-
-Timer::~Timer()
-{
- ResetTimerData();
- delete mImpl;
-}
-
-void Timer::Start()
-{
- // Timer should be used in the event thread
- DALI_ASSERT_DEBUG( Adaptor::IsAvailable() );
-
- if(mImpl->mId != NULL)
- {
- Stop();
- }
- mImpl->mId = ecore_timer_add( (double)mImpl->mInterval/1000.0f, (Ecore_Task_Cb)TimerSourceFunc, this );
-}
-
-void Timer::Stop()
-{
- // Timer should be used in the event thread
- DALI_ASSERT_DEBUG( Adaptor::IsAvailable() );
-
- ResetTimerData();
-}
-
-void Timer::SetInterval( unsigned int interval )
-{
- // stop existing timer
- Stop();
- mImpl->mInterval = interval;
- // start new tick
- Start();
-}
-
-unsigned int Timer::GetInterval() const
-{
- return mImpl->mInterval;
-}
-
-bool Timer::Tick()
-{
- // Guard against destruction during signal emission
- Dali::Timer handle( this );
-
- bool retVal( false );
-
- // Override with new signal if used
- if( !mTickSignal.Empty() )
- {
- retVal = mTickSignal.Emit();
-
- // Timer stops if return value is false
- if (retVal == false)
- {
- Stop();
- }
- else
- {
- retVal = true; // continue emission
- }
- }
- else // no callbacks registered
- {
- // periodic timer is started but nobody listens, continue
- retVal = true;
- }
-
- return retVal;
-}
-
-Dali::Timer::TimerSignalType& Timer::TickSignal()
-{
- return mTickSignal;
-}
-
-void Timer::ResetTimerData()
-{
- if (mImpl->mId != NULL)
- {
- ecore_timer_del(mImpl->mId);
- mImpl->mId = NULL;
- }
-}
-
-bool Timer::IsRunning() const
-{
- return mImpl->mId != NULL;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_INTERNAL_EVENT_HANDLER_H__
-#define __DALI_INTERNAL_EVENT_HANDLER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/events/key-event-integ.h>
-#include <dali/integration-api/events/point.h>
-#include <dali/integration-api/events/touch-event-combiner.h>
-#include <style-monitor.h>
-
-// INTERNAL INCLUDES
-#include <damage-observer.h>
-#include <drag-and-drop-detector-impl.h>
-#include <accessibility-adaptor-impl.h>
-#include <clipboard-event-notifier-impl.h>
-#include <imf-manager-impl.h>
-#include <rotation-observer.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CoreEventInterface;
-class GestureManager;
-class StyleMonitor;
-
-/**
- * The Event Handler class is responsible for setting up receiving of Ecore events and then converts them
- * to TouchEvents when it does receive them.
- *
- * These TouchEvents are then passed on to Core.
- */
-class EventHandler
-{
-public:
-
- /**
- * Constructor.
- * @param[in] surface The surface where events will be sent to.
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] gestureManager The Gesture Manager.
- * @param[in] damageObserver The damage observer (to pass damage events to).
- * @param[in] dndDetector The Drag & Drop listener (to pass DnD events to).
- */
- EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector );
-
- /**
- * Destructor.
- */
- ~EventHandler();
-
- /**
- * Feed (Send) touch event to core and gesture manager
- * @param[in] touchEvent The touch event holding the touch point information.
- */
- void FeedTouchPoint( TouchPoint& point, int timeStamp );
-
- /**
- * Feed (Send) wheel event to core and gesture manager
- * @param[in] wheelEvent The wheel event
- */
- void FeedWheelEvent( WheelEvent& wheelEvent );
-
- /**
- * Feed (Send) key event to core
- * @param[in] keyEvent The key event holding the key information.
- */
- void FeedKeyEvent( KeyEvent& keyEvent );
-
- /**
- * Feed (Send) an event to core
- * @param[in] event The event information.
- */
- void FeedEvent( Integration::Event& event );
-
- /**
- * Called when the adaptor is paused.
- */
- void Pause();
-
- /**
- * Called when the adaptor is resumed (from pause).
- */
- void Resume();
-
- /**
- * Sets the Drag & Drop detector.
- * @param[in] detector An intrusive pointer to the Drag & Drop listener to set. To unset pass in NULL.
- */
- void SetDragAndDropDetector( DragAndDropDetectorPtr detector );
-
- /**
- * Set the rotation observer (note, some adaptors may not have a rotation observer)
- * @param[in] observer The rotation observer
- */
- void SetRotationObserver( RotationObserver* observer );
-
-private:
-
- /**
- * Send touch event to core.
- * @param[in] point The touch point information.
- * @param[in] timeStamp The time the touch occurred.
- */
- void SendEvent(Integration::Point& point, unsigned long timeStamp);
-
- /**
- * Send key event to core.
- * @param[in] keyEvent The KeyEvent to send.
- */
- void SendEvent(Integration::KeyEvent& keyEvent);
-
- /**
- * Send wheel event to core.
- * @param[in] wheelEvent The wheel event
- */
- void SendWheelEvent( WheelEvent& wheelEvent );
-
- /**
- * Send a style change event to the style monitor.
- * @param[in] styleChange The style that has changed.
- */
- void SendEvent( StyleChange::Type styleChange );
-
- /**
- * Send a window damage event to the observer.
- * @param[in] area Damaged area.
- */
- void SendEvent( const DamageArea& area );
-
- /**
- * Inform rotation observer of rotation prepare event
- * @param[in] rotation The rotation event
- */
- void SendRotationPrepareEvent( const RotationEvent& rotation );
-
- /**
- * Inform rotation observer of rotation prepare event
- */
- void SendRotationRequestEvent();
-
- /**
- * Resets the event handler.
- * Called when the adaptor is paused or resumed.
- */
- void Reset();
-
-private:
-
- // Undefined
- EventHandler( const EventHandler& eventHandler );
-
- // Undefined
- EventHandler& operator=( const EventHandler& eventHandler );
-
-private:
-
- CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
- Dali::Integration::TouchEventCombiner mCombiner; ///< Combines multi-touch events.
- GestureManager& mGestureManager; ///< Reference to the GestureManager, set on construction, to send touch events to for analysis.
- Dali::StyleMonitor mStyleMonitor; ///< Handle to the style monitor, set on construction, to send font size and font change events to.
- DamageObserver& mDamageObserver; ///< Reference to the DamageObserver, set on construction, to sent damage events to.
- RotationObserver* mRotationObserver; ///< Pointer to rotation observer, if present.
-
- DragAndDropDetectorPtr mDragAndDropDetector; ///< Pointer to the drag & drop detector, to send Drag & Drop events to.
- Dali::AccessibilityAdaptor mAccessibilityAdaptor; ///< Pointer to the accessibility adaptor
- Dali::ClipboardEventNotifier mClipboardEventNotifier; ///< Pointer to the clipboard event notifier
- Dali::Clipboard mClipboard;///< Pointer to the clipboard
-
- struct Impl; ///< Implementation
- Impl* mImpl; ///< Created on construction and destroyed on destruction.
-
- bool mPaused; ///< The paused state of the adaptor.
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_EVENT_HANDLER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "gesture-manager.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-#include <events/long-press-gesture-detector.h>
-#include <events/pan-gesture-detector.h>
-#include <events/pinch-gesture-detector.h>
-#include <events/tap-gesture-detector.h>
-#include <base/core-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Integration::Log::Filter* gLogFilter = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_GESTURE_MANAGER" );
-
-/**
- * Helper method to return the string representation of a gesture type.
- */
-const char * GetGestureTypeString( Gesture::Type type )
-{
- static const char * const pinch( "Pinch" );
- static const char * const pan( "Pan" );
- static const char * const tap( "tap" );
- static const char * const longPress( "LongPress" );
- static const char * const invalid( "Invalid" );
-
- const char * retVal( NULL );
-
- switch ( type )
- {
- case Gesture::LongPress:
- {
- retVal = longPress;
- break;
- }
-
- case Gesture::Pan:
- {
- retVal = pan;
- break;
- }
-
- case Gesture::Pinch:
- {
- retVal = pinch;
- break;
- }
-
- case Gesture::Tap:
- {
- retVal = tap;
- break;
- }
-
- default:
- retVal = invalid;
- break;
- }
-
- return retVal;
-};
-#endif // DEBUG_ENABLED
-
-const float MINIMUM_DISTANCE_DELTA_DIVISOR = 85.0f;
-} // unnamed namespace
-
-GestureManager::GestureManager(CoreEventInterface& coreEventInterface, Vector2 screenSize,CallbackManager* callbackManager, EnvironmentOptions& environmentOptions)
-: mCoreEventInterface( coreEventInterface ),
- mScreenSize( screenSize ),
- mCallbackManager( callbackManager ),
- mEnvironmentOptions( environmentOptions ),
- mMinimumDistanceDelta(-1.0f),
- mRunning( true ) // This allows gestures to be created before Adaptor::Start() is called e.g. by Indicator
-{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Creating GestureManager\n" );
-}
-
-GestureManager::~GestureManager()
-{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Destroying GestureManager\n" );
-}
-
-void GestureManager::SendEvent(const Integration::TouchEvent& event)
-{
- if (mRunning)
- {
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SendEvent: START\n" );
-
- // gestures can be added / deleted during SendEvent so we make a copy of the container.
- // the gestures are reference counted, so unused gesture detectors will be deleted when
- // the local variable detectors goes out of scope.
- GestureDetectorContainer detectors( mGestureDetectors );
-
- // Send the event to all gesture detectors.
- for ( GestureDetectorContainer::iterator iter = detectors.begin(), endIter = detectors.end(); iter != endIter; ++iter )
- {
- (*iter)->SendEvent(event);
- }
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SendEvent: END\n" );
- }
-}
-
-void GestureManager::Stop()
-{
- if (mRunning)
- {
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Stop\n" );
-
- mGestureDetectors.clear();
- mRunning = false;
- }
-}
-
-void GestureManager::SetMinimumPinchDistance(float distance)
-{
- mMinimumDistanceDelta = distance;
- for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
- {
- if ( ( *iter )->GetType() == Gesture::Pinch )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Set Minimum Pinch Distance: %f\n", distance );
- PinchGestureDetector* gestureDetector = static_cast<PinchGestureDetector*>(iter->Get());
- gestureDetector->SetMinimumPinchDistance(distance);
- break;
- }
- }
-}
-
-void GestureManager::Register(const Integration::GestureRequest& request)
-{
- if (mRunning)
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Creating %s Detector\n", GetGestureTypeString( request.type ) );
-
- switch (request.type)
- {
- case Gesture::LongPress:
- {
- GestureDetectorPtr gesture = new LongPressGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::LongPressGestureRequest&>(request));
- mGestureDetectors.push_back(gesture);
- break;
- }
-
- case Gesture::Pan:
- {
- GestureDetectorPtr gesture = new PanGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::PanGestureRequest&>(request), mEnvironmentOptions);
- mGestureDetectors.push_back(gesture);
- break;
- }
-
- case Gesture::Pinch:
- {
- float minPinchDistance = mMinimumDistanceDelta >= 0.0f ? mMinimumDistanceDelta : (mScreenSize.height / MINIMUM_DISTANCE_DELTA_DIVISOR);
- GestureDetectorPtr gesture = new PinchGestureDetector(mCoreEventInterface, mScreenSize, minPinchDistance);
- mGestureDetectors.push_back(gesture);
- break;
- }
-
- case Gesture::Tap:
- {
- GestureDetectorPtr gesture = new TapGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::TapGestureRequest&>(request));
- mGestureDetectors.push_back(gesture);
- break;
- }
-
- default:
- DALI_ASSERT_DEBUG(false);
- break;
- }
- }
-}
-
-void GestureManager::Unregister(const Integration::GestureRequest& request)
-{
- if ( mRunning )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Unregister: %s\n", GetGestureTypeString( request.type ) );
-
- DeleteGestureDetector( request.type );
-
- }
-}
-
-void GestureManager::Update(const Integration::GestureRequest& request)
-{
- for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter < endIter; ++iter )
- {
- if ( (*iter)->GetType() == request.type )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Update: %s\n", GetGestureTypeString( request.type ) );
- (*iter)->Update( request );
- break;
- }
- }
-}
-
-void GestureManager::DeleteGestureDetector( Gesture::Type type )
-{
- for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
- {
- if ( ( *iter )->GetType() == type )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "DeleteGestureDetector: %s\n", GetGestureTypeString( type ) );
- mGestureDetectors.erase( iter );
- break;
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_GESTURE_MANAGER_H__
-#define __DALI_INTERNAL_GESTURE_MANAGER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/math/vector2.h>
-#include <dali/integration-api/gesture-manager.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-struct TouchEvent;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CallbackManager;
-class CoreEventInterface;
-class EnvironmentOptions;
-
-/**
- * Implementation of the Integration::GestureManager.
- *
- * Contains a list of adaptor gesture detectors. It passes touch events to each required detector which
- * in turn process them to determine if their corresponding gesture has occurred.
- */
-class GestureManager : public Integration::GestureManager
-{
-public:
-
- /**
- * Constructor.
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] screenSize The size of the screen.
- * @param[in] callbackManager used to install callbacks
- * @param[in] environmentOptions Environment Options
- */
- GestureManager(CoreEventInterface& coreEventInterface, Vector2 screenSize, CallbackManager* callbackManager, EnvironmentOptions& environmentOptions);
-
- /**
- * The destructor
- */
- virtual ~GestureManager();
-
-public:
-
- /**
- * Used by the event handler to send touch events to the Gesture Manager.
- * @param[in] event The latest touch event.
- */
- void SendEvent(const Integration::TouchEvent& event);
-
- /**
- * Used by the event handler to stop the GestureManager detection.
- */
- void Stop();
-
- /**
- * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
- * trigger a pinch gesture
- *
- * @param[in] distance The minimum pinch distance in pixels
- */
- void SetMinimumPinchDistance(float distance);
-
-public: // GestureManager overrides
-
- /**
- * copydoc Dali::Integration::GestureManager::Register(const Integration::GestureRequest&)
- */
- virtual void Register(const Integration::GestureRequest& request);
-
- /**
- * copydoc Dali::Integration::GestureManager::Unregister(const Integration::GestureRequest&)
- */
- virtual void Unregister(const Integration::GestureRequest& request);
-
- /**
- * copydoc Dali::Integration::GestureManager::Unregister(const Integration::GestureRequest&)
- */
- virtual void Update(const Integration::GestureRequest& request);
-
-private:
-
- /**
- * Used to delete the gesture detector of the given type.
- */
- void DeleteGestureDetector( Gesture::Type type );
-
-private:
-
- typedef std::vector<GestureDetectorPtr> GestureDetectorContainer;
-
- CoreEventInterface& mCoreEventInterface;
- GestureDetectorContainer mGestureDetectors;
- Vector2 mScreenSize;
- CallbackManager* mCallbackManager;
- EnvironmentOptions& mEnvironmentOptions;
- float mMinimumDistanceDelta; ///< The minimum distance before a pinch is applicable. (-1.0f means pinch detector uses default value)
- bool mRunning; ///< States whether the GestureManager is running or not.
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_GESTURE_MANAGER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "long-press-gesture-detector.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/math/vector2.h>
-
-#include <dali/integration-api/events/gesture-requests.h>
-#include <dali/integration-api/events/long-press-gesture-event.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-
-#include <system-settings.h>
-
-// INTERNAL INCLUDES
-#include <base/core-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-// TODO: Set these according to DPI
-const float MAXIMUM_MOTION_ALLOWED = 60.0f;
-// TODO: Set this time according to system setting (vconf)
-const unsigned long LONG_PRESS_TIME = 500u;
-} // unnamed namespace
-
-LongPressGestureDetector::LongPressGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::LongPressGestureRequest& request)
-: GestureDetector(screenSize, Gesture::LongPress),
- mCoreEventInterface(coreEventInterface),
- mState(Clear),
- mMinimumTouchesRequired(request.minTouches),
- mMaximumTouchesRequired(request.maxTouches),
- mTouchTime(0),
- mTimerSlot( this )
-{
- mTimer = Dali::Timer::New(GetSystemValue());
- mTimer.TickSignal().Connect( mTimerSlot, &LongPressGestureDetector::TimerCallback );
-}
-
-LongPressGestureDetector::~LongPressGestureDetector()
-{
-}
-
-void LongPressGestureDetector::SendEvent(const Integration::TouchEvent& event)
-{
- unsigned int pointCount( event.GetPointCount() );
-
- switch (mState)
- {
- // Clear: Wait till one point touches the screen before starting timer.
- case Clear:
- {
- const Integration::Point& point = event.points[0];
-
- if ( point.GetState() == PointState::DOWN )
- {
- mTouchPositions.clear();
- mTouchPositions[point.GetDeviceId()] = point.GetScreenPosition();
-
- mTouchTime = event.time;
-
- mTimer.SetInterval(GetSystemValue());
- mTimer.Start();
-
- // A long press gesture may be possible, tell Core about this and change state to Touched.
- mState = Touched;
- EmitGesture( Gesture::Possible );
- }
-
- break;
- }
-
- // Touched: Monitor movement and addition/removal of points.
- case Touched:
- {
- if (pointCount > mMaximumTouchesRequired)
- {
- // A long press did not occur, tell Core that it was cancelled and change state to Failed.
- EmitGesture( Gesture::Cancelled );
- mTouchPositions.clear();
- mTimer.Stop();
- mState = Failed;
- break;
- }
-
- bool endLoop(false);
-
- for ( Integration::PointContainerConstIterator iter = event.points.begin(), endIter = event.points.end();
- iter != endIter && !endLoop; ++iter)
- {
- switch( iter->GetState() )
- {
- // add point.
- case PointState::DOWN:
- {
- mTouchPositions[iter->GetDeviceId()] = iter->GetScreenPosition();
- break;
- }
-
- // remove point.
- case PointState::UP:
- case PointState::INTERRUPTED:
- {
- // System has interrupted us, long press is not possible, inform Core
- EmitGesture( Gesture::Cancelled );
- mTouchPositions.clear();
- mTimer.Stop();
- mState = ( pointCount == 1 ) ? Clear : Failed; // Change state to Clear if only one point, Failed otherwise.
- endLoop = true;
- break;
- }
-
- case PointState::MOTION:
- {
- const Vector2 touchPosition( mTouchPositions[iter->GetDeviceId()] - iter->GetScreenPosition() );
- float distanceSquared = touchPosition.LengthSquared();
-
- if (distanceSquared > ( MAXIMUM_MOTION_ALLOWED * MAXIMUM_MOTION_ALLOWED ) )
- {
- // We have moved more than the allowable motion for a long press gesture. Inform Core and change state to Failed.
- EmitGesture( Gesture::Cancelled );
- mTimer.Stop();
- mState = Failed;
- endLoop = true;
- }
- break;
- }
-
- case PointState::STATIONARY:
- case PointState::LEAVE:
- {
- break;
- }
- }
- }
- break;
- }
-
- // Failed/Finished: Monitor the touches, waiting for all touches to be released.
- case Failed:
- case Finished:
- {
- // eventually the final touch point will be removed, marking the end of this gesture.
- if ( pointCount == 1 )
- {
- PointState::Type primaryPointState = event.points[0].GetState();
-
- if ( (primaryPointState == PointState::UP) || (primaryPointState == PointState::INTERRUPTED) )
- {
- if(mState == Finished)
- {
- // When the last touch point is lifted, we should inform the Core that the Long press has finished.
- EmitGesture(Gesture::Finished);
- }
- mTouchPositions.clear();
- mState = Clear; // Reset state to clear when last touch point is lifted.
- }
- }
- break;
- }
- }
-}
-
-void LongPressGestureDetector::Update(const Integration::GestureRequest& request)
-{
- const Integration::LongPressGestureRequest& longPress = static_cast<const Integration::LongPressGestureRequest&>(request);
-
- mMinimumTouchesRequired = longPress.minTouches;
- mMaximumTouchesRequired = longPress.maxTouches;
-}
-
-bool LongPressGestureDetector::TimerCallback()
-{
- EmitGesture(Gesture::Started);
-
- mState = Finished;
-
- // There is no touch event at this time, so ProcessEvents must be called directly
- mCoreEventInterface.ProcessCoreEvents();
-
- return false;
-}
-
-void LongPressGestureDetector::EmitGesture(Gesture::State state)
-{
- unsigned int touchPoints ( mTouchPositions.size() );
-
- // We should tell Core about the Possible and Cancelled states regardless of whether we have satisfied long press requirements.
- if ( (state == Gesture::Possible) ||
- (state == Gesture::Cancelled) ||
- (touchPoints >= mMinimumTouchesRequired) )
- {
- Integration::LongPressGestureEvent longPress( state );
- longPress.numberOfTouches = touchPoints;
-
- for (std::map<int, Vector2>::iterator iter = mTouchPositions.begin(), endIter = mTouchPositions.end();
- iter != endIter; ++iter)
- {
- longPress.point += iter->second;
- }
- longPress.point /= touchPoints;
-
- longPress.time = mTouchTime;
- if ( state != Gesture::Possible )
- {
- longPress.time += GetSystemValue();
- }
-
- mCoreEventInterface.QueueCoreEvent(longPress);
- }
-}
-
-int LongPressGestureDetector::GetSystemValue()
-{
- return GetLongPressTime( LONG_PRESS_TIME );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
-#define __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <map>
-#include <timer.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-struct TouchEvent;
-struct LongPressGestureRequest;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CoreEventInterface;
-
-/**
- * When given a set of touch events, this detector attempts to determine if a long press gesture has taken place.
- * Emits a LongPressGestureEvent (state = Started) when a long press has been detected (Touch held down for more than duration).
- * Emits a further LongPressGestureEvent (state = Finished) when a long press has been completed (Touch Release).
- */
-class LongPressGestureDetector : public GestureDetector
-{
-public:
-
- /**
- * Constructor
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] screenSize The size of the screen.
- * @param[in] request The long press gesture request.
- */
- LongPressGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::LongPressGestureRequest& request);
-
- /**
- * Virtual destructor.
- */
- virtual ~LongPressGestureDetector();
-
-public:
-
- /**
- * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
- */
- virtual void SendEvent(const Integration::TouchEvent& event);
-
- /**
- * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
- */
- virtual void Update(const Integration::GestureRequest& request);
-
-private:
-
- /**
- * Timer Callback
- * @return will return false; one-shot timer.
- */
- bool TimerCallback();
-
- /**
- * Emits the long press gesture if all conditions are applicable.
- * @param[in] state The state of this gesture event.
- */
- void EmitGesture(Gesture::State state);
-
- /**
- * Get current system setting value for tap and hold gesture
- * @return system value for tap and hold gesture [ms]
- */
- int GetSystemValue();
-
-private:
-
- /**
- * Internal state machine.
- */
- enum State
- {
- Clear, ///< No gesture detected.
- Touched, ///< User is touching the screen.
- Failed, ///< Gesture has failed.
- Finished ///< Gesture has been detected and sent.
- };
-
- CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
- State mState; ///< The current state of the detector.
-
- unsigned int mMinimumTouchesRequired; ///< The minimum touches required before emitting a long press.
- unsigned int mMaximumTouchesRequired; ///< The maximum touches allowable. Any more and a long press is not emitted.
-
- std::map<int, Vector2> mTouchPositions; ///< A map with all the touch down positions.
- unsigned long mTouchTime; ///< The time we first pressed down.
-
- Dali::Timer mTimer; ///< The timer used to determine a long press.
- SlotDelegate< LongPressGestureDetector > mTimerSlot;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pan-gesture-detector-base.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-#include <dali/public-api/events/touch-point.h>
-
-#include <dali/integration-api/events/gesture-requests.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const float MINIMUM_MOTION_DISTANCE_BEFORE_PAN( 15.0f );
-const float MINIMUM_MOTION_DISTANCE_BEFORE_PAN_SQUARED( MINIMUM_MOTION_DISTANCE_BEFORE_PAN * MINIMUM_MOTION_DISTANCE_BEFORE_PAN );
-const float MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO( 2.0f / 3.0f );
-const unsigned long MAXIMUM_TIME_DIFF_ALLOWED( 500 );
-const unsigned long MINIMUM_TIME_BEFORE_THRESHOLD_ADJUSTMENTS( 100 );
-const unsigned int MINIMUM_MOTION_EVENTS_BEFORE_PAN(2);
-} // unnamed namespace
-
-PanGestureDetectorBase::PanGestureDetectorBase(Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions* environmentOptions)
-: GestureDetector( screenSize, Gesture::Pan ),
- mState( Clear ),
- mThresholdAdjustmentsRemaining( 0 ),
- mThresholdTotalAdjustments( MINIMUM_MOTION_DISTANCE_BEFORE_PAN * MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO ),
- mPrimaryTouchDownTime( 0 ),
- mMinimumTouchesRequired( request.minTouches ),
- mMaximumTouchesRequired( request.maxTouches ),
- mMinimumDistanceSquared( MINIMUM_MOTION_DISTANCE_BEFORE_PAN_SQUARED ),
- mMinimumMotionEvents( MINIMUM_MOTION_EVENTS_BEFORE_PAN ),
- mMotionEvents( 0 )
-{
- if ( environmentOptions )
- {
- int minimumDistance = environmentOptions->GetMinimumPanDistance();
- if ( minimumDistance >= 0 )
- {
- mMinimumDistanceSquared = minimumDistance * minimumDistance;
-
- // Usually, we do not want to apply the threshold straight away, but phased over the first few pans
- // Set our distance to threshold adjustments ratio here.
- mThresholdTotalAdjustments = minimumDistance * MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO;
- }
-
- int minimumEvents = environmentOptions->GetMinimumPanEvents();
- if ( minimumEvents >= 1 )
- {
- mMinimumMotionEvents = minimumEvents - 1; // Down is the first event
- }
- }
-}
-
-PanGestureDetectorBase::~PanGestureDetectorBase()
-{
-}
-
-void PanGestureDetectorBase::SendEvent(const Integration::TouchEvent& event)
-{
- PointState::Type primaryPointState(event.points[0].GetState());
-
- if (primaryPointState == PointState::INTERRUPTED)
- {
- if ( ( mState == Started ) || ( mState == Possible ) )
- {
- // If our pan had started and we are interrupted, then tell Core that pan is cancelled.
- mTouchEvents.push_back(event);
- SendPan(Gesture::Cancelled, event);
- }
- mState = Clear; // We should change our state to Clear.
- mTouchEvents.clear();
- }
- else
- {
- switch (mState)
- {
- case Clear:
- {
- if (primaryPointState == PointState::DOWN)
- {
- mPrimaryTouchDownLocation = event.points[0].GetScreenPosition();
- mPrimaryTouchDownTime = event.time;
- mMotionEvents = 0;
- if (event.GetPointCount() == mMinimumTouchesRequired)
- {
- // We have satisfied the minimum touches required for a pan, tell core that a gesture may be possible and change our state accordingly.
- mState = Possible;
- SendPan(Gesture::Possible, event);
- }
-
- mTouchEvents.push_back(event);
- }
- break;
- }
-
- case Possible:
- {
- unsigned int pointCount(event.GetPointCount());
- if ( (pointCount >= mMinimumTouchesRequired)&&(pointCount <= mMaximumTouchesRequired) )
- {
- if (primaryPointState == PointState::MOTION)
- {
- mTouchEvents.push_back(event);
- mMotionEvents++;
-
- Vector2 delta(event.points[0].GetScreenPosition() - mPrimaryTouchDownLocation);
-
- if ( ( mMotionEvents >= mMinimumMotionEvents ) &&
- ( delta.LengthSquared() >= mMinimumDistanceSquared ) )
- {
- // If the touch point(s) have moved enough distance to be considered a pan, then tell Core that the pan gesture has started and change our state accordingly.
- mState = Started;
- SendPan(Gesture::Started, event);
- }
- }
- else if (primaryPointState == PointState::UP)
- {
- Vector2 delta(event.points[0].GetScreenPosition() - mPrimaryTouchDownLocation);
- if(delta.LengthSquared() >= mMinimumDistanceSquared)
- {
- SendPan(Gesture::Started, event);
- mTouchEvents.push_back(event);
- SendPan(Gesture::Finished, event);
- }
- else
- {
- // If we have lifted the primary touch point then tell core the pan is cancelled and change our state to Clear.
- SendPan(Gesture::Cancelled, event);
- }
- mState = Clear;
- mTouchEvents.clear();
- }
- }
- else
- {
- // We do not satisfy pan conditions, tell Core our Gesture has been cancelled.
- SendPan(Gesture::Cancelled, event);
-
- if (pointCount == 1 && primaryPointState == PointState::UP)
- {
- // If we have lifted the primary touch point, then change our state to Clear...
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- // ...otherwise change it to Failed.
- mState = Failed;
- }
- }
- break;
- }
-
- case Started:
- {
- mTouchEvents.push_back(event);
-
- unsigned int pointCount(event.GetPointCount());
- if ( (pointCount >= mMinimumTouchesRequired)&&(pointCount <= mMaximumTouchesRequired) )
- {
- switch (primaryPointState)
- {
- case PointState::MOTION:
- // Pan is continuing, tell Core.
- SendPan(Gesture::Continuing, event);
- break;
-
- case PointState::UP:
- // Pan is finally finished when our primary point is lifted, tell Core and change our state to Clear.
- SendPan(Gesture::Finished, event);
- mState = Clear;
- mTouchEvents.clear();
- break;
-
- case PointState::STATIONARY:
- if (pointCount == mMinimumTouchesRequired)
- {
- Integration::PointContainerConstIterator iter = event.points.begin() + 1; // We already know the state of the first point
- for(; iter != event.points.end(); ++iter)
- {
- if(iter->GetState() == PointState::UP)
- {
- // The number of touch points will be less than the minimum required. Inform core and change our state to Finished.
- SendPan(Gesture::Finished, event);
- mState = Finished;
- break;
- }
- }
- }
- break;
-
- default:
- break;
- }
- }
- else
- {
- // We have gone outside of the pan requirements, inform Core that the gesture is finished.
- SendPan(Gesture::Finished, event);
-
- if (pointCount == 1 && primaryPointState == PointState::UP)
- {
- // If this was the primary point being released, then we change our state back to Clear...
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- // ...otherwise we change it to Finished.
- mState = Finished;
- }
- }
- break;
- }
-
- case Finished:
- case Failed:
- {
- if (primaryPointState == PointState::UP)
- {
- // Change our state back to clear when the primary touch point is released.
- mState = Clear;
- mTouchEvents.clear();
- }
- break;
- }
- }
- }
-}
-
-void PanGestureDetectorBase::Update(const Integration::GestureRequest& request)
-{
- const Integration::PanGestureRequest& pan = static_cast<const Integration::PanGestureRequest&>(request);
-
- mMinimumTouchesRequired = pan.minTouches;
- mMaximumTouchesRequired = pan.maxTouches;
-}
-
-void PanGestureDetectorBase::SendPan(Gesture::State state, const Integration::TouchEvent& currentEvent)
-{
- Integration::PanGestureEvent gesture(state);
- gesture.currentPosition = currentEvent.points[0].GetScreenPosition();
- gesture.numberOfTouches = currentEvent.GetPointCount();
-
- if ( mTouchEvents.size() > 1 )
- {
- // Get the second last event in the queue, the last one is the current event
- const Integration::TouchEvent& previousEvent( *( mTouchEvents.rbegin() + 1 ) );
-
- Vector2 previousPosition( mPreviousPosition );
- unsigned long previousTime( previousEvent.time );
-
- // If we've just started then we want to remove the threshold from Core calculations.
- if ( state == Gesture::Started )
- {
- previousPosition = mPrimaryTouchDownLocation;
- previousTime = mPrimaryTouchDownTime;
-
- // If it's a slow pan, we do not want to phase in the threshold over the first few pan-events
- // A slow pan is defined as one that starts the specified number of milliseconds after the down-event
- if ( ( currentEvent.time - previousTime ) > MINIMUM_TIME_BEFORE_THRESHOLD_ADJUSTMENTS )
- {
- mThresholdAdjustmentsRemaining = mThresholdTotalAdjustments;
- mThresholdAdjustmentPerFrame = ( gesture.currentPosition - previousPosition ) / mThresholdTotalAdjustments;
- }
- else
- {
- mThresholdAdjustmentsRemaining = 0;
- mThresholdAdjustmentPerFrame = Vector2::ZERO;
- }
- }
-
- gesture.previousPosition = previousPosition;
- gesture.timeDelta = currentEvent.time - previousTime;
-
- // Apply the threshold with a phased approach
- if ( mThresholdAdjustmentsRemaining > 0 )
- {
- --mThresholdAdjustmentsRemaining;
- gesture.currentPosition -= mThresholdAdjustmentPerFrame * mThresholdAdjustmentsRemaining;
- }
-
- mPreviousPosition = gesture.currentPosition;
- }
- else
- {
- gesture.previousPosition = gesture.currentPosition;
- gesture.timeDelta = 0;
- }
-
- gesture.time = currentEvent.time;
-
- EmitPan(gesture);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
-#define __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/math/vector2.h>
-#include <dali/integration-api/events/pan-gesture-event.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-class Core;
-struct TouchEvent;
-struct PanGestureRequest;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class EnvironmentOptions;
-
-/**
- * When given a set of touch events, this detector attempts to determine if a pan gesture has taken place.
- */
-class PanGestureDetectorBase : public GestureDetector
-{
-public:
-
- /**
- * Virtual destructor.
- */
- virtual ~PanGestureDetectorBase();
-
-public:
-
- /**
- * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
- */
- virtual void SendEvent(const Integration::TouchEvent& event);
-
- /**
- * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
- */
- virtual void Update(const Integration::GestureRequest& request);
-
-protected:
-
- /**
- * Constructor
- * @param[in] screenSize The size of the screen.
- * @param[in] request The details of the request.
- */
- PanGestureDetectorBase(Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions* environmentOptions);
-
-private:
-
- /**
- * Emits the pan gesture event (performs some smoothing operation).
- * @param[in] state The state of the pan.
- * @param[in] currentEvent The latest touch event.
- */
- void SendPan(Gesture::State state, const Integration::TouchEvent& currentEvent);
-
- /**
- * Emits the pan gesture event to the core.
- * @param[in] gesture The pan gesture event.
- */
- virtual void EmitPan(const Integration::PanGestureEvent gesture) = 0;
-
-private:
-
- /**
- * Internal state machine.
- */
- enum State
- {
- Clear, ///< No gesture detected.
- Possible, ///< The current touch event data suggests that a gesture is possible.
- Started, ///< A gesture has been detected.
- Finished, ///< A previously started pan gesture has finished.
- Failed, ///< Current touch event data suggests a pan gesture is not possible.
- };
-
- State mState; ///< The current state of the detector.
- std::vector<Integration::TouchEvent> mTouchEvents; ///< A container of all touch events after an initial down event.
-
- Vector2 mPrimaryTouchDownLocation; ///< The initial touch down point.
- Vector2 mThresholdAdjustmentPerFrame; ///< The adjustment per frame at the start of a slow pan.
- Vector2 mPreviousPosition; ///< The previous position.
-
- unsigned int mThresholdAdjustmentsRemaining; ///< No. of threshold adjustments still to apply (for a slow-pan).
- unsigned int mThresholdTotalAdjustments; ///< The total number of adjustments required.
-
- unsigned long mPrimaryTouchDownTime; ///< The initial touch down time.
- unsigned int mMinimumTouchesRequired; ///< The minimum touches required before a pan should be emitted.
- unsigned int mMaximumTouchesRequired; ///< The maximum touches after which a pan should not be emitted.
-
- unsigned int mMinimumDistanceSquared; ///< The minimum distance squared before pan should start.
- unsigned int mMinimumMotionEvents; ///< The minimum motion events before pan should start.
- unsigned int mMotionEvents; ///< The motion events received so far (before pan is emitted).
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pan-gesture-detector.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/events/gesture-requests.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <base/core-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-PanGestureDetector::PanGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions& environmentOptions)
-: PanGestureDetectorBase(screenSize, request, &environmentOptions),
- mCoreEventInterface(coreEventInterface)
-{
-}
-
-PanGestureDetector::~PanGestureDetector()
-{
-}
-
-void PanGestureDetector::EmitPan(const Integration::PanGestureEvent event)
-{
- mCoreEventInterface.QueueCoreEvent(event);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
-#define __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/math/vector2.h>
-
-// INTERNAL INCLUDES
-#include <events/pan-gesture-detector-base.h>
-#include <dali/integration-api/events/pan-gesture-event.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-struct TouchEvent;
-struct PanGestureRequest;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CoreEventInterface;
-
-/**
- * Detects a pan gesture and sends it to core.
- */
-class PanGestureDetector : public PanGestureDetectorBase
-{
-public:
-
- /**
- * Constructor
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] screenSize The size of the screen.
- * @param[in] request The details of the request.
- * @param[in] environmentOptions The environmentOptions.
- */
- PanGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions& environmentOptions);
-
- /**
- * Virtual destructor.
- */
- virtual ~PanGestureDetector();
-
-private:
-
- /**
- * Emits the pan gesture event to the core.
- * @param[in] gesture The pan gesture event.
- */
- virtual void EmitPan(const Integration::PanGestureEvent gesture);
-
-private:
-
- CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pinch-gesture-detector.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/math/vector2.h>
-
-#include <dali/integration-api/events/pinch-gesture-event.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <base/core-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int MINIMUM_TOUCH_EVENTS_REQUIRED = 4;
-const unsigned int MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START = 4;
-
-inline float GetDistance(const Integration::Point& point1, const Integration::Point& point2)
-{
- Vector2 vector(point1.GetScreenPosition() - point2.GetScreenPosition());
- return vector.Length();
-}
-
-inline Vector2 GetCenterPoint(const Integration::Point& point1, const Integration::Point& point2)
-{
- return Vector2(point1.GetScreenPosition() + point2.GetScreenPosition()) * 0.5f;
-}
-
-} // unnamed namespace
-
-PinchGestureDetector::PinchGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, float minimumPinchDistance)
-: GestureDetector(screenSize, Gesture::Pinch),
- mCoreEventInterface(coreEventInterface),
- mState(Clear),
- mTouchEvents(),
- mMinimumDistanceDelta(minimumPinchDistance),
- mStartingDistance(0.0f)
-{
-}
-
-PinchGestureDetector::~PinchGestureDetector()
-{
-}
-
-void PinchGestureDetector::SetMinimumPinchDistance(float distance)
-{
- mMinimumDistanceDelta = distance;
-}
-
-void PinchGestureDetector::SendEvent(const Integration::TouchEvent& event)
-{
- int pointCount = event.GetPointCount();
-
- switch (mState)
- {
- case Clear:
- {
- if (pointCount == 2)
- {
- // Change state to possible as we have two touch points.
- mState = Possible;
- mTouchEvents.push_back(event);
- }
- break;
- }
-
- case Possible:
- {
- if (pointCount != 2)
- {
- // We no longer have two touch points so change state back to Clear.
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- const Integration::Point& currentPoint1 = event.points[0];
- const Integration::Point& currentPoint2 = event.points[1];
-
- if (currentPoint1.GetState() == PointState::UP || currentPoint2.GetState() == PointState::UP)
- {
- // One of our touch points has an Up event so change our state back to Clear.
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- mTouchEvents.push_back(event);
-
- // We can only determine a pinch after a certain number of touch points have been collected.
- if (mTouchEvents.size() >= MINIMUM_TOUCH_EVENTS_REQUIRED)
- {
- const Integration::Point& firstPoint1 = mTouchEvents[0].points[0];
- const Integration::Point& firstPoint2 = mTouchEvents[0].points[1];
-
- float firstDistance = GetDistance(firstPoint1, firstPoint2);
- float currentDistance = GetDistance(currentPoint1, currentPoint2);
- float distanceChanged = firstDistance - currentDistance;
-
- // Check if distance has changed enough
- if (fabsf(distanceChanged) > mMinimumDistanceDelta)
- {
- // Remove the first few events from the vector otherwise values are exaggerated
- mTouchEvents.erase(mTouchEvents.begin(), mTouchEvents.end() - MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START);
-
- if ( !mTouchEvents.empty() )
- {
- mStartingDistance = GetDistance(mTouchEvents.begin()->points[0], mTouchEvents.begin()->points[1]);
-
- // Send pinch started
- SendPinch(Gesture::Started, event);
-
- mState = Started;
- }
-
- mTouchEvents.clear();
- }
-
- if (mState == Possible)
- {
- // No pinch, so restart detection
- mState = Clear;
- mTouchEvents.clear();
- }
- }
- }
- }
- break;
- }
-
- case Started:
- {
- if (pointCount != 2)
- {
- // Send pinch finished event
- SendPinch(Gesture::Finished, event);
-
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- const Integration::Point& currentPoint1 = event.points[0];
- const Integration::Point& currentPoint2 = event.points[1];
-
- if (currentPoint1.GetState() == PointState::UP || currentPoint2.GetState() == PointState::UP)
- {
- mTouchEvents.push_back(event);
- // Send pinch finished event
- SendPinch(Gesture::Finished, event);
-
- mState = Clear;
- mTouchEvents.clear();
- }
- else
- {
- mTouchEvents.push_back(event);
-
- if (mTouchEvents.size() >= MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START)
- {
- // Send pinch continuing
- SendPinch(Gesture::Continuing, event);
-
- mTouchEvents.clear();
- }
- }
- }
- break;
- }
- }
-}
-
-void PinchGestureDetector::Update(const Integration::GestureRequest& request)
-{
- // Nothing to do.
-}
-
-void PinchGestureDetector::SendPinch(Gesture::State state, const Integration::TouchEvent& currentEvent)
-{
- Integration::PinchGestureEvent gesture(state);
-
- if ( !mTouchEvents.empty() )
- {
- const Integration::TouchEvent& firstEvent = mTouchEvents[0];
-
- // Assert if we have been holding TouchEvents that do not have 2 points
- DALI_ASSERT_DEBUG( firstEvent.GetPointCount() == 2 );
-
- // We should use the current event in our calculations unless it does not have two points.
- // If it does not have two points, then we should use the last point in mTouchEvents.
- Integration::TouchEvent event( currentEvent );
- if ( event.GetPointCount() != 2 )
- {
- event = *mTouchEvents.rbegin();
- }
-
- const Integration::Point& firstPoint1( firstEvent.points[0] );
- const Integration::Point& firstPoint2( firstEvent.points[1] );
- const Integration::Point& currentPoint1( event.points[0] );
- const Integration::Point& currentPoint2( event.points[1] );
-
- float firstDistance = GetDistance(firstPoint1, firstPoint2);
- float currentDistance = GetDistance(currentPoint1, currentPoint2);
- gesture.scale = currentDistance / mStartingDistance;
-
- float distanceDelta = fabsf(firstDistance - currentDistance);
- unsigned long timeDelta = currentEvent.time - firstEvent.time;
- gesture.speed = (distanceDelta / timeDelta) * 1000.0f;
-
- gesture.centerPoint = GetCenterPoint(currentPoint1, currentPoint2);
- }
- else
- {
- // Something has gone wrong, just cancel the gesture.
- gesture.state = Gesture::Cancelled;
- }
-
- gesture.time = currentEvent.time;
-
- mCoreEventInterface.QueueCoreEvent(gesture);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
-#define __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-struct TouchEvent;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CoreEventInterface;
-
-/**
- * When given a set of touch events, this detector attempts to determine if a pinch gesture has taken place.
- */
-class PinchGestureDetector : public GestureDetector
-{
-public:
-
- /**
- * Constructor
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] screenSize The size of the screen.
- */
- PinchGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, float minimumPinchDistance);
-
- /**
- * Virtual destructor.
- */
- virtual ~PinchGestureDetector();
-
- /**
- * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
- * trigger a pinch gesture
- *
- * @param[in] distance The minimum pinch distance in pixels
- */
- void SetMinimumPinchDistance(float distance);
-
-public:
-
- /**
- * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
- */
- virtual void SendEvent(const Integration::TouchEvent& event);
-
- /**
- * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
- */
- virtual void Update(const Integration::GestureRequest& request);
-
-private:
-
- /**
- * Emits the pinch gesture event to the core.
- * @param[in] state The state of the pinch (whether it's starting, continuing or finished).
- * @param[in] currentEvent The latest touch event.
- */
- void SendPinch(Gesture::State state, const Integration::TouchEvent& currentEvent);
-
-private:
-
- /**
- * Internal state machine.
- */
- enum State
- {
- Clear, ///< No gesture detected.
- Possible, ///< The current touch event data suggests that a gesture is possible.
- Started, ///< A gesture has been detected.
- };
-
- CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
- State mState; ///< The current state of the detector.
- std::vector<Integration::TouchEvent> mTouchEvents; ///< The touch events since initial touch down.
-
- float mMinimumDistanceDelta; ///< The minimum distance before a pinch is applicable.
-
- float mStartingDistance; ///< The distance between the two touch points when the pinch is first detected.
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tap-gesture-detector.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-#include <dali/public-api/math/vector2.h>
-
-#include <dali/integration-api/events/gesture-requests.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <base/core-event-interface.h>
-
-// INTERNAL INCLUDES
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-// TODO: Set these according to DPI
-const float MAXIMUM_MOTION_ALLOWED = 20.0f;
-const unsigned long MAXIMUM_TIME_ALLOWED = 500u;
-} // unnamed namespace
-
-TapGestureDetector::TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request)
-: GestureDetector(screenSize, Gesture::Tap),
- mCoreEventInterface(coreEventInterface),
- mState(Clear),
- mMinimumTapsRequired(request.minTaps),
- mMaximumTapsRequired(request.maxTaps),
- mTapsRegistered(0),
- mTouchPosition(),
- mTouchTime(0u),
- mLastTapTime(0u)
-{
-}
-
-TapGestureDetector::~TapGestureDetector()
-{
-}
-
-void TapGestureDetector::SendEvent(const Integration::TouchEvent& event)
-{
- if (event.GetPointCount() == 1)
- {
- const Integration::Point& point = event.points[0];
- PointState::Type pointState = point.GetState();
-
- switch (mState)
- {
- case Clear:
- {
- if (pointState == PointState::DOWN)
- {
- SetupForTouchDown( event, point );
- }
- break;
- }
-
- case Touched:
- {
- unsigned long deltaBetweenTouchDownTouchUp = abs( event.time - mTouchTime ) ;
-
- if ( pointState == PointState::UP )
- {
- if ( deltaBetweenTouchDownTouchUp < MAXIMUM_TIME_ALLOWED )
- {
- mLastTapTime = mTouchTime;
- EmitSingleTap( event.time, point );
- mState = Registered;
- }
- else
- {
- mState = Clear;
- }
- }
- else if (pointState == PointState::INTERRUPTED)
- {
- mState = Clear;
- }
- break;
- }
-
- case Registered:
- {
- if ( pointState == PointState::UP )
- {
- unsigned long deltaBetweenTouchDownTouchUp = abs( event.time - mTouchTime ) ;
-
- if ( deltaBetweenTouchDownTouchUp < MAXIMUM_TIME_ALLOWED )
- {
- // This is a possible multiple tap, so has it been quick enough ?
- unsigned long timeDelta = abs( event.time - mLastTapTime );
- if ( timeDelta > MAXIMUM_TIME_ALLOWED ) // If exceeded time between taps then just a single tap.
- {
- mLastTapTime = event.time;
- EmitSingleTap( event.time, point );
- mState = Registered;
- }
- else
- {
- ++mTapsRegistered;
- EmitGesture( Gesture::Started, event.time );
- mState = Clear;
- }
- }
- else // Delta between touch down and touch up too long to be considered a Tap event
- {
- mState = Clear;
- }
- }
- else if (pointState == PointState::DOWN)
- {
- const Vector2& screen( point.GetScreenPosition() );
- Vector2 distanceDelta(abs(mTouchPosition.x - screen.x),
- abs(mTouchPosition.y - screen.y));
-
- unsigned long timeDelta = abs( event.time - mLastTapTime );
-
- if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
- distanceDelta.y > MAXIMUM_MOTION_ALLOWED ||
- timeDelta > MAXIMUM_TIME_ALLOWED )
- {
- SetupForTouchDown( event, point );
- }
- else
- {
- EmitPossibleState( event );
- }
- }
- break;
- }
-
- case Failed:
- default:
- {
- mState = Clear;
- break;
- }
- }
- }
- else
- {
- mState = Failed;
-
- // We have entered a multi-touch event so emit registered gestures if required.
- EmitGesture(Gesture::Started, event.time);
- }
-}
-
-void TapGestureDetector::SetupForTouchDown( const Integration::TouchEvent& event, const Integration::Point& point )
-{
- mTouchPosition = point.GetScreenPosition();
- mTouchTime = event.time;
- mLastTapTime = 0u;
- mTapsRegistered = 0;
- mState = Touched;
- EmitPossibleState( event );
-}
-
-void TapGestureDetector::EmitPossibleState( const Integration::TouchEvent& event )
-{
- Integration::TapGestureEvent tapEvent( Gesture::Possible );
- tapEvent.point = mTouchPosition;
- tapEvent.time = event.time;
- mCoreEventInterface.QueueCoreEvent(tapEvent);
-}
-
-
-void TapGestureDetector::Update(const Integration::GestureRequest& request)
-{
- const Integration::TapGestureRequest& tap = static_cast<const Integration::TapGestureRequest&>(request);
-
- mMinimumTapsRequired = tap.minTaps;
- mMaximumTapsRequired = tap.maxTaps;
-}
-
-void TapGestureDetector::EmitGesture( Gesture::State state, unsigned int time )
-{
- if ( (state == Gesture::Cancelled) ||
- (mTapsRegistered >= mMinimumTapsRequired && mTapsRegistered <= mMaximumTapsRequired) )
-
- {
- Integration::TapGestureEvent event( state );
- EmitTap( time, event );
- }
-}
-
-void TapGestureDetector::EmitSingleTap( unsigned int time, const Integration::Point& point )
-{
- Integration::TapGestureEvent event( Gesture::Started );
- const Vector2& screen( point.GetScreenPosition() );
- Vector2 distanceDelta(abs(mTouchPosition.x - screen.x),
- abs(mTouchPosition.y - screen.y));
-
- if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
- distanceDelta.y > MAXIMUM_MOTION_ALLOWED )
- {
- event.state = Gesture::Cancelled;
- }
- mTapsRegistered = 1u;
- EmitTap( time, event );
-}
-
-void TapGestureDetector::EmitTap( unsigned int time, Integration::TapGestureEvent& event )
-{
- event.numberOfTaps = mTapsRegistered;
- event.point = mTouchPosition;
- event.time = time;
- mCoreEventInterface.QueueCoreEvent(event);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
-#define __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/events/tap-gesture-event.h>
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/integration-api/events/point.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-detector.h>
-
-namespace Dali
-{
-
-namespace Integration
-{
-struct TouchEvent;
-struct TapGestureRequest;
-}
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class CoreEventInterface;
-
-/**
- * When given a set of touch events, this detector attempts to determine if a tap gesture has taken place.
- */
-class TapGestureDetector : public GestureDetector
-{
-public:
-
- /**
- * Constructor
- * @param[in] coreEventInterface Used to send events to Core.
- * @param[in] screenSize The size of the screen.
- * @param[in] request The tap gesture request.
- */
- TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request);
-
- /**
- * Virtual destructor.
- */
- virtual ~TapGestureDetector();
-
-public:
-
- /**
- * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
- */
- virtual void SendEvent(const Integration::TouchEvent& event);
-
- /**
- * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
- */
- virtual void Update(const Integration::GestureRequest& request);
-
-private:
-
- /**
- * Checks if registered taps are within required bounds and emits tap gesture if they are.
- *
- * @param[in] state current state of incomplete gesture
- * @param[in] time time of this latest touch event
- */
- void EmitGesture( Gesture::State state, unsigned int time );
-
- /**
- * Initialises tap gesture detector for next tap sequence
- *
- * @param[in] event registered touch event
- * @param[in] point position touch event occurred
- */
- void SetupForTouchDown( const Integration::TouchEvent& event, const Integration::Point& point );
-
- /**
- * Emit a touch down event for hit testing
- *
- * @param[in] event registered touch event
- */
- void EmitPossibleState( const Integration::TouchEvent& event );
-
- /**
- * Force a touch event sequence to be treated as a single tap
- *
- * @param[in] time time of this latest touch event
- * @param[in] point position touch event occurred
- */
- void EmitSingleTap( unsigned int time, const Integration::Point& point );
-
- /**
- * Emit a tap event
- *
- * @param[in] time time of this latest touch event
- * @param[in] event registered touch event
- */
- void EmitTap( unsigned int time, Integration::TapGestureEvent& event );
-
-private:
-
- /**
- * Internal state machine.
- */
- enum State
- {
- Clear, ///< No gesture detected.
- Touched, ///< User is touching the screen.
- Registered, ///< At least one tap has been registered.
- Failed, ///< Gesture has failed.
- };
-
- CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
- State mState; ///< Current state of the detector.
-
- int mMinimumTapsRequired; ///< Minimum number of taps required.
- int mMaximumTapsRequired; ///< Maximum number of taps required.
- int mTapsRegistered; ///< In current detection, the number of taps registered.
-
- Vector2 mTouchPosition; ///< The initial touch down position.
- unsigned long mTouchTime; ///< The initial touch down time.
- unsigned long mLastTapTime; ///< Time last tap gesture was registered
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <feedback-player-impl.h>
-
-// EXTERNAL INCLUDES
-#include <fstream>
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-// Type Registration
-Dali::BaseHandle Create()
-{
- return FeedbackPlayer::Get();
-}
-
-Dali::TypeRegistration FEEDBACK_PLAYER_TYPE( typeid(Dali::FeedbackPlayer), typeid(Dali::BaseHandle), Create );
-
-} // unnamed namespace
-
-Dali::FeedbackPlayer FeedbackPlayer::New()
-{
- Dali::FeedbackPlayer player = Dali::FeedbackPlayer( new FeedbackPlayer() );
- return player;
-}
-
-Dali::FeedbackPlayer FeedbackPlayer::Get()
-{
- Dali::FeedbackPlayer player;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::FeedbackPlayer ) );
- if ( handle )
- {
- // If so, downcast the handle
- player = Dali::FeedbackPlayer( dynamic_cast< FeedbackPlayer* >( handle.GetObjectPtr() ) );
- }
- else
- {
- player = Dali::FeedbackPlayer( New() );
- service.Register( typeid( player ), player );
- }
- }
-
- return player;
-}
-
-void FeedbackPlayer::PlayMonotone( unsigned int duration )
-{
- mPlugin.PlayHapticMonotone( duration );
-}
-
-void FeedbackPlayer::PlayFile( const std::string& filePath )
-{
- mPlugin.PlayHaptic( filePath );
-}
-
-void FeedbackPlayer::Stop()
-{
- mPlugin.StopHaptic();
-}
-
-int FeedbackPlayer::PlaySound( const std::string& filename )
-{
- return mPlugin.PlaySound(filename);
-}
-
-void FeedbackPlayer::StopSound( int handle )
-{
- mPlugin.StopSound(handle);
-}
-
-void FeedbackPlayer::PlayFeedbackPattern( int type, int pattern )
-{
- mPlugin.PlayFeedbackPattern(type, pattern);
-}
-
-bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data)
-{
- bool loaded = false;
-
- std::ifstream stream(filename.c_str());
-
- if( stream.is_open() )
- {
- data.assign((std::istreambuf_iterator<char>(stream)),
- std::istreambuf_iterator<char>());
- loaded = true;
- }
-
- return loaded;
-}
-
-FeedbackPlayer::FeedbackPlayer()
-: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME )
-{
-}
-
-FeedbackPlayer::~FeedbackPlayer()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_FEEDBACK_PLAYER_H__
-#define __DALI_INTERNAL_FEEDBACK_PLAYER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <feedback-player.h>
-#include <feedback/feedback-plugin-proxy.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class FeedbackPluginProxy;
-
-/**
- * Plays haptic effects.
- */
-class FeedbackPlayer : public Dali::BaseObject
-{
-
-public:
-
- /**
- * Create a FeedbackPlayer.
- * This should only be called once by the Adaptor class.
- * @return A newly created FeedbackPlayer.
- */
- static Dali::FeedbackPlayer New();
-
- /**
- * Retrieve a handle to the FeedbackPlayer. This creates an instance if none has been created.
- * @return A handle to the FeedbackPlayer.
- */
- static Dali::FeedbackPlayer Get();
-
- /**
- * @copydoc Dali::FeedbackPlayer::PlayMonotone()
- */
- void PlayMonotone(unsigned int duration);
-
- /**
- * @copydoc Dali::FeedbackPlayer::PlayFile()
- */
- void PlayFile( const std::string& filePath );
-
- /**
- * @copydoc Dali::FeedbackPlayer::Stop()
- */
- void Stop();
-
- /**
- * @copydoc Dali::FeedbackPlayer::PlaySound()
- */
- int PlaySound( const std::string& fileName );
-
- /**
- * @copydoc Dali::FeedbackPlayer::StopSound()
- */
- void StopSound( int handle );
-
- /**
- * @copydoc Dali::FeedbackPlayer::PlayFeedbackPattern()
- */
- void PlayFeedbackPattern( int type, int pattern );
-
- /**
- * @copydoc Dali::FeedbackPlayer::LoadFile()
- */
- bool LoadFile(const std::string& filename, std::string& data);
-
-private:
-
- /**
- * Private Constructor; see also FeedbackPlayer::New()
- */
- FeedbackPlayer();
-
- /**
- * Virtual Destructor
- */
- virtual ~FeedbackPlayer();
-
- // Undefined
- FeedbackPlayer(const FeedbackPlayer&);
-
- // Undefined
- FeedbackPlayer& operator=(FeedbackPlayer&);
-
-private:
-
- FeedbackPluginProxy mPlugin;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::FeedbackPlayer& GetImplementation(Dali::FeedbackPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast<Internal::Adaptor::FeedbackPlayer&>(handle);
-}
-
-inline const Internal::Adaptor::FeedbackPlayer& GetImplementation(const Dali::FeedbackPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::FeedbackPlayer&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_FEEDBACK_PLAYER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <feedback/feedback-plugin-proxy.h>
-
-// EXTERNAL INCLUDES
-#include <dlfcn.h>
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if _GLIBCXX_USE_CXX11_ABI
-const char * const FeedbackPluginProxy::DEFAULT_OBJECT_NAME( "libdali-feedback-plugin.so" );
-#else
-const char * const FeedbackPluginProxy::DEFAULT_OBJECT_NAME( "libdali-feedback-plugin-cxx03.so" );
-#endif
-
-FeedbackPluginProxy::FeedbackPluginProxy( const std::string& sharedObjectName )
-: mInitializeAttempted( false ),
- mLibHandle( NULL ),
- mSharedObjectName( sharedObjectName ),
- mCreatePluginFunctionPtr( NULL ),
- mFeedbackPlugin( NULL )
-{
- // Lazily initialize when sound/haptic is first played
-}
-
-FeedbackPluginProxy::~FeedbackPluginProxy()
-{
- if( mFeedbackPlugin )
- {
- delete mFeedbackPlugin;
- mFeedbackPlugin = NULL;
-
- if( mLibHandle && dlclose( mLibHandle ) )
- {
- DALI_LOG_ERROR( "Error closing dali feedback plugin library: %s\n", dlerror() );
- }
- }
-}
-
-void FeedbackPluginProxy::PlayHaptic( const std::string& filePath )
-{
- // Lazy initialization
- Initialize();
-
- if( mFeedbackPlugin )
- {
- mFeedbackPlugin->PlayHaptic( filePath );
- }
-}
-
-void FeedbackPluginProxy::PlayHapticMonotone( unsigned int duration )
-{
- // Lazy initialization
- Initialize();
-
- if( mFeedbackPlugin )
- {
- mFeedbackPlugin->PlayHapticMonotone( duration );
- }
-}
-
-void FeedbackPluginProxy::StopHaptic()
-{
- // Must already have been initialized to play haptic
- if( mFeedbackPlugin )
- {
- mFeedbackPlugin->StopHaptic();
- }
-}
-
-int FeedbackPluginProxy::PlaySound( const std::string& fileName )
-{
- // Lazy initialization
- Initialize();
-
- if( mFeedbackPlugin )
- {
- return mFeedbackPlugin->PlaySound( fileName );
- }
-
- return 0;
-}
-
-void FeedbackPluginProxy::StopSound( int handle )
-{
- // Must already have been initialized to play sound
- if ( mFeedbackPlugin )
- {
- mFeedbackPlugin->StopSound( handle );
- }
-}
-
-void FeedbackPluginProxy::PlayFeedbackPattern( int type, int pattern )
-{
- // Lazy initialization
- Initialize();
-
- if( mFeedbackPlugin )
- {
- mFeedbackPlugin->PlayFeedbackPattern( type, pattern );
- }
-}
-
-void FeedbackPluginProxy::Initialize()
-{
- // Only attempt to load dll once
- if ( !mInitializeAttempted )
- {
- mInitializeAttempted = true;
-
- mLibHandle = dlopen( mSharedObjectName.c_str(), RTLD_NOW | RTLD_GLOBAL );
- if( !mLibHandle )
- {
- DALI_LOG_ERROR( "Cannot load dali feedback plugin library error: %s\n", dlerror() );
- return;
- }
-
- // reset errors
- dlerror();
-
- // load plugin
- mCreatePluginFunctionPtr = reinterpret_cast<CreateFeedbackPlugin*>(dlsym(mLibHandle, "CreateFeedbackPlugin"));
- if(!mCreatePluginFunctionPtr)
- {
- DALI_LOG_ERROR("Cannot load symbol CreateFeedbackPlugin(): %s\n", dlerror());
- return;
- }
-
- // reset errors
- dlerror();
-
- mFeedbackPlugin = mCreatePluginFunctionPtr();
-
- if(!mFeedbackPlugin)
- {
- DALI_LOG_ERROR("Call to function CreateFeedbackPlugin() failed\n");
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
-#define __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-// INTERNAL INCLUDES
-#include <feedback-plugin.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-typedef Dali::FeedbackPlugin::SoundStopCallBack SoundStopCallBack;
-typedef Dali::FeedbackPlugin::CreateFeedbackPlugin CreateFeedbackPlugin;
-
-/**
- * Proxy class to dynamically load, use and unload feedback plugin.
- */
-class FeedbackPluginProxy
-{
-public:
-
- /**
- * The default feedback plugin proxy.
- */
- static const char * const DEFAULT_OBJECT_NAME;
-
-public:
-
- /**
- * Constructor.
- */
- FeedbackPluginProxy( const std::string& sharedObjectName );
-
- /**
- * The destructor
- */
- ~FeedbackPluginProxy();
-
- /**
- * @copydoc Dali::Integration::FeedbackPlugin::PlayHaptic()
- */
- void PlayHaptic( const std::string& filePath );
-
- /**
- * @copydoc Dali::FeedbackPlugin::PlayHapticMonotone()
- */
- void PlayHapticMonotone( unsigned int duration );
-
- /**
- * @copydoc Dali::FeedbackPlugin::StopHaptic()
- */
- void StopHaptic();
-
- /**
- * @copydoc Dali::FeedbackPlugin::PlaySound()
- */
- int PlaySound( const std::string& fileName );
-
- /**
- * @copydoc Dali::FeedbackPlugin::StopSound()
- */
- void StopSound( int handle );
-
- /**
- * @copydoc Dali::FeedbackPlugin::PlayFeedbackPattern()
- */
- void PlayFeedbackPattern( int type, int pattern );
-
-private:
-
- /**
- * Dynamically loads the feedback plugin.
- */
- void Initialize();
-
-private:
-
- bool mInitializeAttempted;
- void* mLibHandle;
- std::string mSharedObjectName;
- CreateFeedbackPlugin* mCreatePluginFunctionPtr;
- Dali::FeedbackPlugin* mFeedbackPlugin;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
+++ /dev/null
-# Common
-
-adaptor_common_internal_src_files = \
- $(adaptor_common_dir)/abort-handler.cpp \
- $(adaptor_common_dir)/accessibility-adaptor-impl.cpp \
- $(adaptor_common_dir)/accessibility-gesture-detector.cpp \
- $(adaptor_common_dir)/adaptor.cpp \
- $(adaptor_common_dir)/adaptor-impl.cpp \
- $(adaptor_common_dir)/application-impl.cpp \
- $(adaptor_common_dir)/clipboard-event-notifier-impl.cpp \
- $(adaptor_common_dir)/command-line-options.cpp \
- $(adaptor_common_dir)/drag-and-drop-detector-impl.cpp \
- $(adaptor_common_dir)/feedback-player-impl.cpp \
- $(adaptor_common_dir)/indicator-buffer.cpp \
- $(adaptor_common_dir)/kernel-trace.cpp \
- $(adaptor_common_dir)/system-trace.cpp \
- $(adaptor_common_dir)/lifecycle-controller-impl.cpp \
- $(adaptor_common_dir)/locale-utils.cpp \
- $(adaptor_common_dir)/native-bitmap-buffer-impl.cpp \
- $(adaptor_common_dir)/object-profiler.cpp \
- $(adaptor_common_dir)/orientation-impl.cpp \
- $(adaptor_common_dir)/performance-logger-impl.cpp \
- $(adaptor_common_dir)/physical-keyboard-impl.cpp \
- $(adaptor_common_dir)/pixel-buffer-impl.cpp \
- $(adaptor_common_dir)/shared-file.cpp \
- $(adaptor_common_dir)/singleton-service-impl.cpp \
- $(adaptor_common_dir)/sound-player-impl.cpp \
- $(adaptor_common_dir)/style-monitor-impl.cpp \
- $(adaptor_common_dir)/trigger-event.cpp \
- $(adaptor_common_dir)/trigger-event-factory.cpp \
- $(adaptor_common_dir)/key-impl.cpp \
- $(adaptor_common_dir)/video-player-impl.cpp \
- $(adaptor_common_dir)/events/gesture-manager.cpp \
- $(adaptor_common_dir)/events/long-press-gesture-detector.cpp \
- $(adaptor_common_dir)/events/pan-gesture-detector-base.cpp \
- $(adaptor_common_dir)/events/pan-gesture-detector.cpp \
- $(adaptor_common_dir)/events/pinch-gesture-detector.cpp \
- $(adaptor_common_dir)/events/tap-gesture-detector.cpp \
- $(adaptor_common_dir)/networking/socket-impl.cpp \
- $(adaptor_common_dir)/networking/socket-factory.cpp \
- $(adaptor_common_dir)/feedback/feedback-plugin-proxy.cpp \
- $(adaptor_common_dir)/gl/egl-factory.cpp \
- $(adaptor_common_dir)/gl/egl-implementation.cpp \
- $(adaptor_common_dir)/gl/egl-sync-implementation.cpp \
- $(adaptor_common_dir)/gl/egl-debug.cpp \
- $(adaptor_common_dir)/gl/gl-proxy-implementation.cpp \
- $(adaptor_common_dir)/gl/gl-extensions.cpp
-
-# Different files depending on the event loop being used
-adaptor_common_internal_ecore_src_files = \
- $(adaptor_common_dir)/event-loop/ecore/ecore-callback-manager.cpp \
- $(adaptor_common_dir)/event-loop/ecore/ecore-file-descriptor-monitor.cpp \
- $(adaptor_common_dir)/event-loop/ecore/ecore-timer-impl.cpp
-
-adaptor_common_internal_default_profile_src_files = \
- $(adaptor_common_dir)/color-controller-impl.cpp \
- $(adaptor_common_dir)/system-settings.cpp
-
-adaptor_common_internal_egl_extension_src_files = \
- $(adaptor_common_dir)/gl/egl-image-extensions.cpp
+++ /dev/null
-#ifndef __DALI_INTERNAL_FRAMEWORK_H__
-#define __DALI_INTERNAL_FRAMEWORK_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/signals/callback.h>
-#ifdef APPCORE_WATCH_AVAILABLE
-#include "wearable/watch/watch-application.h"
-#endif
-
-// INTERNAL INCLUDES
-#include <abort-handler.h>
-#include <device-status.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * The Framework class is ideally placed to provide key API required by Applications.
- *
- * The class is also used to register callbacks with the TIZEN platform so that
- * we know when any of the application lifecycle events occur. This includes events
- * like when our application is to be initialised, terminated, paused, resumed etc.
- *
- */
-class Framework
-{
-public:
-
- enum Type
- {
- NORMAL, ///< normal appFramework
- WATCH, ///< watch appFramework
- WIDGET ///< widget appFramework
- };
-
- /**
- * Observer class for the framework.
- */
- class Observer
- {
- public:
-
- /**
- * Invoked when the application is to be initialised.
- */
- virtual void OnInit() {}
-
- /**
- * Invoked when the application is to be terminated.
- */
- virtual void OnTerminate() {}
-
- /**
- * Invoked when the application is to be paused.
- */
- virtual void OnPause() {}
-
- /**
- * Invoked when the application is to be resumed.
- */
- virtual void OnResume() {}
-
- /**
- * Invoked when the application is to be reset.
- */
- virtual void OnReset() {}
-
- /**
- * Invoked when the AppControl message is received.
- * @param[in] The bundle data of AppControl message.
- */
- virtual void OnAppControl(void *) {}
-
-#ifdef APPCORE_WATCH_AVAILABLE
- /**
- * Invoked at every second
- */
- virtual void OnTimeTick(WatchTime&) {}
-
- /**
- * Invoked at every second in ambient mode
- */
- virtual void OnAmbientTick(WatchTime&) {}
-
- /**
- * Invoked when the device enters or exits ambient mode
- */
- virtual void OnAmbientChanged(bool ambient) {}
-#endif
-
- /**
- * Invoked when the language of the device is changed.
- */
- virtual void OnLanguageChanged() {}
-
- /**
- * Invoked when the region is changed.
- */
- virtual void OnRegionChanged() {}
-
- /**
- * Invoked when the battery level of the device is low.
- */
- virtual void OnBatteryLow( Dali::DeviceStatus::Battery::Status status ) {}
-
- /**
- * Invoked when the memory level of the device is low.
- */
- virtual void OnMemoryLow( Dali::DeviceStatus::Memory::Status status ) {}
- };
-
-public:
-
- /**
- * Constructor
- * @param[in] observer The observer of the Framework.
- * @param[in] argc A pointer to the number of arguments.
- * @param[in] argv A pointer the the argument list.
- * @param[in] type The type of application
- */
- Framework( Observer& observer, int* argc, char ***argv, Type type = NORMAL );
-
- /**
- * Destructor
- */
- ~Framework();
-
-public:
-
- /**
- * Runs the main loop of framework
- */
- void Run();
-
- /**
- * Quits the main loop
- */
- void Quit();
-
- /**
- * Checks whether the main loop of the framework is running.
- * @return true, if the main loop is running, false otherwise.
- */
- bool IsMainLoopRunning();
-
- /**
- * If the main loop aborts unexpectedly, then the connected callback function is called.
- * @param[in] callBack The function to call.
- * @note Only one callback can be registered. The last callback to be set will be called on abort.
- * @note The ownership of callback is passed onto this class.
- */
- void AddAbortCallback( CallbackBase* callback );
-
- /**
- * Gets bundle name which was passed in app_reset callback.
- */
- std::string GetBundleName() const;
-
- /**
- * Gets bundle id which was passed in app_reset callback.
- */
- std::string GetBundleId() const;
-
- /**
- * Gets the path at which application resources are stored.
- */
- static std::string GetResourcePath();
-
- /**
- * Sets system language.
- */
- void SetLanguage( const std::string& language );
-
- /**
- * Sets system region.
- */
- void SetRegion( const std::string& region );
-
- /**
- * Gets system language.
- */
- std::string GetLanguage() const;
-
- /**
- * Gets system region.
- */
- std::string GetRegion() const;
-
-private:
-
- // Undefined
- Framework(const Framework&);
- Framework& operator=(Framework&);
-
-private:
-
- /**
- * Called when the application is created.
- */
- bool Create();
-
- /**
- * Called by the App framework when an application lifecycle event occurs.
- * @param[in] type The type of event occurred.
- * @param[in] bundleData The bundle data of event occurred.
- */
- bool AppStatusHandler(int type, void *bundleData);
-
- /**
- * Called app_reset callback was called with bundle.
- */
- void SetBundleName(const std::string& name);
-
- /**
- * Called app_reset callback was called with bundle.
- */
- void SetBundleId(const std::string& id);
-
- /**
- * Called if the application is aborted.
- */
- void AbortCallback();
-
- /**
- * Called for initializing on specified backend. (X11 or Wayland)
- */
- void InitThreads();
-
-private:
- Observer& mObserver;
- bool mInitialised;
- bool mRunning;
- int* mArgc;
- char*** mArgv;
- std::string mBundleName;
- std::string mBundleId;
- AbortHandler mAbortHandler;
-
-private: // impl members
-
- struct Impl;
- Impl* mImpl;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_FRAMEWORK_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <gl/egl-debug.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Egl
-{
-
-void PrintError( EGLint error)
-{
- switch (error)
- {
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR("EGL_BAD_DISPLAY : Display is not an EGL display connection\n");
- break;
- }
- case EGL_NOT_INITIALIZED:
- {
- DALI_LOG_ERROR("EGL_NOT_INITIALIZED : Display has not been initialized\n");
- break;
- }
- case EGL_BAD_SURFACE:
- {
- DALI_LOG_ERROR("EGL_BAD_SURFACE : Draw or read is not an EGL surface\n");
- break;
- }
- case EGL_BAD_CONTEXT:
- {
- DALI_LOG_ERROR("EGL_BAD_CONTEXT : Context is not an EGL rendering context\n");
- break;
- }
- case EGL_BAD_MATCH:
- {
- DALI_LOG_ERROR("EGL_BAD_MATCH : Draw or read are not compatible with context, or if context is set to EGL_NO_CONTEXT and draw or read are not set to EGL_NO_SURFACE, or if draw or read are set to EGL_NO_SURFACE and context is not set to EGL_NO_CONTEXT\n");
- break;
- }
- case EGL_BAD_ACCESS:
- {
- DALI_LOG_ERROR("EGL_BAD_ACCESS : Context is current to some other thread\n");
- break;
- }
- case EGL_BAD_NATIVE_PIXMAP:
- {
- DALI_LOG_ERROR("EGL_BAD_NATIVE_PIXMAP : A native pixmap underlying either draw or read is no longer valid\n");
- break;
- }
- case EGL_BAD_NATIVE_WINDOW:
- {
- DALI_LOG_ERROR("EGL_BAD_NATIVE_WINDOW : A native window underlying either draw or read is no longer valid\n");
- break;
- }
- case EGL_BAD_CURRENT_SURFACE:
- {
- DALI_LOG_ERROR("EGL_BAD_CURRENT_SURFACE : The previous context has unflushed commands and the previous surface is no longer valid\n");
- break;
- }
- case EGL_BAD_ALLOC:
- {
- DALI_LOG_ERROR("EGL_BAD_ALLOC : Allocation of ancillary buffers for draw or read were delayed until eglMakeCurrent is called, and there are not enough resources to allocate them\n");
- break;
- }
- case EGL_CONTEXT_LOST:
- {
- DALI_LOG_ERROR("EGL_CONTEXT_LOST : If a power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering\n");
- break;
- }
- default:
- {
- DALI_LOG_ERROR("Unknown error with code: %d\n", error);
- break;
- }
- }
-}
-
-} // namespace Egl
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "egl-factory.h"
-
-// INTERNAL INCLUDES
-#include <gl/egl-implementation.h>
-#include <gl/egl-image-extensions.h>
-#include <gl/egl-sync-implementation.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-EglFactory::EglFactory( int multiSamplingLevel,
- Integration::DepthBufferAvailable depthBufferRequired,
- Integration::StencilBufferAvailable stencilBufferRequired )
-: mEglImplementation(NULL),
- mEglImageExtensions(NULL),
- mEglSync(new EglSyncImplementation), // Created early, as needed by Core constructor
- mMultiSamplingLevel( multiSamplingLevel ),
- mDepthBufferRequired( depthBufferRequired ),
- mStencilBufferRequired( stencilBufferRequired )
-{
-}
-
-EglFactory::~EglFactory()
-{
- // Ensure the EGL implementation is destroyed
- delete mEglImageExtensions;
- delete mEglImplementation;
- delete mEglSync;
-}
-
-EglInterface* EglFactory::Create()
-{
- // Created by RenderThread (After Core construction)
- mEglImplementation = new EglImplementation( mMultiSamplingLevel, mDepthBufferRequired, mStencilBufferRequired );
- mEglImageExtensions = new EglImageExtensions( mEglImplementation );
-
- mEglSync->Initialize(mEglImplementation); // The sync impl needs the EglDisplay
- return mEglImplementation;
-}
-
-void EglFactory::Destroy()
-{
- delete mEglImageExtensions;
- mEglImageExtensions = NULL;
- delete mEglImplementation;
- mEglImplementation = NULL;
-}
-
-EglInterface* EglFactory::GetImplementation()
-{
- return mEglImplementation;
-}
-
-EglImageExtensions* EglFactory::GetImageExtensions()
-{
- return mEglImageExtensions;
-}
-
-EglSyncImplementation* EglFactory::GetSyncImplementation()
-{
- return mEglSync;
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
-#define DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/core-enumerations.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/egl-factory-interface.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-class EglImplementation;
-class EglImageExtensions;
-class EglSyncImplementation;
-
-class EglFactory : public EglFactoryInterface
-{
-public:
-
- /**
- * Constructor
- * @param[in] multiSamplingLevel The Multi-sampling level required
- * @param[in] depthBufferRequired Whether the depth buffer is required
- * @param[in] stencilBufferRequired Whether the stencil buffer is required
- */
- EglFactory( int multiSamplingLevel,
- Integration::DepthBufferAvailable depthBufferRequired,
- Integration::StencilBufferAvailable stencilBufferRequired );
-
- /**
- * Destructor
- */
- virtual ~EglFactory();
-
- /**
- * Create an EGL Implementation
- * @return[in] An implementation
- */
- EglInterface* Create();
-
- /**
- * Destroy the EGL Implementation
- */
- void Destroy();
-
- /**
- * Get an implementation if one has been created.
- * @return An implementation, or NULL if one has not yet been created.
- */
- EglInterface* GetImplementation();
-
- /**
- * Get the image extension
- */
- EglImageExtensions* GetImageExtensions();
-
- /**
- * Get the fence sync implementation
- * @return An implementation of fence sync
- */
- EglSyncImplementation* GetSyncImplementation();
-
-private:
- /** Undefined */
- EglFactory(const EglFactory& rhs);
- EglFactory& operator=(const EglFactory& rhs);
-
-private:
- EglImplementation* mEglImplementation;
- EglImageExtensions* mEglImageExtensions;
- EglSyncImplementation* mEglSync;
-
- int mMultiSamplingLevel;
- Integration::DepthBufferAvailable mDepthBufferRequired;
- Integration::StencilBufferAvailable mStencilBufferRequired;
-};
-
-} // namespace Adaptor
-} // namespace Internal
-} // namespace Dali
-
-#endif // DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// CLASS HEADER
-#include "egl-image-extensions.h"
-
-// EXTERNAL INCLUDES
-#if DALI_GLES_VERSION >= 30
-#include <GLES3/gl3.h>
-#include <GLES3/gl3ext.h>
-
-#else
-#include <GLES2/gl2.h>
-#endif // DALI_GLES_VERSION >= 30
-
-#include <GLES2/gl2ext.h>
-
-#include <EGL/eglext.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-implementation.h>
-
-
-namespace
-{
-// function pointers assigned in InitializeEglImageKHR
-PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0;
-PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0;
-PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0;
-} // unnamed namespace
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl)
-: mEglImplementation(eglImpl),
- mImageKHRInitialized(false),
- mImageKHRInitializeFailed(false)
-{
- DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" );
-}
-
-EglImageExtensions::~EglImageExtensions()
-{
-}
-
-void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer)
-{
- if (mImageKHRInitialized == false)
- {
- InitializeEglImageKHR();
- }
-
- if (mImageKHRInitialized == false)
- {
- return NULL;
- }
-
- // Use the EGL image extension
- const EGLint attribs[] =
- {
- EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
- EGL_NONE
- };
-
-// EGL constants use C casts
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
- EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(),
- EGL_NO_CONTEXT,
- EGL_NATIVE_PIXMAP_KHR,
- clientBuffer,
- attribs );
-
- DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n");
- if( EGL_NO_IMAGE_KHR == eglImage )
- {
- switch( eglGetError() )
- {
- case EGL_SUCCESS :
- {
- break;
- }
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
- break;
- }
- case EGL_BAD_CONTEXT:
- {
- DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" );
- break;
- }
- case EGL_BAD_PARAMETER:
- {
- DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" );
- break;
- }
- case EGL_BAD_MATCH:
- {
- DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" );
- break;
- }
- case EGL_BAD_ACCESS:
- {
- DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" );
- break;
- }
- case EGL_BAD_ALLOC:
- {
- DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" );
- break;
- }
- default:
- {
- break;
- }
- }
- }
-#pragma GCC diagnostic pop
-
- return eglImage;
-}
-
-void EglImageExtensions::DestroyImageKHR(void* eglImageKHR)
-{
- DALI_ASSERT_DEBUG( mImageKHRInitialized );
-
- if( ! mImageKHRInitialized )
- {
- return;
- }
-
- if( eglImageKHR == NULL )
- {
- return;
- }
-
- EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
-
- EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage);
-
- if( EGL_FALSE == result )
- {
- switch( eglGetError() )
- {
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
- break;
- }
- case EGL_BAD_PARAMETER:
- {
- DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" );
- break;
- }
- case EGL_BAD_ACCESS:
- {
- DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" );
- break;
- }
- default:
- {
- break;
- }
- }
- }
-}
-
-void EglImageExtensions::TargetTextureKHR(void* eglImageKHR)
-{
- DALI_ASSERT_DEBUG( mImageKHRInitialized );
-
- if( eglImageKHR != NULL )
- {
- EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
-
-#ifdef EGL_ERROR_CHECKING
- GLint glError = glGetError();
-#endif
-
- glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast< GLeglImageOES >( eglImage ) );
-
-#ifdef EGL_ERROR_CHECKING
- glError = glGetError();
- if( GL_NO_ERROR != glError )
- {
- DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError );
- }
-#endif
- }
-}
-
-void EglImageExtensions::InitializeEglImageKHR()
-{
- // avoid trying to reload extended KHR functions, if it fails the first time
- if( ! mImageKHRInitializeFailed )
- {
- eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") );
- eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") );
- glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") );
- }
-
- if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc)
- {
- mImageKHRInitialized = true;
- }
- else
- {
- mImageKHRInitializeFailed = true;
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// CLASS HEADER
-#include <gl/egl-implementation.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <gl/gl-implementation.h>
-#include <gl/egl-debug.h>
-
-// EGL constants use C style casts
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#define TEST_EGL_ERROR(lastCommand) \
-{ \
- EGLint err = eglGetError(); \
- if (err != EGL_SUCCESS) \
- { \
- DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \
- Egl::PrintError(err); \
- DALI_ASSERT_ALWAYS(0 && "EGL error"); \
- } \
-}
-
-EglImplementation::EglImplementation( int multiSamplingLevel,
- Integration::DepthBufferAvailable depthBufferRequired,
- Integration::StencilBufferAvailable stencilBufferRequired )
-: mContextAttribs(),
- mEglNativeDisplay( 0 ),
- mEglNativeWindow( 0 ),
- mCurrentEglNativePixmap( 0 ),
- mEglDisplay( 0 ),
- mEglConfig( 0 ),
- mEglContext( 0 ),
- mCurrentEglSurface( 0 ),
- mMultiSamplingLevel( multiSamplingLevel ),
- mColorDepth( COLOR_DEPTH_24 ),
- mGlesInitialized( false ),
- mIsOwnSurface( true ),
- mContextCurrent( false ),
- mIsWindow( true ),
- mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ),
- mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE )
-{
-}
-
-EglImplementation::~EglImplementation()
-{
- TerminateGles();
-}
-
-bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface )
-{
- if ( !mGlesInitialized )
- {
- mEglNativeDisplay = display;
-
- //@todo see if we can just EGL_DEFAULT_DISPLAY instead
- mEglDisplay = eglGetDisplay(mEglNativeDisplay);
- EGLint error = eglGetError();
-
- if( mEglDisplay == NULL && error != EGL_SUCCESS )
- {
- throw Dali::DaliException( "", "OpenGL ES is not supported");
- }
-
- EGLint majorVersion = 0;
- EGLint minorVersion = 0;
- if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) )
- {
- return false;
- }
- eglBindAPI(EGL_OPENGL_ES_API);
-
- mContextAttribs.Clear();
-
-#if DALI_GLES_VERSION >= 30
-
- mContextAttribs.Reserve(5);
- mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR );
- mContextAttribs.PushBack( DALI_GLES_VERSION / 10 );
- mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR );
- mContextAttribs.PushBack( DALI_GLES_VERSION % 10 );
-
-#else // DALI_GLES_VERSION >= 30
-
- mContextAttribs.Reserve(3);
- mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION );
- mContextAttribs.PushBack( 2 );
-
-#endif // DALI_GLES_VERSION >= 30
-
- mContextAttribs.PushBack( EGL_NONE );
-
- mGlesInitialized = true;
- mIsOwnSurface = isOwnSurface;
- }
-
- return mGlesInitialized;
-}
-
-bool EglImplementation::CreateContext()
-{
- // make sure a context isn't created twice
- DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" );
-
- mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0]));
- TEST_EGL_ERROR("eglCreateContext render thread");
-
- DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" );
-
- DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
- DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
- DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
- DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
- DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
-
- return true;
-}
-
-void EglImplementation::DestroyContext()
-{
- DALI_ASSERT_ALWAYS( mEglContext && "no EGL context" );
-
- eglDestroyContext( mEglDisplay, mEglContext );
- mEglContext = 0;
-}
-
-void EglImplementation::DestroySurface()
-{
- if(mIsOwnSurface && mCurrentEglSurface)
- {
- // Make context null to prevent crash in driver side
- MakeContextNull();
- eglDestroySurface( mEglDisplay, mCurrentEglSurface );
- mCurrentEglSurface = 0;
- }
-}
-
-void EglImplementation::MakeContextCurrent()
-{
- mContextCurrent = true;
-
- if(mIsOwnSurface)
- {
- eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
- }
-
- EGLint error = eglGetError();
-
- if ( error != EGL_SUCCESS )
- {
- Egl::PrintError(error);
-
- DALI_ASSERT_ALWAYS(false && "MakeContextCurrent failed!");
- }
-
- // We want to display this information all the time, so use the LogMessage directly
- Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n"
- " Vendor: %s\n"
- " Version: %s\n"
- " Client APIs: %s\n"
- " Extensions: %s\n",
- eglQueryString(mEglDisplay, EGL_VENDOR),
- eglQueryString(mEglDisplay, EGL_VERSION),
- eglQueryString(mEglDisplay, EGL_CLIENT_APIS),
- eglQueryString(mEglDisplay, EGL_EXTENSIONS));
-}
-
-void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface )
-{
- mCurrentEglNativePixmap = pixmap;
- mCurrentEglSurface = eglSurface;
-
- if(mIsOwnSurface)
- {
- eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
- }
-
- EGLint error = eglGetError();
-
- if ( error != EGL_SUCCESS )
- {
- Egl::PrintError(error);
-
- DALI_ASSERT_ALWAYS(false && "MakeCurrent failed!");
- }
-}
-
-void EglImplementation::MakeContextNull()
-{
- mContextCurrent = false;
- // clear the current context
- eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
-}
-
-void EglImplementation::TerminateGles()
-{
- if ( mGlesInitialized )
- {
- // Make context null to prevent crash in driver side
- MakeContextNull();
-
- if(mIsOwnSurface && mCurrentEglSurface)
- {
- eglDestroySurface(mEglDisplay, mCurrentEglSurface);
- }
- eglDestroyContext(mEglDisplay, mEglContext);
-
- eglTerminate(mEglDisplay);
-
- mEglDisplay = NULL;
- mEglConfig = NULL;
- mEglContext = NULL;
- mCurrentEglSurface = NULL;
-
- mGlesInitialized = false;
- }
-}
-
-bool EglImplementation::IsGlesInitialized() const
-{
- return mGlesInitialized;
-}
-
-void EglImplementation::SwapBuffers()
-{
- eglSwapBuffers( mEglDisplay, mCurrentEglSurface );
-}
-
-void EglImplementation::CopyBuffers()
-{
- eglCopyBuffers( mEglDisplay, mCurrentEglSurface, mCurrentEglNativePixmap );
-}
-
-void EglImplementation::WaitGL()
-{
- eglWaitGL();
-}
-
-void EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth )
-{
- if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth)
- {
- return;
- }
-
- mIsWindow = isWindowType;
-
- EGLint numConfigs;
- Vector<EGLint> configAttribs;
- configAttribs.Reserve(31);
-
- if(isWindowType)
- {
- configAttribs.PushBack( EGL_SURFACE_TYPE );
- configAttribs.PushBack( EGL_WINDOW_BIT );
- }
- else
- {
- configAttribs.PushBack( EGL_SURFACE_TYPE );
- configAttribs.PushBack( EGL_PIXMAP_BIT );
- }
-
- configAttribs.PushBack( EGL_RENDERABLE_TYPE );
-
-#if DALI_GLES_VERSION >= 30
-
-#ifdef _ARCH_ARM_
- configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR );
-#else
- // There is a bug in the desktop emulator
- // Requesting for ES3 causes eglCreateContext even though it allows to ask
- // for a configuration that supports GLES 3.0
- configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
-#endif // _ARCH_ARM_
-
-#else // DALI_GLES_VERSION >= 30
-
- Integration::Log::LogMessage( Integration::Log::DebugInfo, "Using OpenGL ES 2 \n" );
- configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
-
-#endif //DALI_GLES_VERSION >= 30
-
-#if DALI_GLES_VERSION >= 30
-// TODO: enable this flag when it becomes supported
-// configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR );
-// configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR );
-#endif //DALI_GLES_VERSION >= 30
-
- configAttribs.PushBack( EGL_RED_SIZE );
- configAttribs.PushBack( 8 );
- configAttribs.PushBack( EGL_GREEN_SIZE );
- configAttribs.PushBack( 8 );
- configAttribs.PushBack( EGL_BLUE_SIZE );
- configAttribs.PushBack( 8 );
-
- configAttribs.PushBack( EGL_ALPHA_SIZE );
-#ifdef _ARCH_ARM_
- configAttribs.PushBack( (depth == COLOR_DEPTH_32) ? 8 : 0 );
-#else
- // There is a bug in the desktop emulator
- // setting EGL_ALPHA_SIZE to 8 results in eglChooseConfig failing
- configAttribs.PushBack( 0 );
-#endif // _ARCH_ARM_
-
- configAttribs.PushBack( EGL_DEPTH_SIZE );
- configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 );
- configAttribs.PushBack( EGL_STENCIL_SIZE );
- configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 );
-
-#ifndef DALI_PROFILE_UBUNTU
- if( mMultiSamplingLevel != EGL_DONT_CARE )
- {
- configAttribs.PushBack( EGL_SAMPLES );
- configAttribs.PushBack( mMultiSamplingLevel );
- configAttribs.PushBack( EGL_SAMPLE_BUFFERS );
- configAttribs.PushBack( 1 );
- }
-#endif // DALI_PROFILE_UBUNTU
- configAttribs.PushBack( EGL_NONE );
-
- if ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE )
- {
- EGLint error = eglGetError();
- switch (error)
- {
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR("Display is not an EGL display connection\n");
- break;
- }
- case EGL_BAD_ATTRIBUTE:
- {
- DALI_LOG_ERROR("The parameter configAttribs contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range\n");
- break;
- }
- case EGL_NOT_INITIALIZED:
- {
- DALI_LOG_ERROR("Display has not been initialized\n");
- break;
- }
- case EGL_BAD_PARAMETER:
- {
- DALI_LOG_ERROR("The parameter numConfig is NULL\n");
- break;
- }
- default:
- {
- DALI_LOG_ERROR("Unknown error.\n");
- }
- }
- DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!");
- }
-
- if ( numConfigs != 1 )
- {
- DALI_LOG_ERROR("No configurations found.\n");
-
- TEST_EGL_ERROR("eglChooseConfig");
- }
-}
-
-void EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth )
-{
- DALI_ASSERT_ALWAYS( ( mCurrentEglSurface == 0 ) && "EGL surface already exists" );
-
- mEglNativeWindow = window;
- mColorDepth = depth;
- mIsWindow = true;
-
- // egl choose config
- ChooseConfig(mIsWindow, mColorDepth);
-
- mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL );
- TEST_EGL_ERROR("eglCreateWindowSurface");
-
- DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" );
-}
-
-EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth )
-{
- mCurrentEglNativePixmap = pixmap;
- mColorDepth = depth;
- mIsWindow = false;
-
- // egl choose config
- ChooseConfig(mIsWindow, mColorDepth);
-
- mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL );
- TEST_EGL_ERROR("eglCreatePixmapSurface");
-
- DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" );
-
- return mCurrentEglSurface;
-}
-
-bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window )
-{
- bool contextLost = false;
-
- // display connection has not changed, then we can just create a new surface
- // the surface is bound to the context, so set the context to null
- MakeContextNull();
-
- // destroy the surface
- DestroySurface();
-
- // create the EGL surface
- CreateSurfaceWindow( window, mColorDepth );
-
- // set the context to be current with the new surface
- MakeContextCurrent();
-
- return contextLost;
-}
-
-bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface )
-{
- bool contextLost = false;
-
- // display connection has not changed, then we can just create a new surface
- // create the EGL surface
- eglSurface = CreateSurfacePixmap( pixmap, mColorDepth );
-
- // set the eglSurface to be current
- MakeCurrent( pixmap, eglSurface );
-
- return contextLost;
-}
-
-EGLDisplay EglImplementation::GetDisplay() const
-{
- return mEglDisplay;
-}
-
-EGLDisplay EglImplementation::GetContext() const
-{
- return mEglContext;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef DALI_INTERNAL_EGL_IMPLEMENTATION_H
-#define DALI_INTERNAL_EGL_IMPLEMENTATION_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/integration-api/core-enumerations.h>
-
-// INTERNAL INCLUDES
-#include <adaptors/integration-api/egl-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * EglImplementation class provides an EGL implementation.
- */
-class EglImplementation : public EglInterface
-{
-public:
-
- /**
- * Constructor
- * @param[in] multiSamplingLevel The Multi-sampling level required
- * @param[in] depthBufferRequired Whether the depth buffer is required
- * @param[in] stencilBufferRequired Whether the stencil buffer is required
- */
- EglImplementation( int multiSamplingLevel,
- Integration::DepthBufferAvailable depthBufferRequired,
- Integration::StencilBufferAvailable stencilBufferRequired );
-
- /**
- * Destructor
- */
- virtual ~EglImplementation();
-
-public:
-
- /**
- * (Called from ECoreX::RenderSurface, not RenderThread, so not in i/f, hence, not virtual)
- * Initialize GL
- * @param display The display
- * @param isOwnSurface whether the surface is own or not
- * @return true on success, false on failure
- */
- bool InitializeGles( EGLNativeDisplayType display, bool isOwnSurface = true );
-
- /**
- * Create the OpenGL context.
- * @return true if successful
- */
- virtual bool CreateContext();
-
- /**
- * Destroy the OpenGL context.
- */
- void DestroyContext();
-
- /**
- * Destroy the OpenGL surface.
- */
- void DestroySurface();
-
- /**
- * Make the OpenGL context current
- */
- virtual void MakeContextCurrent();
-
- /**
- * clear the OpenGL context
- */
- void MakeContextNull();
-
- /**
- * @brief Make the OpenGL surface current
- *
- * @param pixmap The pixmap to replace the current surface
- * @param eglSurface The eglSurface to replace the current OpenGL surface.
- */
- void MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface );
-
- /**
- * Terminate GL
- */
- virtual void TerminateGles();
-
- /**
- * Checks if GL is initialised
- * @return true if it is
- */
- bool IsGlesInitialized() const;
-
- /**
- * Performs an OpenGL swap buffers command
- */
- virtual void SwapBuffers();
-
- /**
- * Performs an OpenGL copy buffers command
- */
- virtual void CopyBuffers();
-
- /**
- * Performs an EGL wait GL command
- */
- virtual void WaitGL();
-
- /**
- * Choose config of egl
- * @param isWindowType whether the config for window or pixmap
- * @param colorDepth Bit per pixel value (ex. 32 or 24)
- */
- void ChooseConfig( bool isWindowType, ColorDepth depth );
-
- /**
- * Create an OpenGL surface using a window
- * @param window The window to create the surface on
- * @param colorDepth Bit per pixel value (ex. 32 or 24)
- * @return true on success, false on failure
- */
- void CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth );
-
- /**
- * Create the OpenGL surface using a pixmap
- * @param pixmap The pixmap to create the surface on
- * @param colorDepth Bit per pixel value (ex. 32 or 24)
- * @return Handle to an off-screen EGL pixmap surface (the requester has an ownership of this egl surface)
- */
- EGLSurface CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth );
-
- /**
- * Replaces the render surface
- * @param[in] window, the window to create the new surface on
- * @return true if the context was lost due to a change in display
- * between old surface and new surface
- */
- bool ReplaceSurfaceWindow( EGLNativeWindowType window );
-
- /**
- * Replaces the render surface
- * @param[in] pixmap, the pixmap to replace the new surface on
- * @param[out] eglSurface, the eglSurface is created using a pixmap.
- * @return true if the context was lost due to a change in x-display
- * between old surface and new surface
- */
- bool ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface );
-
- /**
- * returns the display with which this object was initialized
- * @return the EGL Display.
- */
- EGLDisplay GetDisplay() const;
-
- /**
- * Returns the EGL context
- * @return the EGL context.
- */
- EGLContext GetContext() const;
-
-private:
-
- Vector<EGLint> mContextAttribs;
-
- EGLNativeDisplayType mEglNativeDisplay;
-
- EGLNativeWindowType mEglNativeWindow;
-
- EGLNativePixmapType mCurrentEglNativePixmap;
-
- EGLDisplay mEglDisplay;
- EGLConfig mEglConfig;
- EGLContext mEglContext;
- EGLSurface mCurrentEglSurface;
-
- int mMultiSamplingLevel;
-
- ColorDepth mColorDepth;
-
- bool mGlesInitialized;
- bool mIsOwnSurface;
- bool mContextCurrent;
- bool mIsWindow;
- bool mDepthBufferRequired;
- bool mStencilBufferRequired;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_INTERNAL_EGL_IMPLEMENTATION_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <gl/egl-sync-implementation.h>
-
-// EXTERNAL INCLUDES
-
-#ifdef _ARCH_ARM_
-
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-#include <EGL/eglext.h>
-
-#endif
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-implementation.h>
-
-#ifdef _ARCH_ARM_
-
-// function pointers
-static PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR = NULL;
-static PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR = NULL;
-static PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR = NULL;
-
-#endif
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-#ifdef _ARCH_ARM_
-
-EglSyncObject::EglSyncObject( EglImplementation& eglSyncImpl )
-: mEglSync(NULL),
- mEglImplementation(eglSyncImpl)
-{
- EGLDisplay display = mEglImplementation.GetDisplay();
- mEglSync = eglCreateSyncKHR( display, EGL_SYNC_FENCE_KHR, NULL );
- if (mEglSync == EGL_NO_SYNC_KHR)
- {
- DALI_LOG_ERROR("eglCreateSyncKHR failed %#0.4x\n", eglGetError());
- mEglSync = NULL;
- }
-}
-
-EglSyncObject::~EglSyncObject()
-{
- if( mEglSync != NULL )
- {
- eglDestroySyncKHR( mEglImplementation.GetDisplay(), mEglSync );
- EGLint error = eglGetError();
- if( EGL_SUCCESS != error )
- {
- DALI_LOG_ERROR("eglDestroySyncKHR failed %#0.4x\n", error);
- }
- }
-}
-
-bool EglSyncObject::IsSynced()
-{
- bool synced = false;
-
- if( mEglSync != NULL )
- {
- EGLint result = eglClientWaitSyncKHR( mEglImplementation.GetDisplay(), mEglSync, 0, 0ull );
- EGLint error = eglGetError();
- if( EGL_SUCCESS != error )
- {
- DALI_LOG_ERROR("eglClientWaitSyncKHR failed %#0.4x\n", error);
- }
- else if( result == EGL_CONDITION_SATISFIED_KHR )
- {
- synced = true;
- }
- }
-
- return synced;
-}
-
-EglSyncImplementation::EglSyncImplementation()
-: mEglImplementation( NULL ),
- mSyncInitialized( false ),
- mSyncInitializeFailed( false )
-{
-}
-
-EglSyncImplementation::~EglSyncImplementation()
-{
-}
-
-void EglSyncImplementation::Initialize( EglImplementation* eglImpl )
-{
- mEglImplementation = eglImpl;
-}
-
-Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject()
-{
- DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
- if( mSyncInitialized == false )
- {
- InitializeEglSync();
- }
-
- EglSyncObject* syncObject = new EglSyncObject(*mEglImplementation);
- mSyncObjects.PushBack( syncObject );
- return syncObject;
-}
-
-void EglSyncImplementation::DestroySyncObject( Integration::GlSyncAbstraction::SyncObject* syncObject )
-{
- DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
-
- if( mSyncInitialized == false )
- {
- InitializeEglSync();
- }
-
- for( SyncIter iter=mSyncObjects.Begin(), end=mSyncObjects.End(); iter != end; ++iter )
- {
- if( *iter == syncObject )
- {
- mSyncObjects.Erase(iter);
- break;
- }
- }
- EglSyncObject* eglSyncObject = static_cast<EglSyncObject*>(syncObject);
- delete eglSyncObject;
-}
-
-void EglSyncImplementation::InitializeEglSync()
-{
- if( ! mSyncInitializeFailed )
- {
- eglCreateSyncKHR = reinterpret_cast< PFNEGLCREATESYNCKHRPROC >( eglGetProcAddress("eglCreateSyncKHR") );
- eglClientWaitSyncKHR = reinterpret_cast< PFNEGLCLIENTWAITSYNCKHRPROC >( eglGetProcAddress("eglClientWaitSyncKHR") );
- eglDestroySyncKHR = reinterpret_cast< PFNEGLDESTROYSYNCKHRPROC >( eglGetProcAddress("eglDestroySyncKHR") );
- }
-
- if( eglCreateSyncKHR && eglClientWaitSyncKHR && eglDestroySyncKHR )
- {
- mSyncInitialized = true;
- }
- else
- {
- mSyncInitializeFailed = true;
- }
-}
-
-#else
-
-EglSyncObject::EglSyncObject( EglImplementation& eglImpl )
-: mPollCounter(3),
- mEglImplementation(eglImpl)
-{
-}
-
-EglSyncObject::~EglSyncObject()
-{
-}
-
-bool EglSyncObject::IsSynced()
-{
- if(mPollCounter <= 0)
- {
- return true;
- }
- --mPollCounter;
- return false;
-}
-
-EglSyncImplementation::EglSyncImplementation()
-: mEglImplementation( NULL ),
- mSyncInitialized( false ),
- mSyncInitializeFailed( false )
-{
-}
-
-EglSyncImplementation::~EglSyncImplementation()
-{
-}
-
-void EglSyncImplementation::Initialize( EglImplementation* eglImpl )
-{
- mEglImplementation = eglImpl;
-}
-
-Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject()
-{
- DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
- return new EglSyncObject(*mEglImplementation);
-}
-
-void EglSyncImplementation::DestroySyncObject(Integration::GlSyncAbstraction::SyncObject* syncObject)
-{
- DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
-
- // The abstraction's virtual destructor is protected, so that Core can't delete the sync objects
- // directly (This object also needs removing from the mSyncObject container in the ARM
- // implementation above). We therefore need to cast to the actual implementation object first.
- EglSyncObject* eglSyncObject = static_cast<EglSyncObject*>(syncObject);
- delete eglSyncObject;
-}
-
-void EglSyncImplementation::InitializeEglSync()
-{
-}
-
-#endif
-
-} // namespace Dali
-} // namespace Internal
-} // namespace Adaptor
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "gl-extensions.h"
-
-// EXTERNAL INCLUDES
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace ECoreX
-{
-
-GlExtensions::GlExtensions()
-:
-#if DALI_GLES_VERSION < 30
-#ifdef GL_EXT_discard_framebuffer
- mGlDiscardFramebuffer( NULL ),
-#endif
-#ifdef GL_OES_get_program_binary
- mGlGetProgramBinaryOES( NULL ),
- mGlProgramBinaryOES( NULL ),
-#endif
-#endif // DALI_GLES_VERSION < 30
- mInitialized( false )
-{
-}
-
-GlExtensions::~GlExtensions()
-{
-}
-
-#if DALI_GLES_VERSION < 30
-
-void GlExtensions::DiscardFrameBuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments)
-{
- // initialize extension on first use as on some hw platforms a context
- // has to be bound for the extensions to return correct pointer
- if( !mInitialized )
- {
- Initialize();
- }
-
-#ifdef GL_EXT_discard_framebuffer
- if( mGlDiscardFramebuffer )
- {
- mGlDiscardFramebuffer(target, numAttachments, attachments);
- }
- else
- {
- DALI_LOG_ERROR("Error: glDiscardFramebufferEXT extension is not available\n");
- }
-#endif
-}
-
-void GlExtensions::GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary)
-{
- // initialize extension on first use as on some hw platforms a context
- // has to be bound for the extensions to return correct pointer
- if( !mInitialized )
- {
- Initialize();
- }
-
-#ifdef GL_OES_get_program_binary
- if (mGlGetProgramBinaryOES)
- {
- mGlGetProgramBinaryOES(program, bufSize, length, binaryFormat, binary);
- }
- else
- {
- DALI_LOG_ERROR("Error: glGetProgramBinaryOES extension is not available\n");
- DALI_ASSERT_DEBUG(0);
- }
-#endif
-}
-
-void GlExtensions::ProgramBinaryOES(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length)
-{
- // initialize extension on first use as on some hw platforms a context
- // has to be bound for the extensions to return correct pointer
- if( !mInitialized )
- {
- Initialize();
- }
-
-#ifdef GL_OES_get_program_binary
- if (mGlProgramBinaryOES)
- {
- mGlProgramBinaryOES(program, binaryFormat, binary, length);
- }
- else
- {
- DALI_LOG_ERROR("Error: glProgramBinaryOES extension is not available\n");
- DALI_ASSERT_DEBUG(0);
- }
-#endif
-}
-
-void GlExtensions::Initialize()
-{
- mInitialized = true;
-
-#ifdef GL_EXT_discard_framebuffer
- mGlDiscardFramebuffer = reinterpret_cast< PFNGLDISCARDFRAMEBUFFEREXTPROC >( eglGetProcAddress("glDiscardFramebufferEXT") );
-#endif
-
-#ifdef GL_OES_get_program_binary
- mGlGetProgramBinaryOES = reinterpret_cast< PFNGLGETPROGRAMBINARYOESPROC >( eglGetProcAddress("glGetProgramBinaryOES") );
- mGlProgramBinaryOES = reinterpret_cast< PFNGLPROGRAMBINARYOESPROC >( eglGetProcAddress("glProgramBinaryOES") );
-#endif
-}
-
-#endif // DALI_GLES_VERSION < 30
-
-} // namespace ECoreX
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_GL_IMPLEMENTATION_H__
-#define __DALI_INTERNAL_GL_IMPLEMENTATION_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#ifndef DALI_GLES_VERSION
-#error "OpenGL ES version not specified"
-#endif
-
-#if DALI_GLES_VERSION >= 31
-#include <GLES3/gl31.h>
-#elif DALI_GLES_VERSION >= 30
-#include <GLES3/gl3.h>
-#else
-#include <cstdlib>
-#include <GLES2/gl2.h>
-#endif
-
-#include <dali/integration-api/gl-abstraction.h>
-
-// INTERNAL INCLUDES
-#include <gl/gl-extensions.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * GlImplementation is a concrete implementation for GlAbstraction.
- * The class provides an OpenGL-ES 2.0 implementation.
- * The class is provided when creating the Integration::Core object.
- */
-class GlImplementation: public Dali::Integration::GlAbstraction
-{
-
-public:
- virtual ~GlImplementation() {}
-
- void PreRender()
- {
- /* Do nothing in main implementation */
- }
-
- void PostRender()
- {
- /* Do nothing in main implementation */
- }
-
- /* OpenGL ES 2.0 */
-
- void ActiveTexture (GLenum texture)
- {
- glActiveTexture(texture);
- }
-
- void AttachShader (GLuint program, GLuint shader)
- {
- glAttachShader(program,shader);
- }
-
- void BindAttribLocation (GLuint program, GLuint index, const char* name)
- {
- glBindAttribLocation(program,index,name);
- }
-
- void BindBuffer (GLenum target, GLuint buffer)
- {
- glBindBuffer(target,buffer);
- }
-
- void BindFramebuffer (GLenum target, GLuint framebuffer)
- {
- glBindFramebuffer(target,framebuffer);
- }
-
- void BindRenderbuffer (GLenum target, GLuint renderbuffer)
- {
- glBindRenderbuffer(target,renderbuffer);
- }
-
- void BindTexture (GLenum target, GLuint texture)
- {
- glBindTexture(target,texture);
- }
-
- void BlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
- {
- glBlendColor(red,green,blue,alpha);
- }
-
- void BlendEquation ( GLenum mode )
- {
- glBlendEquation(mode);
- }
-
- void BlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha)
- {
- glBlendEquationSeparate(modeRGB,modeAlpha);
- }
-
- void BlendFunc (GLenum sfactor, GLenum dfactor)
- {
- glBlendFunc(sfactor,dfactor);
- }
-
- void BlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
- {
- glBlendFuncSeparate(srcRGB,dstRGB,srcAlpha,dstAlpha);
- }
-
- void BufferData (GLenum target, GLsizeiptr size, const void* data, GLenum usage)
- {
- glBufferData(target,size,data,usage);
- }
-
- void BufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void* data)
- {
- glBufferSubData(target,offset,size,data);
- }
-
- GLenum CheckFramebufferStatus (GLenum target)
- {
- return glCheckFramebufferStatus(target);
- }
-
- void Clear (GLbitfield mask)
- {
- glClear(mask);
- }
-
- void ClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
- {
- glClearColor(red,green,blue,alpha);
- }
-
- void ClearDepthf (GLclampf depth)
- {
- glClearDepthf(depth);
- }
-
- void ClearStencil (GLint s)
- {
- glClearStencil(s);
- }
-
- void ColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
- {
- glColorMask(red,green,blue,alpha);
- }
-
- void CompileShader (GLuint shader)
- {
- glCompileShader(shader);
- }
-
- void CompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
- {
- glCompressedTexImage2D(target,level,internalformat,width,height,border,imageSize,data);
- }
-
- void CompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
- {
- glCompressedTexSubImage2D(target,level,xoffset,yoffset,width,height,format,imageSize,data);
- }
-
- void CopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
- {
- glCopyTexImage2D(target,level,internalformat,x,y,width,height,border);
- }
-
- void CopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
- {
- glCopyTexSubImage2D(target,level,xoffset,yoffset,x,y,width,height);
- }
-
- GLuint CreateProgram (void)
- {
- return glCreateProgram();
- }
-
- GLuint CreateShader (GLenum type)
- {
- return glCreateShader(type);
- }
-
- void CullFace (GLenum mode)
- {
- glCullFace(mode);
- }
-
- void DeleteBuffers (GLsizei n, const GLuint* buffers)
- {
- glDeleteBuffers(n,buffers);
- }
-
- void DeleteFramebuffers (GLsizei n, const GLuint* framebuffers)
- {
- glDeleteFramebuffers(n,framebuffers);
- }
-
- void DeleteProgram (GLuint program)
- {
- glDeleteProgram(program);
- }
-
- void DeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers)
- {
- glDeleteRenderbuffers(n,renderbuffers);
- }
-
- void DeleteShader (GLuint shader)
- {
- glDeleteShader(shader);
- }
-
- void DeleteTextures (GLsizei n, const GLuint* textures)
- {
- glDeleteTextures(n,textures);
- }
-
- void DepthFunc (GLenum func)
- {
- glDepthFunc(func);
- }
-
- void DepthMask (GLboolean flag)
- {
- glDepthMask(flag);
- }
-
- void DepthRangef (GLclampf zNear, GLclampf zFar)
- {
- glDepthRangef(zNear,zFar);
- }
-
- void DetachShader (GLuint program, GLuint shader)
- {
- glDetachShader(program,shader);
- }
-
- void Disable (GLenum cap)
- {
- glDisable(cap);
- }
-
- void DisableVertexAttribArray (GLuint index)
- {
- glDisableVertexAttribArray(index);
- }
-
- void DrawArrays (GLenum mode, GLint first, GLsizei count)
- {
- glDrawArrays(mode,first,count);
- }
-
- void DrawElements (GLenum mode, GLsizei count, GLenum type, const void* indices)
- {
- glDrawElements(mode,count,type,indices);
- }
-
- void Enable (GLenum cap)
- {
- glEnable(cap);
- }
-
- void EnableVertexAttribArray (GLuint index)
- {
- glEnableVertexAttribArray(index);
- }
-
- void Finish (void)
- {
- glFinish();
- }
-
- void Flush (void)
- {
- glFlush();
- }
-
- void FramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
- {
- glFramebufferRenderbuffer(target,attachment,renderbuffertarget,renderbuffer);
- }
-
- void FramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
- {
- glFramebufferTexture2D(target,attachment,textarget,texture,level);
- }
-
- void FrontFace (GLenum mode)
- {
- glFrontFace(mode);
- }
-
- void GenBuffers (GLsizei n, GLuint* buffers)
- {
- glGenBuffers(n,buffers);
- }
-
- void GenerateMipmap (GLenum target)
- {
- glGenerateMipmap(target);
- }
-
- void GenFramebuffers (GLsizei n, GLuint* framebuffers)
- {
- glGenFramebuffers(n,framebuffers);
- }
-
- void GenRenderbuffers (GLsizei n, GLuint* renderbuffers)
- {
- glGenRenderbuffers(n,renderbuffers);
- }
-
- void GenTextures (GLsizei n, GLuint* textures)
- {
- glGenTextures(n,textures);
- }
-
- void GetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
- {
- glGetActiveAttrib(program,index,bufsize,length,size,type,name);
- }
-
- void GetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
- {
- glGetActiveUniform(program,index,bufsize,length,size,type,name);
- }
-
- void GetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
- {
- glGetAttachedShaders(program,maxcount,count,shaders);
- }
-
- int GetAttribLocation (GLuint program, const char* name)
- {
- return glGetAttribLocation(program,name);
- }
-
- void GetBooleanv (GLenum pname, GLboolean* params)
- {
- glGetBooleanv(pname,params);
- }
-
- void GetBufferParameteriv (GLenum target, GLenum pname, GLint* params)
- {
- glGetBufferParameteriv(target,pname,params);
- }
-
- GLenum GetError (void)
- {
- return glGetError();
- }
-
- void GetFloatv (GLenum pname, GLfloat* params)
- {
- glGetFloatv(pname,params);
- }
-
- void GetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params)
- {
- glGetFramebufferAttachmentParameteriv(target,attachment,pname,params);
- }
-
- void GetIntegerv (GLenum pname, GLint* params)
- {
- glGetIntegerv(pname,params);
- }
-
- void GetProgramiv (GLuint program, GLenum pname, GLint* params)
- {
- glGetProgramiv(program,pname,params);
- }
-
- void GetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
- {
- glGetProgramInfoLog(program,bufsize,length,infolog);
- }
-
- void GetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params)
- {
- glGetRenderbufferParameteriv(target,pname,params);
- }
-
- void GetShaderiv (GLuint shader, GLenum pname, GLint* params)
- {
- glGetShaderiv(shader,pname,params);
- }
-
- void GetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
- {
- glGetShaderInfoLog(shader,bufsize,length,infolog);
- }
-
- void GetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
- {
- glGetShaderPrecisionFormat(shadertype,precisiontype,range,precision);
- }
-
- void GetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
- {
- glGetShaderSource(shader,bufsize,length,source);
- }
-
- const GLubyte* GetString (GLenum name)
- {
- return glGetString(name);
- }
-
- void GetTexParameterfv (GLenum target, GLenum pname, GLfloat* params)
- {
- glGetTexParameterfv(target,pname,params);
- }
-
- void GetTexParameteriv (GLenum target, GLenum pname, GLint* params)
- {
- glGetTexParameteriv(target,pname,params);
- }
-
- void GetUniformfv (GLuint program, GLint location, GLfloat* params)
- {
- glGetUniformfv(program,location,params);
- }
-
- void GetUniformiv (GLuint program, GLint location, GLint* params)
- {
- glGetUniformiv(program,location,params);
- }
-
- int GetUniformLocation (GLuint program, const char* name)
- {
- return glGetUniformLocation(program,name);
- }
-
- void GetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params)
- {
- glGetVertexAttribfv(index,pname,params);
- }
-
- void GetVertexAttribiv (GLuint index, GLenum pname, GLint* params)
- {
- glGetVertexAttribiv(index,pname,params);
- }
-
- void GetVertexAttribPointerv (GLuint index, GLenum pname, void** pointer)
- {
- glGetVertexAttribPointerv(index,pname,pointer);
- }
-
- void Hint (GLenum target, GLenum mode)
- {
- glHint(target,mode);
- }
-
- GLboolean IsBuffer (GLuint buffer)
- {
- return glIsBuffer(buffer);
- }
-
- GLboolean IsEnabled (GLenum cap)
- {
- return glIsEnabled(cap);
- }
-
- GLboolean IsFramebuffer (GLuint framebuffer)
- {
- return glIsFramebuffer(framebuffer);
- }
-
- GLboolean IsProgram (GLuint program)
- {
- return glIsProgram(program);
- }
-
- GLboolean IsRenderbuffer (GLuint renderbuffer)
- {
- return glIsRenderbuffer(renderbuffer);
- }
-
- GLboolean IsShader (GLuint shader)
- {
- return glIsShader(shader);
- }
-
- GLboolean IsTexture (GLuint texture)
- {
- return glIsTexture(texture);
- }
-
- void LineWidth (GLfloat width)
- {
- glLineWidth(width);
- }
-
- void LinkProgram (GLuint program)
- {
- glLinkProgram(program);
- }
-
- void PixelStorei (GLenum pname, GLint param)
- {
- glPixelStorei(pname,param);
- }
-
- void PolygonOffset (GLfloat factor, GLfloat units)
- {
- glPolygonOffset(factor,units);
- }
-
- void ReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels)
- {
- glReadPixels(x,y,width,height,format,type,pixels);
- }
-
- void ReleaseShaderCompiler (void)
- {
- glReleaseShaderCompiler();
- }
-
- void RenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
- {
- glRenderbufferStorage(target,internalformat,width,height);
- }
-
- void SampleCoverage (GLclampf value, GLboolean invert)
- {
- glSampleCoverage(value,invert);
- }
-
- void Scissor (GLint x, GLint y, GLsizei width, GLsizei height)
- {
- glScissor(x,y,width,height);
- }
-
- void ShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length)
- {
- glShaderBinary(n,shaders,binaryformat,binary,length);
- }
-
- void ShaderSource (GLuint shader, GLsizei count, const char** string, const GLint* length)
- {
- glShaderSource(shader,count,string,length);
- }
-
- void StencilFunc (GLenum func, GLint ref, GLuint mask)
- {
- glStencilFunc(func,ref,mask);
- }
-
- void StencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask)
- {
- glStencilFuncSeparate(face,func,ref,mask);
- }
-
- void StencilMask (GLuint mask)
- {
- glStencilMask(mask);
- }
-
- void StencilMaskSeparate (GLenum face, GLuint mask)
- {
- glStencilMaskSeparate(face,mask);
- }
-
- void StencilOp (GLenum fail, GLenum zfail, GLenum zpass)
- {
- glStencilOp(fail,zfail,zpass);
- }
-
- void StencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
- {
- glStencilOpSeparate(face,fail,zfail,zpass);
- }
-
- void TexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels)
- {
- glTexImage2D(target,level,internalformat,width,height,border,format,type,pixels);
- }
-
- void TexParameterf (GLenum target, GLenum pname, GLfloat param)
- {
- glTexParameterf(target,pname,param);
- }
-
- void TexParameterfv (GLenum target, GLenum pname, const GLfloat* params)
- {
- glTexParameterfv(target,pname,params);
- }
-
- void TexParameteri (GLenum target, GLenum pname, GLint param)
- {
- glTexParameteri(target,pname,param);
- }
-
- void TexParameteriv (GLenum target, GLenum pname, const GLint* params)
- {
- glTexParameteriv(target,pname,params);
- }
-
- void TexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels)
- {
- glTexSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);
- }
-
- void Uniform1f (GLint location, GLfloat x)
- {
- glUniform1f(location,x);
- }
-
- void Uniform1fv (GLint location, GLsizei count, const GLfloat* v)
- {
- glUniform1fv(location,count,v);
- }
-
- void Uniform1i (GLint location, GLint x)
- {
- glUniform1i(location,x);
- }
-
- void Uniform1iv (GLint location, GLsizei count, const GLint* v)
- {
- glUniform1iv(location,count,v);
- }
-
- void Uniform2f (GLint location, GLfloat x, GLfloat y)
- {
- glUniform2f(location,x,y);
- }
-
- void Uniform2fv (GLint location, GLsizei count, const GLfloat* v)
- {
- glUniform2fv(location,count,v);
- }
-
- void Uniform2i (GLint location, GLint x, GLint y)
- {
- glUniform2i(location,x,y);
- }
-
- void Uniform2iv (GLint location, GLsizei count, const GLint* v)
- {
- glUniform2iv(location,count,v);
- }
-
- void Uniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z)
- {
- glUniform3f(location,x,y,z);
- }
-
- void Uniform3fv (GLint location, GLsizei count, const GLfloat* v)
- {
- glUniform3fv(location,count,v);
- }
-
- void Uniform3i (GLint location, GLint x, GLint y, GLint z)
- {
- glUniform3i(location,x,y,z);
- }
-
- void Uniform3iv (GLint location, GLsizei count, const GLint* v)
- {
- glUniform3iv(location,count,v);
- }
-
- void Uniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
- {
- glUniform4f(location,x,y,z,w);
- }
-
- void Uniform4fv (GLint location, GLsizei count, const GLfloat* v)
- {
- glUniform4fv(location,count,v);
- }
-
- void Uniform4i (GLint location, GLint x, GLint y, GLint z, GLint w)
- {
- glUniform4i(location,x,y,z,w);
- }
-
- void Uniform4iv (GLint location, GLsizei count, const GLint* v)
- {
- glUniform4iv(location,count,v);
- }
-
- void UniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
- glUniformMatrix2fv(location,count,transpose,value);
- }
-
- void UniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
- glUniformMatrix3fv(location,count,transpose,value);
- }
-
- void UniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
- glUniformMatrix4fv(location,count,transpose,value);
- }
-
- void UseProgram (GLuint program)
- {
- glUseProgram(program);
- }
-
- void ValidateProgram (GLuint program)
- {
- glValidateProgram(program);
- }
-
- void VertexAttrib1f (GLuint indx, GLfloat x)
- {
- glVertexAttrib1f(indx,x);
- }
-
- void VertexAttrib1fv (GLuint indx, const GLfloat* values)
- {
- glVertexAttrib1fv(indx,values);
- }
-
- void VertexAttrib2f (GLuint indx, GLfloat x, GLfloat y)
- {
- glVertexAttrib2f(indx,x,y);
- }
-
- void VertexAttrib2fv (GLuint indx, const GLfloat* values)
- {
- glVertexAttrib2fv(indx,values);
- }
-
- void VertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z)
- {
- glVertexAttrib3f(indx,x,y,z);
- }
-
- void VertexAttrib3fv (GLuint indx, const GLfloat* values)
- {
- glVertexAttrib3fv(indx,values);
- }
-
- void VertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
- {
- glVertexAttrib4f(indx,x,y,z,w);
- }
-
- void VertexAttrib4fv (GLuint indx, const GLfloat* values)
- {
- glVertexAttrib4fv(indx,values);
- }
-
- void VertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
- {
- glVertexAttribPointer(indx,size,type,normalized,stride,ptr);
- }
-
- void Viewport (GLint x, GLint y, GLsizei width, GLsizei height)
- {
- glViewport(x,y,width,height);
- }
-
- /* OpenGL ES 3.0 */
-
- void ReadBuffer(GLenum mode)
- {
-#if DALI_GLES_VERSION >= 30
- glReadBuffer(mode);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices)
- {
-#if DALI_GLES_VERSION >= 30
- glDrawRangeElements(mode,start,end,count,type,indices);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels)
- {
-#if DALI_GLES_VERSION >= 30
- glTexImage3D(target,level,internalformat,width,height,depth,border,format,type,pixels);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels)
- {
-#if DALI_GLES_VERSION >= 30
- glTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
- {
-#if DALI_GLES_VERSION >= 30
- glCopyTexSubImage3D(target,level,xoffset,yoffset,zoffset,x,y,width,height);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data)
- {
-#if DALI_GLES_VERSION >= 30
- glCompressedTexImage3D(target,level,internalformat,width,height,depth,border,imageSize,data);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data)
- {
-#if DALI_GLES_VERSION >= 30
- glCompressedTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GenQueries(GLsizei n, GLuint* ids)
- {
-#if DALI_GLES_VERSION >= 30
- glGenQueries(n,ids);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DeleteQueries(GLsizei n, const GLuint* ids)
- {
-#if DALI_GLES_VERSION >= 30
- glDeleteQueries(n,ids);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean IsQuery(GLuint id)
- {
-#if DALI_GLES_VERSION >= 30
- return glIsQuery(id);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BeginQuery(GLenum target, GLuint id)
- {
-#if DALI_GLES_VERSION >= 30
- glBeginQuery(target,id);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void EndQuery(GLenum target)
- {
-#if DALI_GLES_VERSION >= 30
- glEndQuery(target);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetQueryiv(GLenum target, GLenum pname, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetQueryiv(target,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetQueryObjectuiv(id,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean UnmapBuffer(GLenum target)
- {
-#if DALI_GLES_VERSION >= 30
- return glUnmapBuffer(target);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetBufferPointerv(target,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DrawBuffers(GLsizei n, const GLenum* bufs)
- {
-#if DALI_GLES_VERSION >= 30
- glDrawBuffers(n,bufs);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix2x3fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix3x2fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix2x4fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix4x2fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix3x4fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformMatrix4x3fv(location,count,transpose,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
- {
-#if DALI_GLES_VERSION >= 30
- glBlitFramebuffer(srcX0,srcY0,srcX1,srcY1,dstX0,dstY0,dstX1,dstY1,mask,filter);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
- {
-#if DALI_GLES_VERSION >= 30
- glRenderbufferStorageMultisample(target,samples,internalformat,width,height);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
- {
-#if DALI_GLES_VERSION >= 30
- glFramebufferTextureLayer(target,attachment,texture,level,layer);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
- {
-#if DALI_GLES_VERSION >= 30
- return glMapBufferRange(target,offset,length,access);
-#else
- return NULL;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
- {
-#if DALI_GLES_VERSION >= 30
- glFlushMappedBufferRange(target,offset,length);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BindVertexArray(GLuint array)
- {
-#if DALI_GLES_VERSION >= 30
- glBindVertexArray(array);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DeleteVertexArrays(GLsizei n, const GLuint* arrays)
- {
-#if DALI_GLES_VERSION >= 30
- glDeleteVertexArrays(n,arrays);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GenVertexArrays(GLsizei n, GLuint* arrays)
- {
-#if DALI_GLES_VERSION >= 30
- glGenVertexArrays(n,arrays);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean IsVertexArray(GLuint array)
- {
-#if DALI_GLES_VERSION >= 30
- return glIsVertexArray(array);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetIntegeri_v(GLenum target, GLuint index, GLint* data)
- {
-#if DALI_GLES_VERSION >= 30
- glGetIntegeri_v(target,index,data);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BeginTransformFeedback(GLenum primitiveMode)
- {
-#if DALI_GLES_VERSION >= 30
- glBeginTransformFeedback(primitiveMode);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void EndTransformFeedback(void)
- {
-#if DALI_GLES_VERSION >= 30
- glEndTransformFeedback();
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
- {
-#if DALI_GLES_VERSION >= 30
- glBindBufferRange(target,index,buffer,offset,size);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BindBufferBase(GLenum target, GLuint index, GLuint buffer)
- {
-#if DALI_GLES_VERSION >= 30
- glBindBufferBase(target,index,buffer);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode)
- {
-#if DALI_GLES_VERSION >= 30
- glTransformFeedbackVaryings(program,count,varyings,bufferMode);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name)
- {
-#if DALI_GLES_VERSION >= 30
- glGetTransformFeedbackVarying(program,index,bufSize,length,size,type,name);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribIPointer(index,size,type,stride,pointer);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetVertexAttribIiv(index,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetVertexAttribIuiv(index,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribI4i(index,x,y,z,w);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribI4ui(index,x,y,z,w);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribI4iv(GLuint index, const GLint* v)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribI4iv(index,v);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribI4uiv(GLuint index, const GLuint* v)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribI4uiv(index,v);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetUniformuiv(GLuint program, GLint location, GLuint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetUniformuiv(program,location,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLint GetFragDataLocation(GLuint program, const GLchar *name)
- {
-#if DALI_GLES_VERSION >= 30
- return glGetFragDataLocation(program,name);
-#else
- return -1;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform1ui(GLint location, GLuint v0)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform1ui(location,v0);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform2ui(GLint location, GLuint v0, GLuint v1)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform2ui(location,v0,v1);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform3ui(location,v0,v1,v2);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform4ui(location,v0,v1,v2,v3);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform1uiv(GLint location, GLsizei count, const GLuint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform1uiv(location,count,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform2uiv(GLint location, GLsizei count, const GLuint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform2uiv(location,count,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform3uiv(GLint location, GLsizei count, const GLuint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform3uiv(location,count,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void Uniform4uiv(GLint location, GLsizei count, const GLuint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glUniform4uiv(location,count,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glClearBufferiv(buffer,drawbuffer,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value)
- {
-#if DALI_GLES_VERSION >= 30
- glClearBufferuiv(buffer,drawbuffer,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value)
- {
-#if DALI_GLES_VERSION >= 30
- glClearBufferfv(buffer,drawbuffer,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
- {
-#if DALI_GLES_VERSION >= 30
- glClearBufferfi(buffer,drawbuffer,depth,stencil);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- const GLubyte* GetStringi(GLenum name, GLuint index)
- {
-#if DALI_GLES_VERSION >= 30
- return glGetStringi(name,index);
-#else
- return NULL;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
- {
-#if DALI_GLES_VERSION >= 30
- glCopyBufferSubData(readTarget,writeTarget,readOffset,writeOffset,size);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices)
- {
-#if DALI_GLES_VERSION >= 30
- glGetUniformIndices(program,uniformCount,uniformNames,uniformIndices);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetActiveUniformsiv(program,uniformCount,uniformIndices,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName)
- {
-#if DALI_GLES_VERSION >= 30
- return glGetUniformBlockIndex(program,uniformBlockName);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetActiveUniformBlockiv(program,uniformBlockIndex,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName)
- {
-#if DALI_GLES_VERSION >= 30
- glGetActiveUniformBlockName(program,uniformBlockIndex,bufSize,length,uniformBlockName);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
- {
-#if DALI_GLES_VERSION >= 30
- glUniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
- {
-#if DALI_GLES_VERSION >= 30
- glDrawArraysInstanced(mode,first,count,instanceCount);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount)
- {
-#if DALI_GLES_VERSION >= 30
- glDrawElementsInstanced(mode,count,type,indices,instanceCount);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLsync FenceSync(GLenum condition, GLbitfield flags)
- {
-#if DALI_GLES_VERSION >= 30
- return glFenceSync(condition,flags);
-#else
- return NULL;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean IsSync(GLsync sync)
- {
-#if DALI_GLES_VERSION >= 30
- return glIsSync(sync);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DeleteSync(GLsync sync)
- {
-#if DALI_GLES_VERSION >= 30
- glDeleteSync(sync);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
- {
-#if DALI_GLES_VERSION >= 30
- return glClientWaitSync(sync,flags,timeout);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
- {
-#if DALI_GLES_VERSION >= 30
- glWaitSync(sync,flags,timeout);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetInteger64v(GLenum pname, GLint64* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetInteger64v(pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values)
- {
-#if DALI_GLES_VERSION >= 30
- glGetSynciv(sync,pname,bufSize,length,values);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetInteger64i_v(GLenum target, GLuint index, GLint64* data)
- {
-#if DALI_GLES_VERSION >= 30
- glGetInteger64i_v(target,index,data);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetBufferParameteri64v(target,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GenSamplers(GLsizei count, GLuint* samplers)
- {
-#if DALI_GLES_VERSION >= 30
- glGenSamplers(count,samplers);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DeleteSamplers(GLsizei count, const GLuint* samplers)
- {
-#if DALI_GLES_VERSION >= 30
- glDeleteSamplers(count,samplers);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean IsSampler(GLuint sampler)
- {
-#if DALI_GLES_VERSION >= 30
- return glIsSampler(sampler);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BindSampler(GLuint unit, GLuint sampler)
- {
-#if DALI_GLES_VERSION >= 30
- glBindSampler(unit,sampler);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void SamplerParameteri(GLuint sampler, GLenum pname, GLint param)
- {
-#if DALI_GLES_VERSION >= 30
- glSamplerParameteri(sampler,pname,param);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param)
- {
-#if DALI_GLES_VERSION >= 30
- glSamplerParameteriv(sampler,pname,param);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
- {
-#if DALI_GLES_VERSION >= 30
- glSamplerParameterf(sampler,pname,param);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param)
- {
-#if DALI_GLES_VERSION >= 30
- glSamplerParameterfv(sampler,pname,param);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetSamplerParameteriv(sampler,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetSamplerParameterfv(sampler,pname,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void VertexAttribDivisor(GLuint index, GLuint divisor)
- {
-#if DALI_GLES_VERSION >= 30
- glVertexAttribDivisor(index,divisor);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void BindTransformFeedback(GLenum target, GLuint id)
- {
-#if DALI_GLES_VERSION >= 30
- glBindTransformFeedback(target,id);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids)
- {
-#if DALI_GLES_VERSION >= 30
- glDeleteTransformFeedbacks(n,ids);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GenTransformFeedbacks(GLsizei n, GLuint* ids)
- {
-#if DALI_GLES_VERSION >= 30
- glGenTransformFeedbacks(n,ids);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- GLboolean IsTransformFeedback(GLuint id)
- {
-#if DALI_GLES_VERSION >= 30
- return glIsTransformFeedback(id);
-#else
- return 0;
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void PauseTransformFeedback(void)
- {
-#if DALI_GLES_VERSION >= 30
- glPauseTransformFeedback();
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ResumeTransformFeedback(void)
- {
-#if DALI_GLES_VERSION >= 30
- glResumeTransformFeedback();
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary)
- {
-#if DALI_GLES_VERSION >= 30
- // if OpenGL ES 2.0 compatibility is need this can be implemented with
- // glGetProgramBinaryOES
- glGetProgramBinary(program,bufSize,length,binaryFormat,binary);
-#else
- mGlExtensions.GetProgramBinaryOES(program, bufSize, length, binaryFormat, binary);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length)
- {
-#if DALI_GLES_VERSION >= 30
- // if OpenGL ES 2.0 compatibility is need this can be implemented with
- // glProgramBinaryOES
- glProgramBinary(program,binaryFormat,binary,length);
-#else
- mGlExtensions.ProgramBinaryOES(program, binaryFormat, binary, length);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void ProgramParameteri(GLuint program, GLenum pname, GLint value)
- {
-#if DALI_GLES_VERSION >= 30
- glProgramParameteri(program,pname,value);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments)
- {
-#if DALI_GLES_VERSION >= 30
- glInvalidateFramebuffer(target,numAttachments,attachments);
-#else
- mGlExtensions.DiscardFrameBuffer(target, numAttachments, attachments);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height)
- {
-#if DALI_GLES_VERSION >= 30
- glInvalidateSubFramebuffer(target,numAttachments,attachments,x,y,width,height);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
- {
-#if DALI_GLES_VERSION >= 30
- glTexStorage2D(target,levels,internalformat,width,height);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
- {
-#if DALI_GLES_VERSION >= 30
- glTexStorage3D(target,levels,internalformat,width,height,depth);
-#endif // DALI_GLES_VERSION >= 30
- }
-
- void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params)
- {
-#if DALI_GLES_VERSION >= 30
- glGetInternalformativ(target,internalformat,pname,bufSize,params);
-#endif // DALI_GLES_VERSION >= 30
- }
-
-private:
- ECoreX::GlExtensions mGlExtensions;
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_GL_IMPLEMENTATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "gl-proxy-implementation.h"
-
-// EXTERNAL INCLUDES
-#include <math.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <base/environment-options.h>
-
-namespace
-{
-const int NUM_FRAMES_PER_SECOND( 60 );
-}
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-Sampler::Sampler( const char* description )
-: mDescription( description ),
- mAccumulatedSquare( 0 ),
- mAccumulated( 0 ),
- mNumSamples( 0 ),
- mMin( 0.0f ),
- mMax( 0.0f ),
- mCurrentFrameCount( 0 )
-{
-}
-
-void Sampler::Increment()
-{
- mCurrentFrameCount++;
-}
-
-void Sampler::Reset()
-{
- mAccumulatedSquare = 0;
- mAccumulated = 0;
- mNumSamples = 0;
- mMin = 0.0f;
- mMax = 0.0f;
- mCurrentFrameCount = 0;
-}
-
-void Sampler::Accumulate()
-{
- if( mNumSamples == 0 )
- {
- mMin = mCurrentFrameCount;
- mMax = mCurrentFrameCount;
- }
- else
- {
- if( mCurrentFrameCount < mMin )
- {
- mMin = mCurrentFrameCount;
- }
- if( mCurrentFrameCount > mMax )
- {
- mMax = mCurrentFrameCount;
- }
- }
-
- mNumSamples++;
-
- mAccumulated += mCurrentFrameCount;
- mAccumulatedSquare += ( mCurrentFrameCount * mCurrentFrameCount );
- mCurrentFrameCount = 0;
-}
-const char* Sampler::GetDescription() const
-{
- return mDescription;
-}
-
-float Sampler::GetMeanValue() const
-{
- float meanValue = 0;
- if( mNumSamples > 0 )
- {
- meanValue = static_cast<double>( mAccumulated ) / static_cast<double>( mNumSamples );
- }
- return meanValue;
-}
-
-float Sampler::GetStandardDeviation() const
-{
- float standardDeviation = 0.0f;
- if( mNumSamples > 0 )
- {
- standardDeviation = sqrtf( mNumSamples * mAccumulatedSquare - ( mAccumulated * mAccumulated ) ) / mNumSamples;
- }
- return standardDeviation;
-}
-
-float Sampler::GetMin() const
-{
- return mMin;
-}
-
-float Sampler::GetMax() const
-{
- return mMax;
-}
-
-uint64_t Sampler::GetCount() const
-{
- return mAccumulated;
-}
-
-ObjectCounter::ObjectCounter( const char* description )
-: mDescription( description ),
- mCount( 0 ),
- mPeak( 0 )
-{}
-
-void ObjectCounter::Increment()
-{
- ++mCount;
- if( mCount > mPeak )
- {
- mPeak = mCount;
- }
-}
-
-void ObjectCounter::Decrement()
-{
- --mCount;
-}
-
-unsigned int ObjectCounter::GetCount() const
-{
- return mCount;
-}
-unsigned int ObjectCounter::GetPeak() const
-{
- return mPeak;
-}
-
-const char* ObjectCounter::GetDescription() const
-{
- return mDescription;
-}
-
-GlProxyImplementation::GlProxyImplementation( EnvironmentOptions& environmentOptions )
-: mEnvironmentOptions( environmentOptions ),
- mActiveTextureSampler( "ActiveTexture calls" ),
- mClearSampler( "Clear calls" ),
- mBindBufferSampler( "Bind buffers" ),
- mBindTextureSampler( "Bind textures" ),
- mDrawSampler( "Draw calls" ),
- mUniformSampler( "Uniform sets" ),
- mUseProgramSampler( "Used programs" ),
- mBufferCount( "Buffer Count" ),
- mTextureCount( "Texture Count" ),
- mProgramCount( "Program Count" ),
- mCurrentFrameCount( 0 ),
- mTotalFrameCount( 0 )
-{
-}
-
-GlProxyImplementation::~GlProxyImplementation()
-{
-}
-
-void GlProxyImplementation::PreRender()
-{
-}
-
-void GlProxyImplementation::PostRender()
-{
- // Accumulate counts in each sampler
- AccumulateSamples();
-
- // When we reach the desired frame count, output the averages from the samples
- mTotalFrameCount++;
- mCurrentFrameCount++;
-
- if( mCurrentFrameCount >= mEnvironmentOptions.GetGlesCallTime() * NUM_FRAMES_PER_SECOND )
- {
- mCurrentFrameCount = 0;
- LogResults();
-
- if( !mEnvironmentOptions.GetGlesCallAccumulate() )
- {
- ResetSamplers();
- }
- }
-}
-
-void GlProxyImplementation::Clear( GLbitfield mask )
-{
- mClearSampler.Increment();
- GlImplementation::Clear(mask);
-}
-
-void GlProxyImplementation::GenBuffers(GLsizei n, GLuint* buffers)
-{
- mBufferCount.Increment();
- GlImplementation::GenBuffers( n, buffers );
-}
-
-void GlProxyImplementation::DeleteBuffers( GLsizei n, const GLuint* buffers )
-{
- mBufferCount.Decrement();
- GlImplementation::DeleteBuffers( n, buffers );
-}
-
-void GlProxyImplementation::BindBuffer( GLenum target, GLuint buffer )
-{
- mBindBufferSampler.Increment();
- GlImplementation::BindBuffer( target, buffer );
-}
-
-void GlProxyImplementation::GenTextures( GLsizei n, GLuint* textures )
-{
- mTextureCount.Increment();
- GlImplementation::GenTextures( n, textures );
-}
-
-void GlProxyImplementation::DeleteTextures( GLsizei n, const GLuint* textures )
-{
- mTextureCount.Decrement();
- GlImplementation::DeleteTextures( n, textures );
-}
-
-void GlProxyImplementation::ActiveTexture( GLenum texture )
-{
- mActiveTextureSampler.Increment();
- GlImplementation::ActiveTexture( texture );
-}
-
-void GlProxyImplementation::BindTexture( GLenum target, GLuint texture )
-{
- mBindTextureSampler.Increment();
- GlImplementation::BindTexture(target,texture);
-}
-
-void GlProxyImplementation::DrawArrays( GLenum mode, GLint first, GLsizei count )
-{
- mDrawSampler.Increment();
- GlImplementation::DrawArrays( mode, first, count );
-}
-
-void GlProxyImplementation::DrawElements( GLenum mode, GLsizei count, GLenum type, const void* indices )
-{
- mDrawSampler.Increment();
- GlImplementation::DrawElements( mode, count, type, indices );
-}
-
-void GlProxyImplementation::Uniform1f( GLint location, GLfloat x )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform1f( location, x );
-}
-
-void GlProxyImplementation::Uniform1fv( GLint location, GLsizei count, const GLfloat* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform1fv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform1i( GLint location, GLint x )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform1i( location, x );
-}
-
-void GlProxyImplementation::Uniform1iv( GLint location, GLsizei count, const GLint* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform1iv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform2f( GLint location, GLfloat x, GLfloat y)
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform2f( location, x, y );
-}
-
-void GlProxyImplementation::Uniform2fv( GLint location, GLsizei count, const GLfloat* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform2fv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform2i( GLint location, GLint x, GLint y )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform2i( location, x, y );
-}
-
-void GlProxyImplementation::Uniform2iv( GLint location, GLsizei count, const GLint* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform2iv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform3f( GLint location, GLfloat x, GLfloat y, GLfloat z )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform3f( location, x, y, z );
-}
-
-void GlProxyImplementation::Uniform3fv( GLint location, GLsizei count, const GLfloat* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform3fv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform3i( GLint location, GLint x, GLint y, GLint z )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform3i( location, x, y, z );
-}
-
-void GlProxyImplementation::Uniform3iv( GLint location, GLsizei count, const GLint* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform3iv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform4f( GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform4f( location, x, y, z, w );
-}
-
-void GlProxyImplementation::Uniform4fv( GLint location, GLsizei count, const GLfloat* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform4fv( location, count, v );
-}
-
-void GlProxyImplementation::Uniform4i( GLint location, GLint x, GLint y, GLint z, GLint w )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform4i( location, x, y, z, w );
-}
-
-void GlProxyImplementation::Uniform4iv( GLint location, GLsizei count, const GLint* v )
-{
- mUniformSampler.Increment();
- GlImplementation::Uniform4iv( location, count, v );
-}
-
-void GlProxyImplementation::UniformMatrix2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
-{
- mUniformSampler.Increment();
- GlImplementation::UniformMatrix2fv( location, count, transpose, value );
-}
-
-void GlProxyImplementation::UniformMatrix3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
-{
- mUniformSampler.Increment();
- GlImplementation::UniformMatrix3fv( location, count, transpose, value );
-}
-
-void GlProxyImplementation::UniformMatrix4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
-{
- mUniformSampler.Increment();
- GlImplementation::UniformMatrix4fv( location, count, transpose, value);
-}
-
-GLuint GlProxyImplementation::CreateProgram( void )
-{
- mProgramCount.Increment();
- return GlImplementation::CreateProgram();
-}
-
-void GlProxyImplementation::DeleteProgram( GLuint program )
-{
- mProgramCount.Decrement();
- GlImplementation::DeleteProgram( program );
-}
-
-void GlProxyImplementation::UseProgram( GLuint program )
-{
- mUseProgramSampler.Increment();
- GlImplementation::UseProgram( program );
-}
-
-void GlProxyImplementation::AccumulateSamples()
-{
- // Accumulate counts in each sampler
- mActiveTextureSampler.Accumulate();
- mClearSampler.Accumulate();
- mBindBufferSampler.Accumulate();
- mBindTextureSampler.Accumulate();
- mDrawSampler.Accumulate();
- mUniformSampler.Accumulate();
- mUseProgramSampler.Accumulate();
-}
-
-void GlProxyImplementation::LogResults()
-{
- Debug::LogMessage( Debug::DebugInfo, "OpenGL ES statistics sampled over %d frames) operations per frame:\n", mTotalFrameCount );
- LogCalls( mActiveTextureSampler );
- LogCalls( mClearSampler );
- LogCalls( mBindBufferSampler );
- LogCalls( mBindTextureSampler );
- LogCalls( mDrawSampler );
- LogCalls( mUniformSampler );
- LogCalls( mUseProgramSampler );
- Debug::LogMessage( Debug::DebugInfo, "OpenGL ES Object Count:\n" );
- LogObjectCounter( mBufferCount );
- LogObjectCounter( mTextureCount );
- LogObjectCounter( mProgramCount );
-}
-
-void GlProxyImplementation::LogCalls( const Sampler& sampler )
-{
- Debug::LogMessage( Debug::DebugInfo, " %s : Mean %5.2f (Min:%5.2f, Max:%5.2f, StdDev:%5.2f, Actual:%d)\n",
- sampler.GetDescription(),
- sampler.GetMeanValue(), sampler.GetMin(), sampler.GetMax(),
- sampler.GetStandardDeviation(),
- sampler.GetCount() );
-}
-
-void GlProxyImplementation::LogObjectCounter( const ObjectCounter& sampler )
-{
- Debug::LogMessage( Debug::DebugInfo, " %s : %u (Peak:%u)\n",
- sampler.GetDescription(),
- sampler.GetCount(),
- sampler.GetPeak() );
-}
-
-void GlProxyImplementation::ResetSamplers()
-{
- mActiveTextureSampler.Reset();
- mClearSampler.Reset();
- mBindBufferSampler.Reset();
- mBindTextureSampler.Reset();
- mDrawSampler.Reset();
- mUniformSampler.Reset();
- mUseProgramSampler.Reset();
- mTotalFrameCount = 0;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
-#define __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <gl/gl-implementation.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-class EnvironmentOptions;
-
-/**
- * Helper class to calculate the statistics for Open GLES calls
- */
-class Sampler
-{
-public:
-
- /**
- * Constructor
- * @param description to write to the log
- */
- Sampler( const char* description );
-
- /**
- * Increment the counter for this frame
- */
- void Increment();
-
- /**
- * Reset the counter
- */
- void Reset();
-
- /**
- * Accumulate the count onto statistics
- */
- void Accumulate();
-
- /**
- * @return the description of the sampler
- */
- const char* GetDescription() const;
-
- /**
- * @return the mean value
- */
- float GetMeanValue() const;
-
- /**
- * @return the standard deviation
- */
- float GetStandardDeviation() const;
-
- /**
- * @return the minimum value
- */
- float GetMin() const;
-
- /**
- * @return the maximum value
- */
- float GetMax() const;
-
- /**
- * @return the current count
- */
- uint64_t GetCount() const;
-
-private: // Data
-
- const char* mDescription;
-
- uint64_t mAccumulatedSquare;
- uint64_t mAccumulated;
- uint64_t mNumSamples;
- float mMin;
- float mMax;
- unsigned int mCurrentFrameCount;
-};
-
-/**
- * Helper class to calculate number of OpenGL objects
- */
-class ObjectCounter
-{
-public:
- ObjectCounter( const char* description );
-
- /**
- * Increment the counter
- */
- void Increment();
-
- /**
- * Decrement the counter
- */
- void Decrement();
-
- /**
- * @return The current number of objects
- */
- unsigned int GetCount() const;
-
- /**
- * @return The maximum number of objects created
- */
- unsigned int GetPeak() const;
-
- /**
- * @return the description of the sampler
- */
- const char* GetDescription() const;
-
-private:
- const char* mDescription;
- unsigned int mCount;
- unsigned int mPeak;
-};
-
-/**
- * GlProxyImplementation is a wrapper for the concrete implementation
- * of GlAbstraction that also gathers statistical information.
- */
-class GlProxyImplementation : public GlImplementation
-{
-public:
-
- /**
- * Constructor
- * @param environmentOptions to check how often to log results
- */
- GlProxyImplementation( EnvironmentOptions& environmentOptions );
-
- /**
- * Virtual destructor
- */
- virtual ~GlProxyImplementation();
-
- /**
- * @copydoc GlAbstraction::PreRender();
- */
- virtual void PreRender();
-
- /**
- * @copydoc GlAbstraction::PostRender();
- */
- virtual void PostRender();
-
- /* OpenGL ES 2.0 API */
- virtual void Clear( GLbitfield mask );
-
- virtual void GenBuffers( GLsizei n, GLuint* buffers );
- virtual void DeleteBuffers( GLsizei n, const GLuint* buffers );
- virtual void BindBuffer( GLenum target, GLuint buffer );
-
- virtual void GenTextures( GLsizei n, GLuint* textures );
- virtual void DeleteTextures( GLsizei n, const GLuint* textures );
- virtual void ActiveTexture( GLenum texture );
- virtual void BindTexture( GLenum target, GLuint texture );
-
- virtual void DrawArrays( GLenum mode, GLint first, GLsizei count );
- virtual void DrawElements( GLenum mode, GLsizei count, GLenum type, const void* indices );
-
- virtual void Uniform1f ( GLint location, GLfloat x );
- virtual void Uniform1fv( GLint location, GLsizei count, const GLfloat* v );
- virtual void Uniform1i ( GLint location, GLint x );
- virtual void Uniform1iv( GLint location, GLsizei count, const GLint* v );
- virtual void Uniform2f ( GLint location, GLfloat x, GLfloat y );
- virtual void Uniform2fv( GLint location, GLsizei count, const GLfloat* v );
- virtual void Uniform2i ( GLint location, GLint x, GLint y );
- virtual void Uniform2iv( GLint location, GLsizei count, const GLint* v );
- virtual void Uniform3f ( GLint location, GLfloat x, GLfloat y, GLfloat z );
- virtual void Uniform3fv( GLint location, GLsizei count, const GLfloat* v );
- virtual void Uniform3i ( GLint location, GLint x, GLint y, GLint z );
- virtual void Uniform3iv( GLint location, GLsizei count, const GLint* v );
- virtual void Uniform4f ( GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w );
- virtual void Uniform4fv( GLint location, GLsizei count, const GLfloat* v );
- virtual void Uniform4i ( GLint location, GLint x, GLint y, GLint z, GLint w );
- virtual void Uniform4iv( GLint location, GLsizei count, const GLint* v );
- virtual void UniformMatrix2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
- virtual void UniformMatrix3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
- virtual void UniformMatrix4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
-
- virtual GLuint CreateProgram( void );
- virtual void DeleteProgram( GLuint program );
- virtual void UseProgram( GLuint program );
-
-private: // Helpers
-
- void AccumulateSamples();
- void LogResults();
- void LogCalls( const Sampler& sampler );
- void LogObjectCounter( const ObjectCounter& sampler );
- void ResetSamplers();
-
-private: // Data
-
- EnvironmentOptions& mEnvironmentOptions;
- Sampler mActiveTextureSampler;
- Sampler mClearSampler;
- Sampler mBindBufferSampler;
- Sampler mBindTextureSampler;
- Sampler mDrawSampler;
- Sampler mUniformSampler;
- Sampler mUseProgramSampler;
- ObjectCounter mBufferCount;
- ObjectCounter mTextureCount;
- ObjectCounter mProgramCount;
-
- int mCurrentFrameCount;
- int mTotalFrameCount;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "indicator-buffer.h"
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-IndicatorBuffer::IndicatorBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat )
-: mAdaptor(adaptor),
- mImageWidth(width),
- mImageHeight(height),
- mPixelFormat(pixelFormat)
-{
- DALI_ASSERT_ALWAYS( adaptor );
-
- // Use BitmapImage when SharedGlBuffer extension is unavailable
- mBitmapBuffer = new NativeBitmapBuffer( adaptor, mImageWidth, mImageHeight, mPixelFormat );
- mNativeImage = mBitmapBuffer;
-}
-
-bool IndicatorBuffer::UpdatePixels( const unsigned char *src, size_t size )
-{
- // Use double buffered bitmap when SharedGlBuffer extension is unavailable
- mBitmapBuffer->Write( src, size );
- return true;
-}
-
-NativeImageInterface& IndicatorBuffer::GetNativeImage() const
-{
- DALI_ASSERT_DEBUG(mNativeImage.Get());
- return *mNativeImage;
-}
-
-void IndicatorBuffer::SetAdaptor( Adaptor* adaptor )
-{
- mAdaptor = adaptor;
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_INDICATOR_BUFFER_H__
-#define __DALI_INTERNAL_INDICATOR_BUFFER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/ref-object.h>
-
-// INTERNAL INCLUDES
-#include <native-bitmap-buffer-impl.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-namespace Adaptor
-{
-
-class NativeBitmapBuffer;
-class IndicatorBuffer;
-
-typedef IntrusivePtr<IndicatorBuffer> IndicatorBufferPtr;
-
-/**
- * The IndicatorBuffer class uses the best available implementation for rendering indicator data.
- * On platforms where EglImage is available it uses either SharedGlBuffer or NativeImageSource, on older
- * platforms it falls back to using a bitmap buffer based solution.
- */
-class IndicatorBuffer : public RefObject
-{
-public:
-
- /**
- * Constructor
- */
- IndicatorBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat );
-
- /**
- * Copy bitmap data to pixel buffer.
- * @param src bitmap data source
- * @param size size of bitmap data
- * @return true if successful, false otherwise
- */
- bool UpdatePixels( const unsigned char *src, size_t size );
-
- /**
- * Returns the NativeImage used internally
- * @return the NativeImage used internally
- */
- NativeImageInterface& GetNativeImage() const;
-
- /**
- * Set currently used Adaptor
- * @param adaptor
- */
- void SetAdaptor( Adaptor* adaptor );
-
-private:
- NativeImageInterfacePtr mNativeImage; ///< Image buffer created for shared file copy
-
- NativeBitmapBufferPtr mBitmapBuffer; ///< Image buffer created for shared file copy if extension not available
-
- Adaptor* mAdaptor;
-
- int mImageWidth;
- int mImageHeight;
- Pixel::Format mPixelFormat;
-};
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif // __DALI_INTERNAL_INDICATOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "kernel-trace.h"
-
-// EXTERNAL HEADERS
-#include <fcntl.h>
-#include <stdio.h>
-#include <unistd.h>
-
-// INTERNAL HEADERS
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const char* TRACE_MARKER_FILE = "/sys/kernel/debug/tracing/trace_marker";
-const char* SPI_PREFIX = "SPI_EV_DALI_"; ///< prefix to let the SPI tool know it should read the trace
-}// un-named name space
-
-KernelTrace::KernelTrace()
-: mFileDescriptor( 0 ),
- mLoggedError( false )
-{
-}
-
-KernelTrace::~KernelTrace()
-{
- if( mFileDescriptor )
- {
- close( mFileDescriptor );
- }
-}
-
-// If this function doesn't appear to work, you can test manually on the device.
-// $ cd /sys/kernel/debug/tracing
-//
-// If the folder doesn't exist then the kernel needs to be re-built with ftrace enabled
-// If it does exist, then you can continue to test ftrace is working:
-//
-// $ echo 1 > tracing_enabled
-// $ echo "test" > trace_marker
-// $ cat trace
-// should print out test message
-// If the message did not get added to the trace, then check you have write permissions to the trace_marker file.
-//
-//
-void KernelTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage )
-{
- // Open the trace_marker file
- if( mFileDescriptor == 0 )
- {
- mFileDescriptor = open( TRACE_MARKER_FILE , O_WRONLY);
- if( mFileDescriptor == -1 )
- {
- // we want to keep trying to open it, so it will start working if someone fixes
- // the permissions on the trace marker
- mFileDescriptor = 0;
-
- // first time we fail to open the file, log an error
- if( !mLoggedError )
- {
- mLoggedError = true;
- DALI_LOG_ERROR("Failed to open /sys/kernel/debug/tracing/trace_marker for writing please check file permissions.\n");
- }
-
- }
- }
-
- if( mFileDescriptor > 0 )
- {
- std::string msg( SPI_PREFIX );
- msg+=traceMessage;
-
- int ret = write( mFileDescriptor, msg.c_str(), msg.length() );
- // if it failed then close the file description and try again next time we trace
- if( ret < 0 )
- {
- close( mFileDescriptor );
- mFileDescriptor = 0;
- }
- }
-}
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
-#define __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <base/interfaces/trace-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Concrete Kernel Tracing Interface.
- * Used to log trace messages to the kernel using ftrace.
- *
- */
-class KernelTrace : public TraceInterface
-{
-public:
-
- /**
- * Constructor
- */
- KernelTrace();
-
- /**
- * Destructor
- */
- virtual ~KernelTrace();
-
- /**
- * @copydoc KernelTracerInterface::KernelTrace()
- */
- virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage );
-
-private:
-
- int mFileDescriptor;
- bool mLoggedError:1;
-
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "key-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dlfcn.h>
-#include <map>
-#include <string.h>
-#include <iostream>
-
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gKeyExtensionLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEY_EXTENSION");
-#endif
-
-// Path for loading extension keys
-#if _GLIBCXX_USE_CXX11_ABI
-const char* KEY_EXTENSION_PLUGIN_SO( "libdali-key-extension.so" );
-#else
-const char* KEY_EXTENSION_PLUGIN_SO( "libdali-key-extension-cxx03.so" );
-#endif
-
-class KeyMap
-{
- public:
-
- KeyMap():
- mExtensionKeyLookupTable(NULL),
- mPlugin(NULL),
- mHandle(NULL),
- mCreateKeyExtensionPluginPtr(NULL),
- mDestroyKeyExtensionPluginPtr(NULL),
- mLookup( cmpString ),
- mExtensionLookup( cmpString ),
- mExtensionLookupCount(0),
- mIsLookupTableInitialized( false ),
- mIsExtensionLookupTableInitialized( false )
- {
- }
-
- ~KeyMap()
- {
- if( mHandle != NULL )
- {
- if( mDestroyKeyExtensionPluginPtr != NULL )
- {
- mDestroyKeyExtensionPluginPtr( mPlugin );
- }
-
- dlclose( mHandle );
- }
- }
-
- int GetDaliKeyEnum( const char* keyName )
- {
- // If lookup table is not initialized, initialize lookup table
- if( !mIsLookupTableInitialized )
- {
- InitializeLookupTable();
- }
-
- Lookup::const_iterator i = mLookup.find( keyName );
-
- if( i == mLookup.end() )
- {
- // If cannot find target, find it at the extension
- // If extension lookup table is not initialized, initialize extension lookup table
- if( !mIsExtensionLookupTableInitialized )
- {
- InitializeExtensionLookupTable();
- }
-
- // Find at extension
- i = mExtensionLookup.find( keyName );
-
- if( i == mExtensionLookup.end() )
- {
- return -1;
- }
- else
- {
- return (*i).second.first;
- }
- }
- else
- {
- return (*i).second.first;
- }
- }
-
- const char* GetKeyName( int daliKeyCode )
- {
- // If lookup table is not initialized, initialize lookup table
- if( !mIsLookupTableInitialized )
- {
- InitializeLookupTable();
- }
-
- for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i )
- {
- if( KeyLookupTable[i].daliKeyCode == daliKeyCode )
- {
- return KeyLookupTable[i].keyName;
- }
- }
-
- // If extension lookup table is not initialized, initialize extension lookup table
- if( !mIsExtensionLookupTableInitialized )
- {
- InitializeExtensionLookupTable();
- }
-
- for( size_t i = 0; i < mExtensionLookupCount ; ++i )
- {
- if( mExtensionKeyLookupTable[i].daliKeyCode == daliKeyCode )
- {
- return mExtensionKeyLookupTable[i].keyName;
- }
- }
-
- return NULL;
- }
-
- bool IsDeviceButton( const char* keyName )
- {
- // If lookup table is not initialized, initialize lookup table
- if( !mIsLookupTableInitialized )
- {
- InitializeLookupTable();
- }
-
- Lookup::const_iterator i = mLookup.find( keyName );
- if( i == mLookup.end() )
- {
- // If cannot find target, find it at the extension.
- // If extension lookup table is not initialized, initialize extension lookup table
- if( !mIsExtensionLookupTableInitialized )
- {
- InitializeExtensionLookupTable();
- }
-
- // Find at extension
- i = mExtensionLookup.find( keyName );
-
- if( i == mExtensionLookup.end() )
- {
- return false;
- }
- else
- {
- return (*i).second.second;
- }
- }
- else
- {
- return (*i).second.second;
- }
-
- return false;
- }
-
-
- private:
-
- void InitializeLookupTable()
- {
- // create the lookup
- for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i )
- {
- mLookup[ KeyLookupTable[i].keyName ] = DaliKeyType( KeyLookupTable[i].daliKeyCode, KeyLookupTable[i].deviceButton );
- }
-
- mIsLookupTableInitialized = true;
- }
-
- void InitializeExtensionLookupTable()
- {
- // Try to load extension keys
- char* error = NULL;
- mHandle = dlopen( KEY_EXTENSION_PLUGIN_SO, RTLD_NOW );
- error = dlerror();
-
- if( mHandle == NULL )
- {
- DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get handle from libdali-key-extension.so\n" );
- return;
- }
-
- if( error != NULL )
- {
- DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "dlopen got error: %s \n", error );
- return;
- }
-
- mCreateKeyExtensionPluginPtr = reinterpret_cast< CreateKeyExtensionPluginFunction >( dlsym( mHandle, "CreateKeyExtensionPlugin" ) );
- if( mCreateKeyExtensionPluginPtr == NULL )
- {
- DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get CreateKeyExtensionPlugin function\n" );
- return;
- }
-
- mPlugin = mCreateKeyExtensionPluginPtr();
- if( mPlugin == NULL )
- {
- DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to create plugin object\n" );
- return;
- }
-
- mDestroyKeyExtensionPluginPtr = reinterpret_cast< DestroyKeyExtensionPluginFunction >( dlsym( mHandle, "DestroyKeyExtensionPlugin" ) );
- if( mDestroyKeyExtensionPluginPtr == NULL )
- {
- DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get DestroyKeyExtensionPlugin function\n" );
- return;
- }
-
- mExtensionKeyLookupTable = mPlugin->GetKeyLookupTable();
- mExtensionLookupCount = mPlugin->GetKeyLookupTableCount();
-
- // Add extension keys to lookup
- for( size_t i = 0; i < mExtensionLookupCount ; ++i )
- {
- mExtensionLookup[ mExtensionKeyLookupTable[i].keyName ] = DaliKeyType( mExtensionKeyLookupTable[i].daliKeyCode, mExtensionKeyLookupTable[i].deviceButton );
- }
-
- mIsExtensionLookupTableInitialized = true;
- }
-
- /**
- * compare function, to compare string by pointer
- */
- static bool cmpString( const char* a, const char* b)
- {
- return strcmp(a, b) < 0;
- }
-
- KeyExtensionPlugin::KeyLookup* mExtensionKeyLookupTable; ///< Lookup table for extension keys
- Dali::KeyExtensionPlugin* mPlugin; ///< Key extension plugin handle
- void* mHandle; ///< Handle for the loaded library
- typedef Dali::KeyExtensionPlugin* (*CreateKeyExtensionPluginFunction)(); ///< Type of function pointer to get KeyExtensionPlugin object
- typedef void (*DestroyKeyExtensionPluginFunction)( Dali::KeyExtensionPlugin* plugin ); ///< Type of function pointer to delete KeyExtensionPlugin object
- CreateKeyExtensionPluginFunction mCreateKeyExtensionPluginPtr; ///< Function pointer to get KeyExtensionPlugin object
- DestroyKeyExtensionPluginFunction mDestroyKeyExtensionPluginPtr; ///< Function pointer to delete KeyExtensionPlugin object
-
- typedef std::pair< int, bool > DaliKeyType;
- typedef std::map<const char* /* key name */, DaliKeyType /* key code */, bool(*) ( char const* a, char const* b) > Lookup;
- Lookup mLookup;
- Lookup mExtensionLookup;
- size_t mExtensionLookupCount; ///< count of extension lookup table
- bool mIsLookupTableInitialized; ///< flag for basic lookup table initialization
- bool mIsExtensionLookupTableInitialized; ///< flag for extension lookup table initialization
-};
-KeyMap globalKeyLookup;
-
-} // un-named name space
-
-bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey)
-{
- int key = globalKeyLookup.GetDaliKeyEnum( keyEvent.keyPressedName.c_str() );
- return daliKey == key;
-}
-
-bool IsDeviceButton( const char* keyName )
-{
- return globalKeyLookup.IsDeviceButton( keyName );
-}
-
-const char* GetKeyName( Dali::KEY daliKey )
-{
- return globalKeyLookup.GetKeyName( daliKey );
-}
-
-int GetDaliKeyCode( const char* keyName )
-{
- return globalKeyLookup.GetDaliKeyEnum( keyName );
-}
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_KEY_IMPL_H__
-#define __DALI_KEY_IMPL_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <key.h>
-#include <key-extension-plugin.h>
-#include <key-devel.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Implementation of the Key matching
- */
-namespace KeyLookup
-{
-
-struct KeyLookup
-{
- const char* keyName; ///< XF86 key name
- const Dali::KEY daliKeyCode; ///< Dali key code
- const bool deviceButton; ///< Whether the key is from a button on the device
-};
-
-extern KeyLookup KeyLookupTable[];
-extern const std::size_t KEY_LOOKUP_COUNT;
-
-/**
- * @copydoc Dali::IsKey()
- */
-bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey );
-
-/**
- * Check if a the given key name string is a button on the device itself.
- * @param keyName A pointer to the key name
- * @return true if the key is matched, false if not
- */
-bool IsDeviceButton( const char* keyName );
-
-/**
- * Get a key name from a dali key code.
- * @param daliKey The dali key code
- * @return The key name. NULL if the daliKey does not exist in the supported key lookup table.
- */
-const char* GetKeyName( Dali::KEY daliKey );
-
-/**
- * @brief Get the key code from a key name.
- * @param[in] keyName The key name
- * @return The key code. -1 if the daliKey does not exist in the supported key lookup table.
- */
-int GetDaliKeyCode( const char* keyName );
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_KEY_IMPL_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "lifecycle-controller-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::LifecycleController LifecycleController::Get()
-{
- Dali::LifecycleController lifecycleController;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::LifecycleController ) );
- if(handle)
- {
- // If so, downcast the handle
- lifecycleController = Dali::LifecycleController( dynamic_cast< LifecycleController* >( handle.GetObjectPtr() ) );
- }
- else
- {
- lifecycleController = Dali::LifecycleController( new LifecycleController() );
- service.Register( typeid( lifecycleController ), lifecycleController );
- }
- }
-
- return lifecycleController;
-}
-
-LifecycleController::LifecycleController()
-{
-}
-
-LifecycleController::~LifecycleController()
-{
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::InitSignal()
-{
- return mInitSignal;
-}
-
-void LifecycleController::EmitInitSignal()
-{
- if( !mInitSignal.Empty() )
- {
- mInitSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::TerminateSignal()
-{
- return mTerminateSignal;
-}
-
-void LifecycleController::EmitTerminateSignal()
-{
- if( !mTerminateSignal.Empty() )
- {
- mTerminateSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::PauseSignal()
-{
- return mPauseSignal;
-}
-
-void LifecycleController::EmitPauseSignal()
-{
- if( !mPauseSignal.Empty() )
- {
- mPauseSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResumeSignal()
-{
- return mResumeSignal;
-}
-
-void LifecycleController::EmitResumeSignal()
-{
- if( !mResumeSignal.Empty() )
- {
- mResumeSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResetSignal()
-{
- return mResetSignal;
-}
-
-void LifecycleController::EmitResetSignal()
-{
- if( !mResetSignal.Empty() )
- {
- mResetSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResizeSignal()
-{
- return mResizeSignal;
-}
-
-void LifecycleController::EmitResizeSignal()
-{
- if( !mResizeSignal.Empty() )
- {
- mResizeSignal.Emit();
- }
-}
-
-Dali::LifecycleController::LifecycleSignalType& LifecycleController::LanguageChangedSignal()
-{
- return mLanguageChangedSignal;
-}
-
-void LifecycleController::EmitLanguageChangedSignal()
-{
- if( !mLanguageChangedSignal.Empty() )
- {
- mLanguageChangedSignal.Emit();
- }
-}
-
-void LifecycleController::OnInit( Dali::Application& app )
-{
- EmitInitSignal();
-}
-
-void LifecycleController::OnTerminate( Dali::Application& app )
-{
- EmitTerminateSignal();
-}
-
-void LifecycleController::OnPause( Dali::Application& app )
-{
- EmitPauseSignal();
-}
-
-void LifecycleController::OnResume( Dali::Application& app )
-{
- EmitResumeSignal();
-}
-
-void LifecycleController::OnReset( Dali::Application& app )
-{
- EmitResetSignal();
-}
-
-void LifecycleController::OnLanguageChanged( Dali::Application& app )
-{
- EmitLanguageChangedSignal();
-}
-
-void LifecycleController::OnResize( Dali::Application& app )
-{
- EmitResizeSignal();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
-#define __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <lifecycle-controller.h>
-#include <application.h>
-
-namespace Dali
-{
-
-class Adaptor;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * This provides signals that are emitted according the lifecylce of the program.
- */
-class LifecycleController : public BaseObject, public ConnectionTracker
-{
-public:
-
- // Creation & Destruction
-
- /**
- * Constructor.
- */
- LifecycleController();
-
- /**
- * Retrieve the initialized instance of the LifecycleController.
- * @return Handle to LifecycleController.
- */
- static Dali::LifecycleController Get();
-
- // Signals
-
- /**
- * @copydoc Dali::StyleMonitor::InitSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& InitSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::TerminateSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& TerminateSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::PauseSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& PauseSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::ResumeSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& ResumeSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::ResetSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& ResetSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::ResizeSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& ResizeSignal();
-
- /**
- * @copydoc Dali::StyleMonitor::LanguageChangedSignal()
- */
- Dali::LifecycleController::LifecycleSignalType& LanguageChangedSignal();
-
-public:
-
- /**
- * Called when the framework is initialised.
- *
- * @param[in] app The application instance
- */
- void OnInit( Dali::Application& app );
-
- /**
- * Called when the framework is terminated.
- *
- * @param[in] app The application instance
- */
- void OnTerminate( Dali::Application& app );
-
- /**
- * Called when the framework is paused.
- *
- * @param[in] app The application instance
- */
- void OnPause( Dali::Application& app );
-
- /**
- * Called when the framework resumes from a paused state.
- *
- * @param[in] app The application instance
- */
- void OnResume( Dali::Application& app );
-
- /**
- * Called when the framework informs the application that it should reset itself.
- *
- * @param[in] app The application instance
- */
- void OnReset( Dali::Application& app );
-
- /**
- * Called when the framework informs the application that the language of the device has changed.
- *
- * @param[in] app The application instance
- */
- void OnLanguageChanged( Dali::Application& app );
-
- /**
- * Signal handler when the adaptor's window resizes itself.
- *
- * @param[in] app The application instance
- */
- void OnResize( Dali::Application& app );
-
-protected:
-
- /**
- * Virtual Destructor.
- */
- virtual ~LifecycleController();
-
-private:
-
- /**
- * Emit the init signal.
- */
- void EmitInitSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitTerminateSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitPauseSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitResumeSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitResetSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitResizeSignal();
-
- /**
- * Emit the init signal.
- */
- void EmitLanguageChangedSignal();
-
-private:
-
- // Signals
- Dali::LifecycleController::LifecycleSignalType mInitSignal;
- Dali::LifecycleController::LifecycleSignalType mTerminateSignal;
- Dali::LifecycleController::LifecycleSignalType mPauseSignal;
- Dali::LifecycleController::LifecycleSignalType mResumeSignal;
- Dali::LifecycleController::LifecycleSignalType mResetSignal;
- Dali::LifecycleController::LifecycleSignalType mResizeSignal;
- Dali::LifecycleController::LifecycleSignalType mLanguageChangedSignal;
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Additional Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::LifecycleController& GetImplementation(Dali::LifecycleController& controller)
-{
- DALI_ASSERT_ALWAYS(controller && "Controller handle is empty");
- BaseObject& handle = controller.GetBaseObject();
- return static_cast<Internal::Adaptor::LifecycleController&>(handle);
-}
-
-inline const Internal::Adaptor::LifecycleController& GetImplementation(const Dali::LifecycleController& controller)
-{
- DALI_ASSERT_ALWAYS(controller && "Controller handle is empty");
- const BaseObject& handle = controller.GetBaseObject();
- return static_cast<const Internal::Adaptor::LifecycleController&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "locale-utils.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Locale
-{
-
-namespace
-{
-
-struct LocaleDirectionInfo
-{
- const char * locale;
- const char * name;
- Locale::Direction direction;
-};
-
-const LocaleDirectionInfo LOCALE_DIRECTION_LOOKUP_TABLE[] =
-{
- { "af", "Afrikaans", Locale::LeftToRight },
- { "am", "Amharic", Locale::LeftToRight },
- { "ar", "Arabic", Locale::RightToLeft },
- { "as", "Assamese", Locale::LeftToRight },
- { "az", "Azerbaijani", Locale::RightToLeft },
- { "be", "Belarusian", Locale::LeftToRight },
- { "bg", "Bulgarian", Locale::LeftToRight },
- { "bn", "Bengali", Locale::LeftToRight },
- { "bo", "Tibetan", Locale::LeftToRight },
- { "bs", "Bosnian", Locale::LeftToRight },
- { "ca", "Catalan", Locale::LeftToRight },
- { "cs", "Czech", Locale::LeftToRight },
- { "cy", "Welsh", Locale::LeftToRight },
- { "da", "Danish", Locale::LeftToRight },
- { "de", "German", Locale::LeftToRight },
- { "dv", "Divehi", Locale::RightToLeft },
- { "el", "Greek", Locale::LeftToRight },
- { "en", "English", Locale::LeftToRight },
- { "es", "Spanish", Locale::LeftToRight },
- { "et", "Estonian", Locale::LeftToRight },
- { "eu", "Basque", Locale::LeftToRight },
- { "fa", "Farsi", Locale::RightToLeft },
- { "fi", "Finnish", Locale::LeftToRight },
- { "fo", "Faroese", Locale::LeftToRight },
- { "fr", "French", Locale::LeftToRight },
- { "gd", "Gaelic", Locale::LeftToRight },
- { "gl", "Galician", Locale::LeftToRight },
- { "gn", "Guarani", Locale::LeftToRight },
- { "gu", "Gujarati", Locale::LeftToRight },
- { "he", "Hebrew", Locale::RightToLeft },
- { "hi", "Hindi", Locale::LeftToRight },
- { "hr", "Croatian", Locale::LeftToRight },
- { "hu", "Hungarian", Locale::LeftToRight },
- { "hy", "Armenian", Locale::LeftToRight },
- { "id", "Indonesian", Locale::LeftToRight },
- { "is", "Icelandic", Locale::LeftToRight },
- { "it", "Italian", Locale::LeftToRight },
- { "ja", "Japanese", Locale::LeftToRight },
- { "ka", "Georgian", Locale::LeftToRight },
- { "kk", "Kazakh", Locale::RightToLeft },
- { "km", "Khmer", Locale::LeftToRight },
- { "kn", "Kannada", Locale::LeftToRight },
- { "ko", "Korean", Locale::LeftToRight },
- { "ks", "Kashmiri", Locale::RightToLeft },
- { "la", "Latin", Locale::LeftToRight },
- { "lo", "Lao", Locale::LeftToRight },
- { "lt", "Lithuanian", Locale::LeftToRight },
- { "lv", "Latvian", Locale::LeftToRight },
- { "mi", "Maori", Locale::LeftToRight },
- { "mk", "FYRO Macedonia", Locale::LeftToRight },
- { "ml", "Malayalam", Locale::LeftToRight },
- { "mn", "Mongolian", Locale::LeftToRight },
- { "mr", "Marathi", Locale::LeftToRight },
- { "ms", "Malay", Locale::LeftToRight },
- { "mt", "Maltese", Locale::LeftToRight },
- { "my", "Burmese", Locale::LeftToRight },
- { "nb", "Norwegian: Bokml", Locale::LeftToRight },
- { "ne", "Nepali", Locale::LeftToRight },
- { "nl", "Dutch", Locale::LeftToRight },
- { "nn", "Norwegian: Nynorsk", Locale::LeftToRight },
- { "or", "Oriya", Locale::LeftToRight },
- { "pa", "Punjabi", Locale::LeftToRight },
- { "pl", "Polish", Locale::LeftToRight },
- { "pt", "Portuguese", Locale::LeftToRight },
- { "rm", "Raeto-Romance", Locale::LeftToRight },
- { "ro", "Romanian", Locale::LeftToRight },
- { "ru", "Russian", Locale::LeftToRight },
- { "sa", "Sanskrit", Locale::LeftToRight },
- { "sb", "Sorbian", Locale::LeftToRight },
- { "sd", "Sindhi", Locale::LeftToRight },
- { "si", "Sinhala", Locale::LeftToRight },
- { "sk", "Slovak", Locale::LeftToRight },
- { "sl", "Slovenian", Locale::LeftToRight },
- { "so", "Somali", Locale::LeftToRight },
- { "sq", "Albanian", Locale::LeftToRight },
- { "sr", "Serbian", Locale::LeftToRight },
- { "sv", "Swedish", Locale::LeftToRight },
- { "sw", "Swahili", Locale::LeftToRight },
- { "ta", "Tamil", Locale::LeftToRight },
- { "te", "Telugu", Locale::LeftToRight },
- { "tg", "Tajik", Locale::RightToLeft },
- { "th", "Thai", Locale::LeftToRight },
- { "tk", "Turkmen", Locale::LeftToRight },
- { "tn", "Setsuana", Locale::LeftToRight },
- { "tr", "Turkish", Locale::LeftToRight },
- { "ts", "Tsonga", Locale::LeftToRight },
- { "tt", "Tatar", Locale::LeftToRight },
- { "uk", "Ukrainian", Locale::LeftToRight },
- { "ur", "Urdu", Locale::RightToLeft },
- { "uz", "Uzbek", Locale::LeftToRight },
- { "vi", "Vietnamese", Locale::LeftToRight },
- { "xh", "Xhosa", Locale::LeftToRight },
- { "yi", "Yiddish", Locale::RightToLeft },
- { "zh", "Chinese", Locale::LeftToRight },
- { "zu", "Zulu", Locale::LeftToRight },
-
- { NULL, NULL, Locale::LeftToRight }
-};
-
-} // unnamed namespace
-
-Locale::Direction GetDirection( const std::string& locale )
-{
- Locale::Direction direction( Locale::LeftToRight );
-
- if ( !locale.empty() && locale.size() > 2 )
- {
- for ( const LocaleDirectionInfo* iter = &LOCALE_DIRECTION_LOOKUP_TABLE[0]; iter->locale; ++iter )
- {
- if ( !locale.compare( 0, 2, iter->locale ) )
- {
- direction = iter->direction;
- break;
- }
- }
- }
-
- return direction;
-}
-
-} // namespace Locale
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "native-bitmap-buffer-impl.h"
-
-// EXTERNAL HEADERS
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/bitmap.h>
-
-// INTERNAL HEADERS
-#include <common/gl/gl-implementation.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-NativeBitmapBuffer::NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pFormat )
-: mWidth(width),
- mHeight(height),
- mPixelFormat(pFormat),
- mLastReadBuffer(NULL)
-{
- DALI_ASSERT_ALWAYS( adaptor );
- mBuffer = new Integration::LocklessBuffer( width * height * Pixel::GetBytesPerPixel(pFormat) );
- mGlAbstraction = &(adaptor->GetGlAbstraction());
-}
-
-NativeBitmapBuffer::~NativeBitmapBuffer()
-{
- delete mBuffer;
-}
-
-void NativeBitmapBuffer::PrepareTexture()
-{
- DALI_ASSERT_ALWAYS( mBuffer );
- GLenum pixelFormat = GL_RGBA;
- GLenum pixelDataType = GL_UNSIGNED_BYTE;
-
- Integration::ConvertToGlFormat( mPixelFormat, pixelDataType, pixelFormat );
-
- const unsigned char* buf = mBuffer->Read();
-
- if( buf && buf != mLastReadBuffer ) // Prevent same buffer being uploaded multiple times
- {
- mLastReadBuffer = buf;
-
- // The active texture has already been set to a sampler and bound.
- mGlAbstraction->TexImage2D( GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, buf );
- }
-}
-
-void NativeBitmapBuffer::Write( const unsigned char *src, size_t size )
-{
- mBuffer->Write( src, size ); // Write will cause LocklessBuffer to switch to the other buffer
-}
-
-bool NativeBitmapBuffer::GlExtensionCreate()
-{
- return true;
-}
-
-void NativeBitmapBuffer::GlExtensionDestroy()
-{
-}
-
-unsigned int NativeBitmapBuffer::TargetTexture()
-{
- return 0;
-}
-
-unsigned int NativeBitmapBuffer::GetWidth() const
-{
- return mWidth;
-}
-
-unsigned int NativeBitmapBuffer::GetHeight() const
-{
- return mHeight;
-}
-
-bool NativeBitmapBuffer::RequiresBlending() const
-{
- return Pixel::HasAlpha( mPixelFormat );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_NATIVE_BITMAP_BUFFER_H__
-#define __DALI_NATIVE_BITMAP_BUFFER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL HEADERS
-#include <dali/public-api/images/native-image-interface.h>
-#include <dali/public-api/images/pixel.h>
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/lockless-buffer.h>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL HEADERS
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class NativeBitmapBuffer;
-typedef IntrusivePtr<NativeBitmapBuffer> NativeBitmapBufferPtr;
-
-/**
- * A Bitmap-based implementation of the NativeImage interface.
- */
-class NativeBitmapBuffer : public NativeImageInterface
-{
-
-public:
- /**
- * Constructor.
- * @param adaptor Adaptor used
- * @param width width of image
- * @param height height of image
- * @param pixelFormat pixel format for image
- */
- NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat );
-
- /**
- * virtual destructor
- */
- virtual ~NativeBitmapBuffer();
-
- /**
- * Write to buffer. Does not block.
- * @param[in] src data source
- * @param[in] size size of data in bytes
- * @return true if successful, false if currently reading from buffer in render thread
- */
- void Write( const unsigned char* src, size_t size );
-
-public:
- /**
- * @copydoc Dali::NativeImageInterface::GlExtensionCreate()
- */
- virtual bool GlExtensionCreate();
-
- /**
- * @copydoc Dali::NativeImageInterface::GlExtensionDestroy()
- */
- virtual void GlExtensionDestroy();
-
- /**
- * @copydoc Dali::NativeImageInterface::TargetTexture()
- */
- virtual unsigned int TargetTexture();
-
- /**
- * @copydoc Dali::NativeImageInterface::PrepareTexture()
- */
- virtual void PrepareTexture();
-
- /**
- * @copydoc Dali::NativeImageInterface::GetWidth()
- */
- virtual unsigned int GetWidth() const;
-
- /**
- * @copydoc Dali::NativeImageInterface::GetHeight()
- */
- virtual unsigned int GetHeight() const;
-
- /**
- * @copydoc Dali::NativeImageInterface::RequiresBlending()
- */
- virtual bool RequiresBlending() const;
-
-private:
- NativeBitmapBuffer( const NativeBitmapBuffer& ); ///< not defined
- NativeBitmapBuffer& operator =( const NativeBitmapBuffer& ); ///< not defined
- NativeBitmapBuffer(); ///< not defined
-
-private:
- Integration::GlAbstraction* mGlAbstraction; ///< GlAbstraction used
-
- Integration::LocklessBuffer* mBuffer; ///< bitmap data double buffered
- unsigned int mWidth; ///< Image width
- unsigned int mHeight; ///< Image height
- Pixel::Format mPixelFormat; ///< Image pixelformat
- const unsigned char* mLastReadBuffer; ///< last buffer that was read
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_NATIVE_BITMAP_BUFFER_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-// CLASS HEADER
-#include "socket-factory.h"
-
-// INTERNAL INCLUDES
-#include <networking/socket-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-SocketInterface* SocketFactory::NewSocket( SocketInterface::Protocol protocol )
-{
- return new Socket( protocol );
-}
-
-void SocketFactory::DestroySocket( SocketInterface* socketInterface )
-{
- Socket* socket( static_cast<Socket* >( socketInterface ));
- delete socket;
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
-#define __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <base/interfaces/socket-factory-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief concrete implementation of the socket factory interface
- */
-class SocketFactory : public SocketFactoryInterface
-{
-public:
-
-
- /**
- * @brief Constructor
- */
- SocketFactory( )
- {
- }
-
- /**
- * @brief destructor
- */
- virtual ~SocketFactory()
- {
- }
-
- /**
- * @copydoc SocketFactoryInterface::NewSocket()
- */
- virtual SocketInterface* NewSocket( SocketInterface::Protocol protocol );
-
- /**
- * @copydoc SocketFactoryInterface::DestroySocket()
- */
- virtual void DestroySocket( SocketInterface* socket );
-
-};
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "socket-impl.h"
-
-// EXTERNAL INCLUDES
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <errno.h>
-#include <unistd.h>
-#include <dali/integration-api/debug.h>
-
-// Sockets enums like INADDR_ANY use C-Casts
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int MAX_SOCKET_DATA_WRITE_SIZE = 1024 * 1024 * 10 ; // limit maximum size to write to 10 MB
-}
-
-Socket::Socket( Protocol protocol , int fileDescriptor )
-:mSocketFileDescriptor( fileDescriptor ),
- mBound(false),
- mListening(false),
- mQuitPipeCreated(false),
- mBlocked(false)
-{
- int addressFamily( AF_INET );
- int netProtocol( IPPROTO_TCP );
- int type( SOCK_STREAM ); // for TCP
-
- if( protocol == UDP )
- {
- type = SOCK_DGRAM;
- netProtocol = IPPROTO_UDP;
- }
- if( mSocketFileDescriptor == -1)
- {
- mSocketFileDescriptor = socket( addressFamily,type, netProtocol);
- if( mSocketFileDescriptor == -1 )
- {
- DALI_LOG_ERROR( "Unable to create socket\n" );
- }
- }
- else
- {
- // socket already open
- mBound = true;
- }
-}
-
-Socket::~Socket()
-{
- if( SocketIsOpen() )
- {
- CloseSocket();
- }
-}
-
-bool Socket::SocketIsOpen() const
-{
- return (mSocketFileDescriptor != -1);
-}
-
-bool Socket::CloseSocket()
-{
-
- if( ! SocketIsOpen() )
- {
- DALI_LOG_ERROR("Socket already closed or is invalid \n");
- return false;
- }
-
- int ret = close( mSocketFileDescriptor );
- mSocketFileDescriptor = -1;
- mListening = false;
- mBound = false;
-
- if( ret == -1 )
- {
- DALI_LOG_ERROR("Socket close failed\n");
- return false;
- }
- return true;
-}
-
-bool Socket::Bind( uint16_t port )
-{
- if( ! SocketIsOpen() || mBound )
- {
- DALI_LOG_ERROR("Socket is invalid, or already bound\n");
- return false;
- }
- struct sockaddr_in serverAddress;
-
- memset( &serverAddress, 0, sizeof(serverAddress) );
- serverAddress.sin_family = AF_INET; // internet
- serverAddress.sin_port = htons( port ); // host-to-net short (16-bit) translation
- serverAddress.sin_addr.s_addr = htonl( INADDR_ANY ); // binds the socket to all available interfaces
-
- int ret = bind( mSocketFileDescriptor,
- reinterpret_cast< struct sockaddr* >( &serverAddress ),
- sizeof(serverAddress));
-
- if( ret == -1 )
- {
- char buf[512];
- DALI_LOG_ERROR( "bind failed for port %d %s \n", port, strerror_r( errno, buf, 512 ) );
- return false;
- }
-
- mBound = true;
-
- return true;
-}
-
-bool Socket::Listen( int blacklog)
-{
- if( ! mBound || mListening )
- {
- DALI_LOG_ERROR("socket is not bound, or already opened for listening\n");
- return false;
- }
- int ret = listen( mSocketFileDescriptor, blacklog);
-
- if( ret == -1 )
- {
- DALI_LOG_ERROR("Listen failed\n");
- return false;
- }
-
- mListening = true;
-
- return true;
-}
-
-SocketInterface* Socket::Accept() const
-{
- if( !mListening )
- {
- DALI_LOG_ERROR("socket is not being listened to\n");
- return NULL;
- }
-
- struct sockaddr clientAddress;
-
- socklen_t addressLength(sizeof(sockaddr_in));
-
- int clientFileDescriptor = accept( mSocketFileDescriptor, &clientAddress, &addressLength);
- if( clientFileDescriptor == -1 )
- {
- DALI_LOG_ERROR("Accept failed\n");
- return NULL;
- }
-
- // create a new socket, only TCP supports connections
- Socket* client = new Socket( TCP, clientFileDescriptor );
-
- return client;
-}
-
-bool Socket::CreateQuitPipe()
-{
- if( !mQuitPipeCreated )
- {
- // create a pipe file descriptor to be able to break from the Select statement
- //
- int ret = pipe( mQuitPipe );
- if( ret != 0)
- {
- DALI_LOG_ERROR("Pipe creation failed\n");
- return false;
- }
- mQuitPipeCreated = true;
- }
- return true;
-}
-void Socket::DeleteQuitPipe()
-{
- if( mQuitPipeCreated )
- {
- close( mQuitPipe[0] );
- close( mQuitPipe[1] );
- }
-}
-
-SocketInterface::SelectReturn Socket::Select()
-{
- bool ok = CreateQuitPipe();
- if( !ok )
- {
- return ERROR;
- }
-
- fd_set readFileDescriptors, exceptFileDescriptors;
- FD_ZERO(&readFileDescriptors);
- FD_ZERO(&exceptFileDescriptors);
-
- FD_SET(mSocketFileDescriptor,&readFileDescriptors );
- FD_SET(mQuitPipe[0],&readFileDescriptors );
-
- FD_SET(mSocketFileDescriptor,&exceptFileDescriptors);
-
- unsigned int maxFd = mQuitPipe[0] > mSocketFileDescriptor ? mQuitPipe[0]: mSocketFileDescriptor;
-
- for( ;; )
- {
- // this will block waiting for file descriptors
- int ret = select( maxFd+1, &readFileDescriptors, NULL, &exceptFileDescriptors, NULL );
- if( ret == -1 )
- {
- DALI_LOG_ERROR("select failed\n");
- return ERROR;
- }
- else if ( FD_ISSET( mQuitPipe[0] , &readFileDescriptors ))
- {
- // ExitSelect() called
- return QUIT;
- }
- else if ( FD_ISSET( mSocketFileDescriptor, &readFileDescriptors ))
- {
- // socket data received
- return DATA_AVAILABLE;
- }
- }
- return QUIT;
-}
-
-void Socket::ExitSelect()
-{
- if( mQuitPipeCreated )
- {
- // write a single character to the pipe (can be anything)
- char c = ' ';
- int ret = write( mQuitPipe[1], &c, 1);
- if( ret < 1 )
- {
- DALI_LOG_ERROR("ExitSelect failed!\n");
- }
- return;
- }
-}
-
-bool Socket::ReuseAddress( bool reUse )
-{
- if( ! SocketIsOpen() | mBound )
- {
- DALI_LOG_ERROR("Socket is invalid or already bound \n");
- return false;
- }
-
- int reUseInteger = reUse; // convert it to an int
-
- int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &reUseInteger, sizeof(reUseInteger));
- if( ret == -1 )
- {
- char buf[512];
- DALI_LOG_ERROR( "SO_REUSEADDR option failed %s \n", strerror_r( errno, buf, 512 ) );
- return false;
- }
- return true;
-}
-
-bool Socket::SetBufferSize( SocketInterface::BufferType type, unsigned int size )
-{
- if( ! SocketIsOpen() || mBound )
- {
- DALI_LOG_ERROR("Socket is invalid or already bound \n");
- return false;
- }
- int option = SO_RCVBUF;
- if( type == SocketInterface::SEND_BUFFER )
- {
- option = SO_SNDBUF;
- }
-
- int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET,option,&size,sizeof(size));
- if( ret == -1 )
- {
- DALI_LOG_ERROR("SO_RCVBUF / SO_SNDBUF option failed \n");
- return false;
- }
- return true;
-}
-
-bool Socket::Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead )
-{
- bytesRead = 0;
-
- if( !SocketIsOpen() )
- {
- DALI_LOG_ERROR("Socket is invalid \n");
- return false;
- }
-
- bytesRead = read( mSocketFileDescriptor, buffer, bufferSizeInBytes );
-
- return true;
-}
-
-bool Socket::Write( const void* buffer, unsigned int bufferSizeInBytes )
-{
- if( !SocketIsOpen() )
- {
- DALI_LOG_ERROR("Socket is invalid \n");
- return false;
- }
-
- // check we don't try to write more than 10MB ( this can be increased if required)
- if( bufferSizeInBytes > MAX_SOCKET_DATA_WRITE_SIZE )
- {
- DALI_LOG_ERROR("Writing %d bytes exceeds MAX_SOCKET_DATA_WRITE_SIZE of %d bytes \n", bufferSizeInBytes, MAX_SOCKET_DATA_WRITE_SIZE);
- return false;
- }
-
- int bytesWritten = 0;
-
- // write isn't guaranteed to write the entire buffer in one go
-
- while( bytesWritten != static_cast< int>(bufferSizeInBytes))
- {
- const char* byteBuffer = static_cast<const char *>( buffer );
- byteBuffer+=bytesWritten;
-
- int ret = write( mSocketFileDescriptor, byteBuffer, bufferSizeInBytes - bytesWritten );
- if( ret < 1)
- {
- DALI_LOG_ERROR("Socket writer error \n");
- return false;
- }
- else
- {
- bytesWritten += ret;
- }
- }
- return true;
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
-#define __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <base/interfaces/socket-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief Concrete implementation of a socket under Linux.
- *
- * Provides automatic closing of socket on destruction.
- */
-class Socket : public SocketInterface
-{
-public:
-
- /**
- * @brief Constructor
- * @param protocol network protocol
- * @param fileDescriptor option file descriptor if the socket is already open
- */
- Socket( Protocol protocol , int fileDescriptor = -1 );
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketIsOpen()
- */
- virtual bool SocketIsOpen() const;
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::CloseSocket
- */
- virtual bool CloseSocket();
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Bind
- */
- virtual bool Bind( uint16_t port ) ;
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Listen
- */
- virtual bool Listen( int blacklog);
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Accept
- */
- virtual SocketInterface* Accept() const ;
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Select
- */
- virtual SelectReturn Select( );
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::ExitSelect
- */
- virtual void ExitSelect();
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Recieve
- */
- virtual bool Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead );
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::Send
- */
- virtual bool Write( const void* buffer, unsigned int bufferLength );
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::ReuseAddress
- */
- virtual bool ReuseAddress( bool reUse );
-
- /**
- * @copydoc Dali::Internal::Adaptor::SocketInterface::SetBufferSize
- *
- */
- virtual bool SetBufferSize( SocketInterface::BufferType type, unsigned int bufferSizeInBytes );
-
- /**
- * @brief Virtual destructor
- */
- virtual ~Socket();
-
-private:
-
-
- /**
- * @brief Helper to create the quit pipe
- */
- bool CreateQuitPipe();
-
- /**
- * @brief Helper to delete the quit pipe
- */
- void DeleteQuitPipe();
-
- int mSocketFileDescriptor; ///< file descriptor
- int mQuitPipe[2]; ///< Pipe to inform Select to quit.
- bool mBound:1; ///< whether the socket is bound
- bool mListening:1; ///< whether the socket is being listen to
- bool mQuitPipeCreated:1; ///< whether the quit pipe has been created
- bool mBlocked:1; ///< whether the socket is blocked waiting for a connection
-};
-
-
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "object-profiler.h"
-
-// EXTERNAL INCLUDES
-#include <stdlib.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/profiling.h>
-#include <dali/public-api/common/stage.h>
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/object/type-registry.h>
-
-using std::string;
-using namespace Dali::Integration::Profiling;
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-ObjectProfiler::ObjectProfiler( unsigned int timeInterval )
-{
- // This class must be created after the Stage; this means it doesn't count the initial objects
- // that are created by the stage (base layer, default camera actor)
- mObjectRegistry = Dali::Stage::GetCurrent().GetObjectRegistry();
-
- mTimer = Dali::Timer::New( timeInterval * 1000 );
- mTimer.TickSignal().Connect( this, &ObjectProfiler::OnTimeout );
- mTimer.Start();
-
- mObjectRegistry.ObjectCreatedSignal().Connect( this, &ObjectProfiler::OnObjectCreated );
- mObjectRegistry.ObjectDestroyedSignal().Connect( this, &ObjectProfiler::OnObjectDestroyed );
-}
-
-ObjectProfiler::~ObjectProfiler()
-{
-}
-
-void ObjectProfiler::DisplayInstanceCounts()
-{
- for( auto&& element : mInstanceCountContainer )
- {
- int memorySize = GetMemorySize( element.first, element.second );
- if( memorySize > 0 )
- {
- LogMessage( Debug::DebugInfo, "%-30s: % 4d Memory MemorySize: ~% 6.1f kB\n",
- element.first.c_str(), element.second, memorySize / 1024.0f );
- }
- else
- {
- LogMessage( Debug::DebugInfo, "%-30s: % 4d\n",
- element.first.c_str(), element.second );
- }
- }
- LogMessage(Debug::DebugInfo, "\n");
-}
-
-bool ObjectProfiler::OnTimeout()
-{
- DisplayInstanceCounts();
- return true;
-}
-
-void ObjectProfiler::OnObjectCreated(BaseHandle handle)
-{
- string theType = handle.GetTypeName();
- if( theType.empty() )
- {
- DALI_LOG_ERROR("Object created from an unregistered type\n");
- theType = "<Unregistered>";
- }
-
- mInstanceTypes.push_back(InstanceTypePair(&handle.GetBaseObject(), theType));
-
- bool found = false;
- for( auto&& element : mInstanceCountContainer )
- {
- if( element.first == theType )
- {
- element.second++;
- found = true;
- }
- }
- if( !found )
- {
- InstanceCountPair instanceCount( theType, 1 );
- mInstanceCountContainer.emplace_back( instanceCount );
- }
-}
-
-void ObjectProfiler::OnObjectDestroyed(const Dali::RefObject* object)
-{
- const BaseObject* baseObject = static_cast<const BaseObject*>(object);
-
- const auto end = mInstanceTypes.end();
- for( auto iter = mInstanceTypes.begin(); iter != end; ++iter )
- {
- if( iter->first == baseObject )
- {
- const auto& theType = iter->second;
- if( !theType.empty() )
- {
- auto&& countIter = std::find_if( mInstanceCountContainer.begin(),
- mInstanceCountContainer.end(),
- [theType] ( const InstanceCountPair& instance )
- { return instance.first == theType; } );
- if( countIter != mInstanceCountContainer.end() )
- {
- (*countIter).second--;
- }
- }
- mInstanceTypes.erase( iter );
- return;
- }
- }
-}
-
-int ObjectProfiler::GetMemorySize(const std::string& name, int count)
-{
- struct MemoryMemorySize
- {
- std::string name;
- int memorySize;
- };
- MemoryMemorySize memoryMemorySizes[] =
- {
- { "Animation", ANIMATION_MEMORY_SIZE },
- { "Constraint", CONSTRAINT_MEMORY_SIZE },
- { "Actor", ACTOR_MEMORY_SIZE },
- { "Layer", LAYER_MEMORY_SIZE },
- { "CameraActor", CAMERA_ACTOR_MEMORY_SIZE },
- { "Image", IMAGE_MEMORY_SIZE },
- { "Renderer", RENDERER_MEMORY_SIZE },
- { "Geometry", GEOMETRY_MEMORY_SIZE },
- { "PropertyBuffer", PROPERTY_BUFFER_MEMORY_SIZE },
- { "TextureSet", TEXTURE_SET_MEMORY_SIZE },
- { "Sampler", SAMPLER_MEMORY_SIZE },
- { "Shader", SHADER_MEMORY_SIZE },
- };
-
- for( size_t i=0; i<sizeof(memoryMemorySizes)/sizeof(MemoryMemorySize); i++ )
- {
- if( memoryMemorySizes[i].name.compare(name) == 0 )
- {
- return count * memoryMemorySizes[i].memorySize;
- }
- }
- return 0;
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-#ifndef __DALI_ADAPTOR_OBJECT_PROFILER_H__
-#define __DALI_ADAPTOR_OBJECT_PROFILER_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/object/object-registry.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/signals/connection-tracker.h>
-
-// INTERNAL INCLUDES
-#include <timer.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * Class to profile the number of instances of Objects in the system
- */
-class ObjectProfiler : public ConnectionTracker
-{
-public:
-
- /**
- * Constructor
- * @param timeInterval to specify the frequency of reporting
- */
- ObjectProfiler( unsigned int timeInterval );
-
- /**
- * Destructor
- */
- ~ObjectProfiler();
-
- /**
- * Display a list of types with the current number of instances in the system
- */
- void DisplayInstanceCounts();
-
-private:
- /**
- * If timer is running, display the instance counts
- */
- bool OnTimeout();
-
- /**
- * Callback used when objects are created. Increases instance count for that object type
- * @param[in] handle of the created object
- */
- void OnObjectCreated(BaseHandle handle);
-
- /**
- * Callback used when objects are created. Decreases instance count for that object type
- * @param[in] object The object being destroyed
- */
- void OnObjectDestroyed(const Dali::RefObject* object);
-
- /**
- * Get the memory size of the given object
- */
- int GetMemorySize(const std::string& name, int count);
-
-private:
-
- using InstanceCountPair = std::pair< const std::string, int >;
- using InstanceTypePair = std::pair< BaseObject*, std::string >;
-
- Dali::ObjectRegistry mObjectRegistry;
- Dali::Timer mTimer;
- std::vector< InstanceCountPair > mInstanceCountContainer;
- std::vector< InstanceTypePair > mInstanceTypes;
-};
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif // __DALI_ADAPTOR_OBJECT_PROFILER_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "orientation-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <window-impl.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-Orientation* Orientation::New(Window* window)
-{
- Orientation* orientation = new Orientation(window);
-
- return orientation;
-}
-
-Orientation::Orientation(Window* window)
-: mWindow(window),
- mOrientation(0),
- mWindowWidth(0),
- mWindowHeight(0)
-{
-}
-
-Orientation::~Orientation()
-{
- // Note, there is only one orientation object that's owned by window,
- // so it will live longer than adaptor. (hence, no need to remove rotation observer)
-}
-
-void Orientation::SetAdaptor(Dali::Adaptor& adaptor)
-{
- Adaptor& adaptorImpl = Adaptor::GetImplementation(adaptor);
- adaptorImpl.SetRotationObserver(this);
-}
-
-int Orientation::GetDegrees() const
-{
- return mOrientation;
-}
-
-float Orientation::GetRadians() const
-{
- return Math::PI * float(mOrientation) / 180.0f;
-}
-
-Orientation::OrientationSignalType& Orientation::ChangedSignal()
-{
- return mChangedSignal;
-}
-
-void Orientation::OnRotationPrepare( const RotationEvent& rotation )
-{
- mOrientation = rotation.angle;
- mWindowWidth = rotation.width;
- mWindowHeight = rotation.height;
-}
-
-void Orientation::OnRotationRequest()
-{
- // Emit signal
- if( !mChangedSignal.Empty() )
- {
- Dali::Orientation handle( this );
- mChangedSignal.Emit( handle );
- }
-
- if( mWindow != NULL )
- {
- mWindow->RotationDone( mOrientation, mWindowWidth, mWindowHeight );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ORIENTATION_H__
-#define __DALI_INTERNAL_ORIENTATION_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <cmath>
-#include <dali/public-api/common/constants.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <orientation.h>
-#include <rotation-observer.h>
-
-namespace Dali
-{
-class Adaptor;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-class Window;
-class Orientation;
-
-typedef IntrusivePtr<Orientation> OrientationPtr;
-
-class Orientation : public BaseObject, public RotationObserver
-{
-public:
-
- typedef Dali::Orientation::OrientationSignalType OrientationSignalType;
-
- static Orientation* New(Window* window);
-
- /**
- * Constructor
- */
- Orientation(Window* window);
-
-protected:
- /**
- * Destructor
- */
- virtual ~Orientation();
-
-public:
- /**
- * Set the adaptor for basic setup
- * @param[in] adaptor The adaptor
- */
- void SetAdaptor(Dali::Adaptor& adaptor);
-
- /**
- * Returns the actual orientation in degrees
- * @return The device's orientation
- */
- int GetDegrees() const;
-
- /**
- * Returns the actual orientation in radians
- * @return The device's orientation
- */
- float GetRadians() const;
-
-public: // Signals
-
- /**
- * @copydoc Dali::Orientation::ChangedSignal()
- */
- OrientationSignalType& ChangedSignal();
-
-private:
- /**
- * @copydoc Dali::Internal::Adaptor::RotationObserver::OnRotationPrepare()
- */
- virtual void OnRotationPrepare( const RotationEvent& rotation );
-
- /**
- * @copydoc Dali::Internal::Adaptor::RotationObserver::OnRotationRequest()
- */
- virtual void OnRotationRequest( );
-
- // Undefined
- Orientation(const Orientation&);
- Orientation& operator=(Orientation&);
-
-private:
- /**
- * Signals and sends event of orientation change.
- */
- void EmitOrientationChange();
-
-private:
-
- Window* mWindow;
-
- OrientationSignalType mChangedSignal;
-
- int mOrientation;
- int mWindowWidth;
- int mWindowHeight;
-};
-
-inline Orientation& GetImplementation (Dali::Orientation& orientation)
-{
- DALI_ASSERT_ALWAYS(orientation && "Orientation handle is empty");
-
- BaseObject& handle = orientation.GetBaseObject();
-
- return static_cast<Orientation&>(handle);
-}
-
-inline const Orientation& GetImplementation(const Dali::Orientation& orientation)
-{
- DALI_ASSERT_ALWAYS(orientation && "Orientation handle is empty");
-
- const BaseObject& handle = orientation.GetBaseObject();
-
- return static_cast<const Orientation&>(handle);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ORIENTATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <performance-logger-impl.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-PerformanceInterface* GetPerformanceInterface()
-{
- if( Adaptor::IsAvailable() )
- {
- return Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetPerformanceInterface();
- }
-
- return NULL;
-}
-
-} // Anonymous namespace
-
-PerformanceLoggerPtr PerformanceLogger::New( const char* name )
-{
- PerformanceLoggerPtr logger = new PerformanceLogger( name );
- return logger;
-}
-
-PerformanceLogger::PerformanceLogger( const char* name )
-: mContext( 0 )
-{
- PerformanceInterface* performance = GetPerformanceInterface();
- if( performance )
- {
- mContext = performance->AddContext( name );
- }
-}
-
-PerformanceLogger::~PerformanceLogger()
-{
- PerformanceInterface* performance = GetPerformanceInterface();
- if( performance )
- {
- performance->RemoveContext( mContext );
- }
-}
-
-void PerformanceLogger::AddMarker( Dali::PerformanceLogger::Marker markerType )
-{
- PerformanceInterface* performance = GetPerformanceInterface();
- if( performance )
- {
- PerformanceInterface::MarkerType newMarkerType = PerformanceInterface::START;
- switch( markerType )
- {
- case Dali::PerformanceLogger::START_EVENT:
- {
- newMarkerType = PerformanceInterface::START;
- break;
- }
- case Dali::PerformanceLogger::END_EVENT:
- {
- newMarkerType = PerformanceInterface::END;
- break;
- }
- }
-
- performance->AddMarker( newMarkerType, mContext );
- }
-}
-
-void PerformanceLogger::SetLoggingFrequency( unsigned int logFrequency)
-{
- PerformanceInterface* performance = GetPerformanceInterface();
- if( performance )
- {
- performance->SetLoggingFrequency( logFrequency, mContext );
- }
-}
-
-void PerformanceLogger::EnableLogging( bool enable )
-{
- PerformanceInterface* performance = GetPerformanceInterface();
- if( performance )
- {
- performance->EnableLogging( enable, mContext );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
-#define __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/performance-interface.h>
-#include <performance-logger.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class PerformanceLogger;
-
-typedef IntrusivePtr<PerformanceLogger> PerformanceLoggerPtr;
-
-/**
- * @brief Interface for the performance logger
- */
-class PerformanceLogger : public BaseObject
-{
-public:
-
- /**
- * @brief Create a new logger
- *
- * @param[in] name The name of the logger. This needs to be a compile-time literal and alive for the whole lifetime of the performance logger.
- * @return a new logger
- */
- static PerformanceLoggerPtr New( const char* name );
-
- /**
- * Constructor
- * @param[in] name The name to assing to the logger
- */
- PerformanceLogger( const char* name );
-
- /**
- * Destructor.
- */
- virtual ~PerformanceLogger();
-
- /**
- * Add a performance marker
- *
- * @param markerType Performance marker type
- */
- void AddMarker( Dali::PerformanceLogger::Marker markerType );
-
- /**
- * Set the logging frequency
- *
- * @param logFrequency how often to log out in seconds
- */
- void SetLoggingFrequency( unsigned int logFrequency);
-
- /**
- * Set logging on or off for this logger
- *
- * @param[in] enable Enable logging or not
- */
- void EnableLogging( bool enable );
-
-private: // Implementation
-
- // not implemented
- PerformanceLogger( const PerformanceLogger& );
- PerformanceLogger& operator=( const PerformanceLogger& );
-
-private:
-
- PerformanceInterface::ContextId mContext; ///< Context of this logger
-
-};
-
-// Helpers for public-api forwarding methods
-
-inline static Internal::Adaptor::PerformanceLogger& GetImplementation( Dali::PerformanceLogger& logger )
-{
- DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" );
-
- BaseObject& handle = logger.GetBaseObject();
-
- return static_cast< Internal::Adaptor::PerformanceLogger& >( handle );
-}
-
-inline static const Internal::Adaptor::PerformanceLogger& GetImplementation( const Dali::PerformanceLogger& logger )
-{
- DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" );
-
- const BaseObject& handle = logger.GetBaseObject();
-
- return static_cast< const Internal::Adaptor::PerformanceLogger& >( handle );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-
-// CLASS HEADER
-#include <physical-keyboard-impl.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::PhysicalKeyboard PhysicalKeyboard::New()
-{
- Dali::PhysicalKeyboard keyboardHandle;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- keyboardHandle = Dali::PhysicalKeyboard( new PhysicalKeyboard() );
- service.Register( typeid( keyboardHandle ), keyboardHandle );
- }
-
- return keyboardHandle;
-}
-
-Dali::PhysicalKeyboard PhysicalKeyboard::Get()
-{
- Dali::PhysicalKeyboard keyboardHandle;
-
- Dali::SingletonService service = SingletonService::Get();
- if ( service )
- {
- BaseHandle handle = service.GetSingleton( typeid( Dali::PhysicalKeyboard ) );
- if( handle )
- {
- // If so, downcast the handle of singleton to focus manager
- keyboardHandle = Dali::PhysicalKeyboard( dynamic_cast< PhysicalKeyboard* >( handle.GetObjectPtr() ) );
- }
- }
-
- return keyboardHandle;
-}
-
-bool PhysicalKeyboard::IsAttached() const
-{
- return mAttached;
-}
-
-void PhysicalKeyboard::KeyReceived( bool fromPhysicalKeyboard )
-{
- if ( mAttached != fromPhysicalKeyboard )
- {
- mAttached = fromPhysicalKeyboard;
-
- Dali::PhysicalKeyboard handle( this );
- mStatusChangedSignal.Emit( handle );
- }
-}
-
-PhysicalKeyboard::~PhysicalKeyboard()
-{
-}
-
-PhysicalKeyboard::PhysicalKeyboard()
-: mAttached( false )
-{
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
-#define __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <physical-keyboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class PhysicalKeyboard : public BaseObject
-{
-public:
-
- /**
- * Creates a new instance of the PhysicalKeyboard.
- */
- static Dali::PhysicalKeyboard New();
-
- /**
- * Gets the singleton instance of the Physical Keyboard.
- */
- static Dali::PhysicalKeyboard Get();
-
- /**
- * @copydoc Dali::PhysicalKeyboard::IsAttached()
- */
- bool IsAttached() const;
-
- /**
- * Should be called by the EventHandler when a key is received. If it's received from a physical
- * keyboard then the parameter should be true.
- * @param[in] fromPhysicalKeyboard true if received from a physical keyboard, false otherwise.
- */
- void KeyReceived( bool fromPhysicalKeyboard );
-
- // Signals
-
- /**
- * @copydoc Dali::PhysicalKeyboard::StatusChangedSignal()
- */
- Dali::PhysicalKeyboard::PhysicalKeyboardSignalType& StatusChangedSignal() { return mStatusChangedSignal; }
-
-protected:
-
- /**
- * A reference counted object may only be deleted by calling Unreference()
- */
- virtual ~PhysicalKeyboard();
-
-private:
-
- // Undefined
- PhysicalKeyboard( const PhysicalKeyboard& );
- PhysicalKeyboard& operator=( PhysicalKeyboard& );
-
- /**
- * Constructor
- */
- PhysicalKeyboard();
-
-private:
-
- Dali::PhysicalKeyboard::PhysicalKeyboardSignalType mStatusChangedSignal; ///< Status changed signal
- bool mAttached; ///< true if the physical keyboard is attached, false otherwise
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline static Internal::Adaptor::PhysicalKeyboard& GetImplementation( PhysicalKeyboard& keyboard )
-{
- DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" );
-
- BaseObject& handle = keyboard.GetBaseObject();
-
- return static_cast< Internal::Adaptor::PhysicalKeyboard& >( handle );
-}
-
-inline static const Internal::Adaptor::PhysicalKeyboard& GetImplementation( const PhysicalKeyboard& keyboard )
-{
- DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" );
-
- const BaseObject& handle = keyboard.GetBaseObject();
-
- return static_cast< const Internal::Adaptor::PhysicalKeyboard& >( handle );
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
+++ /dev/null
-/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pixel-buffer-impl.h"
-
-// EXTERNAL INCLUDES
-#include <stdlib.h>
-#include <cstring>
-
-// INTERNAL INCLUDES
-#include "pixel-manipulation.h"
-#include "alpha-mask.h"
-#include "gaussian-blur.h"
-#include <platform-abstractions/portable/image-operations.h>
-#include <platform-abstractions/portable/pixel-manipulation.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-PixelBuffer::PixelBuffer( unsigned char* buffer,
- unsigned int bufferSize,
- unsigned int width,
- unsigned int height,
- Dali::Pixel::Format pixelFormat )
-: mMetadata(),
- mBuffer( buffer ),
- mBufferSize( bufferSize ),
- mWidth( width ),
- mHeight( height ),
- mPixelFormat( pixelFormat )
-{
-}
-
-PixelBuffer::~PixelBuffer()
-{
- ReleaseBuffer();
-}
-
-PixelBufferPtr PixelBuffer::New( unsigned int width,
- unsigned int height,
- Dali::Pixel::Format pixelFormat )
-{
- unsigned int bufferSize = width * height * Dali::Pixel::GetBytesPerPixel( pixelFormat );
- unsigned char* buffer = NULL;
- if( bufferSize > 0 )
- {
- buffer = static_cast<unsigned char*>( malloc ( bufferSize ) );
- }
- return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
-}
-
-PixelBufferPtr PixelBuffer::New( unsigned char* buffer,
- unsigned int bufferSize,
- unsigned int width,
- unsigned int height,
- Dali::Pixel::Format pixelFormat )
-{
- return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
-}
-
-Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer )
-{
- Dali::PixelData pixelData = Dali::PixelData::New( pixelBuffer.mBuffer,
- pixelBuffer.mBufferSize,
- pixelBuffer.mWidth,
- pixelBuffer.mHeight,
- pixelBuffer.mPixelFormat,
- Dali::PixelData::FREE );
- pixelBuffer.mBuffer = NULL;
- pixelBuffer.mWidth = 0;
- pixelBuffer.mHeight = 0;
- pixelBuffer.mBufferSize = 0;
-
- return pixelData;
-}
-
-unsigned int PixelBuffer::GetWidth() const
-{
- return mWidth;
-}
-
-unsigned int PixelBuffer::GetHeight() const
-{
- return mHeight;
-}
-
-Dali::Pixel::Format PixelBuffer::GetPixelFormat() const
-{
- return mPixelFormat;
-}
-
-unsigned char* PixelBuffer::GetBuffer() const
-{
- return mBuffer;
-}
-
-unsigned int PixelBuffer::GetBufferSize() const
-{
- return mBufferSize;
-}
-
-Dali::PixelData PixelBuffer::CreatePixelData() const
-{
- unsigned char* destBuffer = NULL;
-
- if( mBufferSize > 0 )
- {
- destBuffer = static_cast<unsigned char*>( malloc( mBufferSize ) );
- memcpy( destBuffer, mBuffer, mBufferSize );
- }
-
- Dali::PixelData pixelData = Dali::PixelData::New( destBuffer, mBufferSize,
- mWidth, mHeight,
- mPixelFormat,
- Dali::PixelData::FREE );
- return pixelData;
-}
-
-void PixelBuffer::ApplyMask( const PixelBuffer& inMask, float contentScale, bool cropToMask )
-{
- if( cropToMask )
- {
- // First scale this buffer by the contentScale, and crop to the mask size
- // If it's too small, then scale the mask to match the image size
- // Then apply the mask
- ScaleAndCrop( contentScale, ImageDimensions( inMask.GetWidth(), inMask.GetHeight() ) );
-
- if( inMask.mWidth > mWidth || inMask.mHeight > mHeight )
- {
- PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
- ApplyMaskInternal( *mask );
- }
- else
- {
- ApplyMaskInternal( inMask );
- }
- }
- else
- {
- // First, scale the mask to match the image size,
- // then apply the mask.
- PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
- ApplyMaskInternal( *mask );
- }
-}
-
-void PixelBuffer::ApplyMaskInternal( const PixelBuffer& mask )
-{
- int byteOffset=0;
- int bitMask=0;
-
- Dali::Pixel::GetAlphaOffsetAndMask(mPixelFormat, byteOffset, bitMask);
- if( Dali::Pixel::HasAlpha( mPixelFormat ) && bitMask == 255 )
- {
- ApplyMaskToAlphaChannel( *this, mask );
- }
- else
- {
- PixelBufferPtr newPixelBuffer = CreateNewMaskedBuffer( *this, mask );
- TakeOwnershipOfBuffer( *newPixelBuffer );
- // On leaving scope, newPixelBuffer will get destroyed.
- }
-}
-
-void PixelBuffer::TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer )
-{
- ReleaseBuffer();
-
- // Take ownership of new buffer
- mBuffer = pixelBuffer.mBuffer;
- pixelBuffer.mBuffer = NULL;
- mBufferSize = pixelBuffer.mBufferSize;
- mWidth = pixelBuffer.mWidth;
- mHeight = pixelBuffer.mHeight;
- mPixelFormat = pixelBuffer.mPixelFormat;
-}
-
-void PixelBuffer::ReleaseBuffer()
-{
- if( mBuffer )
- {
- free( mBuffer );
- }
-}
-
-void PixelBuffer::AllocateFixedSize( uint32_t size )
-{
- ReleaseBuffer();
- mBuffer = reinterpret_cast<unsigned char*>(malloc( size ));
- mBufferSize = size;
-}
-
-void PixelBuffer::ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions )
-{
- ImageDimensions outDimensions( float(mWidth) * scaleFactor,
- float(mHeight) * scaleFactor );
-
- if( outDimensions.GetWidth() != mWidth || outDimensions.GetHeight() != mHeight )
- {
- Resize( outDimensions );
- }
-
- ImageDimensions postCropDimensions(
- std::min(cropDimensions.GetWidth(), outDimensions.GetWidth()),
- std::min(cropDimensions.GetHeight(), outDimensions.GetHeight()));
-
- if( postCropDimensions.GetWidth() < outDimensions.GetWidth() ||
- postCropDimensions.GetHeight() < outDimensions.GetHeight() )
- {
- uint16_t x = ( outDimensions.GetWidth() - postCropDimensions.GetWidth() ) / 2;
- uint16_t y = ( outDimensions.GetHeight() - postCropDimensions.GetHeight() ) / 2;
- Crop( x, y, postCropDimensions );
- }
-}
-
-void PixelBuffer::Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions )
-{
- PixelBufferPtr outBuffer = NewCrop( *this, x, y, cropDimensions );
- TakeOwnershipOfBuffer( *outBuffer );
-}
-
-PixelBufferPtr PixelBuffer::NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions )
-{
- PixelBufferPtr outBuffer = PixelBuffer::New( cropDimensions.GetWidth(), cropDimensions.GetHeight(), inBuffer.GetPixelFormat() );
- int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
- int srcStride = inBuffer.mWidth * bytesPerPixel;
- int destStride = cropDimensions.GetWidth() * bytesPerPixel;
-
- // Clamp crop to right edge
- if( x + cropDimensions.GetWidth() > inBuffer.mWidth )
- {
- destStride = ( inBuffer.mWidth - x ) * bytesPerPixel;
- }
-
- int srcOffset = x * bytesPerPixel + y * srcStride;
- int destOffset = 0;
- unsigned char* destBuffer = outBuffer->mBuffer;
-
- // Clamp crop to last row
- unsigned int endRow = y + cropDimensions.GetHeight();
- if( endRow > inBuffer.mHeight )
- {
- endRow = inBuffer.mHeight - 1 ;
- }
- for( uint16_t row = y; row < endRow; ++row )
- {
- memcpy(destBuffer + destOffset, inBuffer.mBuffer + srcOffset, destStride );
- srcOffset += srcStride;
- destOffset += destStride;
- }
- return outBuffer;
-
-}
-
-void PixelBuffer::SetMetadata( const Property::Map& map )
-{
- mMetadata.reset(new Property::Map(map));
-}
-
-bool PixelBuffer::GetMetadata(Property::Map& outMetadata) const
-{
- if( !mMetadata )
- {
- return false;
- }
- outMetadata = *mMetadata;
- return true;
-}
-
-void PixelBuffer::SetMetadata(std::unique_ptr<Property::Map> metadata)
-{
- mMetadata = std::move(metadata);
-}
-
-void PixelBuffer::Resize( ImageDimensions outDimensions )
-{
- if( mWidth != outDimensions.GetWidth() || mHeight != outDimensions.GetHeight() )
- {
- PixelBufferPtr outBuffer = NewResize( *this, outDimensions );
- TakeOwnershipOfBuffer( *outBuffer );
- }
-}
-
-PixelBufferPtr PixelBuffer::NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions )
-{
- PixelBufferPtr outBuffer = PixelBuffer::New( outDimensions.GetWidth(), outDimensions.GetHeight(), inBuffer.GetPixelFormat() );
- ImageDimensions inDimensions( inBuffer.mWidth, inBuffer.mHeight );
-
- bool hasAlpha = Pixel::HasAlpha( inBuffer.mPixelFormat );
- int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
-
- Resampler::Filter filterType = Resampler::LANCZOS4;
- if( inDimensions.GetWidth() < outDimensions.GetWidth() && inDimensions.GetHeight() < outDimensions.GetHeight() )
- {
- filterType = Resampler::MITCHELL;
- }
-
- // This method only really works for 8 bit wide channels.
- // (But could be expanded to work)
- if( inBuffer.mPixelFormat == Pixel::A8 ||
- inBuffer.mPixelFormat == Pixel::L8 ||
- inBuffer.mPixelFormat == Pixel::LA88 ||
- inBuffer.mPixelFormat == Pixel::RGB888 ||
- inBuffer.mPixelFormat == Pixel::RGB8888 ||
- inBuffer.mPixelFormat == Pixel::BGR8888 ||
- inBuffer.mPixelFormat == Pixel::RGBA8888 ||
- inBuffer.mPixelFormat == Pixel::BGRA8888 )
- {
- Dali::Internal::Platform::Resample( inBuffer.mBuffer, inDimensions,
- outBuffer->GetBuffer(), outDimensions,
- filterType, bytesPerPixel, hasAlpha );
- }
- else
- {
- DALI_LOG_ERROR( "Trying to resize an image with too narrow a channel width" );
- }
-
- return outBuffer;
-}
-
-void PixelBuffer::ApplyGaussianBlur( const float blurRadius )
-{
- // This method only works for pixel buffer in RGBA format.
- if( mWidth > 0 && mHeight > 0 && mPixelFormat == Pixel::RGBA8888 )
- {
- if ( blurRadius > Math::MACHINE_EPSILON_1 )
- {
- PerformGaussianBlurRGBA( *this, blurRadius );
- }
- }
- else
- {
- DALI_LOG_ERROR( "Trying to apply gaussian blur to an empty pixel buffer or a pixel buffer not in RGBA format" );
- }
-}
-
-void PixelBuffer::MultiplyColorByAlpha()
-{
- auto bytesPerPixel = Pixel::GetBytesPerPixel( mPixelFormat );
-
- // Compressed textures have unknown size of the pixel. Alpha premultiplication
- // must be skipped in such case
- if( Pixel::GetBytesPerPixel(mPixelFormat) && Pixel::HasAlpha(mPixelFormat) )
- {
- unsigned char* pixel = mBuffer;
- const unsigned int bufferSize = mWidth * mHeight;
-
- for( unsigned int i=0; i<bufferSize; ++i )
- {
- unsigned int alpha = ReadChannel( pixel, mPixelFormat, Adaptor::ALPHA );
- {
- auto red = ReadChannel( pixel, mPixelFormat, Adaptor::RED);
- auto green = ReadChannel( pixel, mPixelFormat, Adaptor::GREEN);
- auto blue = ReadChannel( pixel, mPixelFormat, Adaptor::BLUE);
- auto luminance = ReadChannel( pixel, mPixelFormat, Adaptor::LUMINANCE);
- WriteChannel( pixel, mPixelFormat, Adaptor::RED, red*alpha / 255 );
- WriteChannel( pixel, mPixelFormat, Adaptor::GREEN, green*alpha/255 );
- WriteChannel( pixel, mPixelFormat, Adaptor::BLUE, blue*alpha/255 );
- WriteChannel( pixel, mPixelFormat, Adaptor::LUMINANCE, luminance*alpha/255 );
- }
- pixel += bytesPerPixel;
- }
- }
-}
-
-
-
-
-}// namespace Adaptor
-}// namespace Internal
-}// namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H
-#define DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H
-
-/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <pixel-buffer.h>
-#include <dali/public-api/images/image-operations.h> // For ImageDimensions
-#include <dali/public-api/images/pixel-data.h>
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/object/property-map.h>
-
-// EXTERNAL INCLUDES
-#include <memory>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class PixelBuffer;
-typedef IntrusivePtr<PixelBuffer> PixelBufferPtr;
-
-class PixelBuffer : public BaseObject
-{
-public:
-
- /**
- * @brief Create a PixelBuffer object with a pre-allocated buffer.
- * The PixelBuffer object owns this buffer, which may be retrieved
- * and modified using GetBuffer().
- *
- * @param [in] width Buffer width in pixels
- * @param [in] height Buffer height in pixels
- * @param [in] pixelFormat The pixel format
- */
- static PixelBufferPtr New( unsigned int width,
- unsigned int height,
- Pixel::Format pixelFormat );
-
- /**
- * @brief Create a PixelBuffer object. For internal use only.
- *
- * @param [in] buffer The raw pixel data.
- * @param [in] bufferSize The size of the buffer in bytes
- * @param [in] width Buffer width in pixels
- * @param [in] height Buffer height in pixels
- * @param [in] pixelFormat The pixel format
- * @param [in] releaseFunction The function used to release the memory.
- */
- static PixelBufferPtr New( unsigned char* buffer,
- unsigned int bufferSize,
- unsigned int width,
- unsigned int height,
- Pixel::Format pixelFormat );
-
- /**
- * Convert a pixelBuffer object into a PixelData object.
- * The new object takes ownership of the buffer data, and the
- * mBuffer pointer is reset to NULL.
- * @param[in] pixelBuffer The buffer to convert
- * @return the pixelData
- */
- static Dali::PixelData Convert( PixelBuffer& pixelBuffer );
-
- /**
- * @brief Constructor.
- *
- * @param [in] buffer The raw pixel data.
- * @param [in] bufferSize The size of the buffer in bytes
- * @param [in] width Buffer width in pixels
- * @param [in] height Buffer height in pixels
- * @param [in] pixelFormat The pixel format
- */
- PixelBuffer( unsigned char* buffer,
- unsigned int bufferSize,
- unsigned int width,
- unsigned int height,
- Pixel::Format pixelFormat );
-
-protected:
-
- /**
- * @brief Destructor.
- *
- * Release the pixel buffer if exists.
- */
- ~PixelBuffer();
-
-public:
-
- /**
- * Get the width of the buffer in pixels.
- * @return The width of the buffer in pixels
- */
- unsigned int GetWidth() const;
-
- /**
- * Get the height of the buffer in pixels
- * @return The height of the buffer in pixels
- */
- unsigned int GetHeight() const;
-
- /**
- * Get the pixel format
- * @return The pixel format
- */
- Pixel::Format GetPixelFormat() const;
-
- /**
- * Get the pixel buffer if it's present.
- * @return The buffer if exists, or NULL if there is no pixel buffer.
- */
- unsigned char* GetBuffer() const;
-
- /**
- * Get the size of the buffer in bytes
- * @return The size of the buffer
- */
- unsigned int GetBufferSize() const;
-
- /**
- * Copy the buffer into a new PixelData
- */
- Dali::PixelData CreatePixelData() const;
-
- /**
- * @brief Apply the mask to the current buffer.
- *
- * This method may update the internal object - e.g. the new buffer
- * may have a different pixel format - as an alpha channel may be
- * added.
- * @param[in] mask The mask to apply to this pixel buffer
- * @param[in] contentScale The scaling factor to apply to the content
- * @param[in] cropToMask Whether to crop the output to the mask size (true) or scale the
- * mask to the content size (false)
- */
- void ApplyMask( const PixelBuffer& mask, float contentScale, bool cropToMask );
-
- /**
- * @brief Apply a Gaussian blur to the current buffer with the given radius.
- *
- * @param[in] blurRadius The radius for Gaussian blur
- */
- void ApplyGaussianBlur( const float blurRadius );
-
- /**
- * Crops this buffer to the given crop rectangle. Assumes the crop rectangle
- * is within the bounds of this size.
- * @param[in] x The top left corner's X
- * @param[in] y The top left corner's y
- * @param[in] cropDimensions The dimensions of the crop
- */
- void Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions );
-
- /**
- * Resizes the buffer to the given dimensions. Uses either Lanczos4 for downscaling
- * or Mitchell for upscaling
- * @param[in] outDimensions The new dimensions
- */
- void Resize( ImageDimensions outDimensions );
-
- /**
- * Multiplies the image's color values by the alpha value. This provides better
- * blending capability.
- */
- void MultiplyColorByAlpha();
-
- /**
- * @brief Sets image metadata
- *
- * @param map Property map containing Exif fields
- */
- void SetMetadata( const Property::Map& map );
-
- /**
- * @brief Returns image metadata as a property map
- * @param[out] outMetadata Property map to copy the data into
- * @return True on success
- */
- bool GetMetadata(Property::Map& outMetadata) const;
-
- /**
- * @brief Sets metadata property map for the pixel buffer
- * @note The function takes over the ownership of the property map
- * @param[in] metadata Property map to copy the data into
- */
- void SetMetadata(std::unique_ptr<Property::Map> metadata);
-
- /**
- * Allocates fixed amount of memory for the pixel data. Used by compressed formats.
- * @param[in] size Size of memory to be allocated
- */
- void AllocateFixedSize( uint32_t size );
-
-private:
- /*
- * Undefined copy constructor.
- */
- PixelBuffer(const PixelBuffer& other);
-
- /*
- * Undefined assignment operator.
- */
- PixelBuffer& operator= (const PixelBuffer& other);
-
- /**
- * Internal method to apply the mask to this buffer. Expects that they are the same size.
- */
- void ApplyMaskInternal( const PixelBuffer& mask );
-
- /**
- * Takes ownership of the other object's pixel buffer.
- */
- void TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer );
-
- /**
- * Release the buffer
- */
- void ReleaseBuffer();
-
- /**
- * Scales this buffer buffer by the given factor, and crops at the center to the
- * given dimensions.
- */
- void ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions );
-
- /**
- * Creates a new buffer which is a crop of the passed in buffer,
- * using the given crop rectangle. Assumes the crop rectangle is
- * within the bounds of this size.
- * @param[in] inBuffer The source buffer
- * @param[in] x The top left corner's X
- * @param[in] y The top left corner's y
- * @param[in] cropDimensions The dimensions of the crop
- * @return the new pixel buffer
- */
- static PixelBufferPtr NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions );
-
- /**
- * Creates a new buffer which is a resized version of the passed in buffer.
- * Uses either Lanczos4 for downscaling, or Mitchell for upscaling.
- * @param[in] inBuffer The source buffer
- * @param[in] outDimensions The new dimensions
- * @return a new buffer of the given size.
- */
- static PixelBufferPtr NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions );
-
-
-private:
-
- std::unique_ptr<Property::Map> mMetadata; ///< Metadata fields
- unsigned char* mBuffer; ///< The raw pixel data
- unsigned int mBufferSize; ///< Buffer sized in bytes
- unsigned int mWidth; ///< Buffer width in pixels
- unsigned int mHeight; ///< Buffer height in pixels
- Pixel::Format mPixelFormat; ///< Pixel format
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-/**
- * Helper methods for public API
- */
-inline Internal::Adaptor::PixelBuffer& GetImplementation( Devel::PixelBuffer& handle )
-{
- DALI_ASSERT_ALWAYS( handle && "handle is empty" );
-
- BaseObject& object = handle.GetBaseObject();
-
- return static_cast<Internal::Adaptor::PixelBuffer&>( object );
-}
-
-inline const Internal::Adaptor::PixelBuffer& GetImplementation( const Devel::PixelBuffer& handle )
-{
- DALI_ASSERT_ALWAYS( handle && "handle is empty" );
-
- const BaseObject& object = handle.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::PixelBuffer&>( object );
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "shared-file.h"
-
-// EXTERNAL INCLUDES
-#include <sys/types.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <sys/file.h>
-#include <sys/mman.h>
-
-#include <cstring>
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-SharedFile* SharedFile::New(const char* filename, int size, bool isSystem)
-{
- SharedFile *sf = NULL;
-
- sf = new SharedFile;
-
- bool opened = sf->OpenFile( filename, size, isSystem );
- if( !opened )
- {
- delete sf;
- sf = NULL;
- }
- return sf;
-}
-
-SharedFile::SharedFile()
-: mFileDescriptor(-1),
- mSize(0),
- mAddress(NULL),
- mFilename()
-{
-}
-
-SharedFile::~SharedFile()
-{
- Close();
-}
-
-void SharedFile::Close()
-{
- if( mAddress != NULL )
- {
- munmap( mAddress, mSize );
- mAddress = NULL;
- }
-
- if( mFileDescriptor >= 0 )
- {
- close( mFileDescriptor );
- mFileDescriptor = -1;
- }
-}
-
-unsigned char* SharedFile::GetAddress()
-{
- return static_cast<unsigned char *>( mAddress );
-}
-
-bool SharedFile::OpenFile(const char* filename, int size, bool isSystem)
-{
- bool opened = false;
- mode_t mode;
-
- mode = S_IRUSR | S_IWUSR;
- if( isSystem )
- {
- mode |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
- }
-
- mFileDescriptor = shm_open( filename, O_RDONLY, mode );
-
- if( mFileDescriptor >= 0 )
- {
- mFilename = filename;
-
- mSize = size;
- mAddress = mmap( NULL, mSize, PROT_READ, MAP_SHARED, mFileDescriptor, 0 );
-
-// MAP_FAILED is a macro with C cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
- if( mAddress != MAP_FAILED )
- {
- opened = true;
- }
-#pragma GCC diagnostic pop
- }
- return opened;
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <singleton-service-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#if defined(DEBUG_ENABLED)
-#include <tizen-logging.h>
-Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" );
-
-// Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction
-#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) \
- if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string ); }
-
-#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )
-
-#else
-
-#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)
-#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)
-
-#endif
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-thread_local SingletonService * gSingletonService = 0;
-} // unnamed namespace
-
-Dali::SingletonService SingletonService::New()
-{
- Dali::SingletonService singletonService( new SingletonService );
- return singletonService;
-}
-
-Dali::SingletonService SingletonService::Get()
-{
- Dali::SingletonService singletonService;
- if ( gSingletonService )
- {
- singletonService = Dali::SingletonService( gSingletonService );
- }
- return singletonService;
-}
-
-void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
-{
- if( singleton )
- {
- DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() );
- mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );
- }
-}
-
-void SingletonService::UnregisterAll( )
-{
- mSingletonContainer.clear();
-}
-
-BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
-{
- BaseHandle object;
-
- const SingletonContainer::const_iterator end = mSingletonContainer.end();
- for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )
- {
- // comparing the addresses as these are allocated statically per library
- if( ( *iter ).first == info.name() )
- {
- object = ( *iter ).second;
- }
- }
-
- return object;
-}
-
-SingletonService::SingletonService()
-: mSingletonContainer()
-{
- // Can only have one instance of SingletonService
- DALI_ASSERT_ALWAYS( !gSingletonService && "Only one instance of SingletonService is allowed");
-
- gSingletonService = this;
-
- DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" );
-}
-
-SingletonService::~SingletonService()
-{
- gSingletonService = 0;
-
- DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_SINGLETON_SERVICE_H__
-#define __DALI_INTERNAL_SINGLETON_SERVICE_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/common/vector-wrapper.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class SingletonService : public Dali::BaseObject
-{
-public:
-
- /**
- * Create a SingletonService.
- * This should only be called once by the Application class.
- * @return A newly created SingletonService.
- */
- static Dali::SingletonService New();
-
- /**
- * @copydoc Dali::SingletonService::Get()
- */
- static Dali::SingletonService Get();
-
- /**
- * @copydoc Dali::SingletonService::Register()
- */
- void Register( const std::type_info& info, BaseHandle singleton );
-
- /**
- * @copydoc Dali::SingletonService::UnregisterAll()
- */
- void UnregisterAll();
-
- /**
- * @copydoc Dali::SingletonService::GetSingleton()
- */
- BaseHandle GetSingleton( const std::type_info& info ) const;
-
-private:
-
- /**
- * Private Constructor
- * @see SingletonService::New()
- */
- SingletonService();
-
- /**
- * Virtual Destructor
- */
- virtual ~SingletonService();
-
- // Undefined
- SingletonService( const SingletonService& );
- SingletonService& operator=( SingletonService& );
-
-private:
-
- // using the address of the type name string as compiler will allocate these once per library
- // and we don't support un/re-loading of dali libraries while singleton service is alive
- typedef std::pair< const char*, BaseHandle> SingletonPair;
- typedef std::vector< SingletonPair > SingletonContainer;
- typedef SingletonContainer::const_iterator SingletonConstIter;
-
- SingletonContainer mSingletonContainer; ///< The container to look up singleton by its type name
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::SingletonService& GetImplementation(Dali::SingletonService& player)
-{
- DALI_ASSERT_ALWAYS( player && "SingletonService handle is empty" );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast<Internal::Adaptor::SingletonService&>(handle);
-}
-
-inline const Internal::Adaptor::SingletonService& GetImplementation(const Dali::SingletonService& player)
-{
- DALI_ASSERT_ALWAYS( player && "SingletonService handle is empty" );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::SingletonService&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_SINGLETON_SERVICE_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <sound-player-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-const char* const SIGNAL_SOUND_PLAY_FINISHED = "soundPlayFinished";
-
-// Type Registration
-Dali::BaseHandle GetInstance()
-{
- return SoundPlayer::Get();
-}
-
-Dali::TypeRegistration SOUND_PLAYER_TYPE( typeid(Dali::SoundPlayer), typeid(Dali::BaseHandle), GetInstance );
-
-Dali::SignalConnectorType SIGNAL_CONNECTOR_1( SOUND_PLAYER_TYPE, SIGNAL_SOUND_PLAY_FINISHED, Dali::Internal::Adaptor::SoundPlayer::DoConnectSignal );
-
-} // unnamed namespace
-
-Dali::SoundPlayer SoundPlayer::New()
-{
- Dali::SoundPlayer player = Dali::SoundPlayer( new SoundPlayer() );
- return player;
-}
-
-Dali::SoundPlayer SoundPlayer::Get()
-{
- Dali::SoundPlayer player;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::SoundPlayer ) );
- if ( handle )
- {
- // If so, downcast the handle
- player = Dali::SoundPlayer( dynamic_cast< SoundPlayer* >( handle.GetObjectPtr() ) );
- }
- else
- {
- player = Dali::SoundPlayer( New() );
- service.Register( typeid( player ), player );
- }
- }
-
- return player;
-}
-
-int SoundPlayer::PlaySound( const std::string fileName )
-{
- return mPlugin.PlaySound( fileName );
-}
-
-void SoundPlayer::Stop( int handle )
-{
- mPlugin.StopSound( handle );
-}
-
-SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal()
-{
- return mSoundPlayFinishedSignal;
-}
-
-bool SoundPlayer::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
-{
- bool connected( true );
- SoundPlayer* player = dynamic_cast<SoundPlayer*>( object );
-
- if( player && ( SIGNAL_SOUND_PLAY_FINISHED == signalName ) )
- {
- player->SoundPlayFinishedSignal().Connect( tracker, functor );
- }
- else
- {
- // signalName does not match any signal
- connected = false;
- }
-
- return connected;
-}
-
-SoundPlayer::SoundPlayer()
-: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME )
-{
-}
-
-SoundPlayer::~SoundPlayer()
-{
-}
-
-void SoundPlayer::EmitSoundPlayFinishedSignal()
-{
- // Emit SoundPlayFinished signal
-
- if ( !mSoundPlayFinishedSignal.Empty() )
- {
- Dali::SoundPlayer handle( this );
- mSoundPlayFinishedSignal.Emit( handle );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_SOUND_PLAYER_H__
-#define __DALI_INTERNAL_SOUND_PLAYER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <sound-player.h>
-#include <feedback/feedback-plugin-proxy.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Plays haptic effects.
- */
-class SoundPlayer : public Dali::BaseObject
-{
-
-public:
-
- typedef Dali::SoundPlayer::SoundPlayFinishedSignalType SoundPlayFinishedSignalType;
-
- /**
- * Create a SoundPlayer.
- * @return A newly created SoundPlayer.
- */
- static Dali::SoundPlayer New();
-
- /**
- * Retrieve a handle to the SoundPlayer. This creates an instance if none has been created.
- * @return A handle to the SoundPlayer.
- */
- static Dali::SoundPlayer Get();
-
- /**
- * @copydoc Dali::SoundPlayer::PlaySound()
- */
- int PlaySound(const std::string fileName);
-
- /**
- * @copydoc Dali::SoundPlayer::Stop()
- */
- void Stop(int handle);
-
- /**
- * @copydoc Dali::SoundPlayer::SoundPlayFinishedSignal()
- */
- SoundPlayFinishedSignalType& SoundPlayFinishedSignal();
-
- /**
- * Connects a callback function with the object's signals.
- * @param[in] object The object providing the signal.
- * @param[in] tracker Used to disconnect the signal.
- * @param[in] signalName The signal to connect to.
- * @param[in] functor A newly allocated FunctorDelegate.
- * @return True if the signal was connected.
- * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
- */
- static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
-
-private:
-
- /**
- * Private Constructor; see also soundPlayer::New()
- * @param[in] soundPlayer The public sound player class
- */
- SoundPlayer();
-
- /**
- * Destructor
- */
- virtual ~SoundPlayer();
-
- /**
- * Emits the SoundPlayFinished signal.
- */
- void EmitSoundPlayFinishedSignal();
-
- // Undefined
- SoundPlayer(const SoundPlayer&);
-
- // Undefined
- SoundPlayer& operator=(SoundPlayer&);
-
-private:
-
- FeedbackPluginProxy mPlugin;
- SoundPlayFinishedSignalType mSoundPlayFinishedSignal;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::SoundPlayer& GetImplementation(Dali::SoundPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast<Internal::Adaptor::SoundPlayer&>(handle);
-}
-
-inline const Internal::Adaptor::SoundPlayer& GetImplementation(const Dali::SoundPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::SoundPlayer&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_SOUND_PLAYER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "style-monitor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <fstream>
-#include <sstream>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_STYLE_MONITOR");
-#endif
-
-/**
- * Use font client to get the system default font family
- * @param[in] fontClient handle to font client
- * @param[out] fontFamily string representing font family
- */
-void GetSystemDefaultFontFamily( TextAbstraction::FontClient& fontClient, std::string& fontFamily )
-{
- TextAbstraction::FontDescription defaultFontDescription;
- if ( fontClient )
- {
- fontClient.GetDefaultPlatformFontDescription( defaultFontDescription );
- fontFamily = defaultFontDescription.family;
- }
-}
-
-} // unnamed namespace
-
-Dali::StyleMonitor StyleMonitor::Get()
-{
- Dali::StyleMonitor styleMonitor;
-
- Dali::SingletonService service( SingletonService::Get() );
- if( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::StyleMonitor ) );
- if( handle )
- {
- // If so, downcast the handle
- styleMonitor = Dali::StyleMonitor( dynamic_cast< StyleMonitor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- styleMonitor = Dali::StyleMonitor( new StyleMonitor() );
- service.Register( typeid( styleMonitor ), styleMonitor );
- }
- }
-
- return styleMonitor;
-}
-
-StyleMonitor::StyleMonitor()
-: mDefaultFontSize(-1)
-{
- mFontClient = TextAbstraction::FontClient::Get();
- GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleMonitor::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() );
- mDefaultFontSize = mFontClient.GetDefaultFontSize();
-}
-
-StyleMonitor::~StyleMonitor()
-{
-}
-
-void StyleMonitor::StyleChanged( StyleChange::Type styleChange )
-{
- switch ( styleChange )
- {
- case StyleChange::DEFAULT_FONT_CHANGE:
- {
- if ( mFontClient )
- {
- mFontClient.ResetSystemDefaults();
- GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily );
- }
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleChanged::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() );
- break;
- }
-
- case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
- {
- mDefaultFontSize = mFontClient.GetDefaultFontSize();
- break;
- }
-
- case StyleChange::THEME_CHANGE:
- {
- break;
- }
- }
-
- EmitStyleChangeSignal(styleChange);
-}
-
-std::string StyleMonitor::GetDefaultFontFamily() const
-{
- return mDefaultFontFamily;
-}
-
-std::string StyleMonitor::GetDefaultFontStyle() const
-{
- return mDefaultFontStyle;
-}
-
-int StyleMonitor::GetDefaultFontSize() const
-{
- return mDefaultFontSize;
-}
-
-const std::string& StyleMonitor::GetTheme() const
-{
- return mUserDefinedThemeFilePath;
-}
-
-void StyleMonitor::SetTheme(const std::string& path)
-{
- mUserDefinedThemeFilePath = path;
- EmitStyleChangeSignal( StyleChange::THEME_CHANGE );
-}
-
-bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
-{
- bool retval( false );
- std::ifstream in( filename.c_str(), std::ios::in );
- if( in )
- {
- std::stringstream buffer;
- buffer << in.rdbuf();
-
- output = buffer.str();
-
- in.close();
- retval = true;
- }
- return retval;
-}
-
-Dali::StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
-{
- return mStyleChangeSignal;
-}
-
-void StyleMonitor::EmitStyleChangeSignal( StyleChange::Type styleChange )
-{
- if( !mStyleChangeSignal.Empty() )
- {
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::EmitStyleChangeSignal\n" );
- Dali::StyleMonitor handle( this );
- mStyleChangeSignal.Emit( handle, styleChange );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_STYLE_MONITOR_H__
-#define __DALI_INTERNAL_STYLE_MONITOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/base-object.h>
-#include <dali/devel-api/text-abstraction/font-client.h>
-
-// INTERNAL INCLUDES
-#include <style-monitor.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * This holds the platform's style information.
- * It provides a signal when any aspect of the default style changes on the device.
- */
-class StyleMonitor : public BaseObject
-{
-public:
-
- // Creation & Destruction
-
- /**
- * Constructor.
- */
- StyleMonitor();
-
- /**
- * Retrieve the initialized instance of the StyleMonitor.
- * @return Handle to StyleMonitor.
- */
- static Dali::StyleMonitor Get();
-
- // Style Change Notifications
-
- /**
- * Informs the Style Monitor that the style has changed.
- * @param[in] styleChange The details of the change.
- */
- void StyleChanged( StyleChange::Type styleChange );
-
- // Style Information
-
- /**
- * @copydoc Dali::StyleMonitor::GetDefaultFontFamily() const
- */
- std::string GetDefaultFontFamily() const;
-
- /**
- * @copydoc Dali::StyleMonitor::GetDefaultFontStyle() const
- */
- std::string GetDefaultFontStyle() const;
-
- /**
- * @copydoc Dali::StyleMonitor::GetDefaultFontSize() const
- */
- int GetDefaultFontSize() const;
-
- /**
- * @copydoc Dali::StyleMonitor::GetTheme() const
- */
- const std::string& GetTheme() const;
-
- /**
- * @copydoc Dali::StyleMonitor::SetTheme()
- */
- void SetTheme(const std::string& themeFilePath);
-
- /**
- * @copydoc Dali::StyleMonitor::LoadThemeFile()
- */
- bool LoadThemeFile( const std::string& filename, std::string& output );
-
- // Signals
-
- /**
- * @copydoc Dali::StyleMonitor::StyleChangeSignal()
- */
- Dali::StyleMonitor::StyleChangeSignalType& StyleChangeSignal();
-
-protected:
-
- /**
- * Virtual Destructor.
- */
- virtual ~StyleMonitor();
-
-private:
-
- /**
- * Emit the style change signal.
- * @param[in] styleChange The details of the style change
- */
- inline void EmitStyleChangeSignal( StyleChange::Type styleChange );
-
-private:
-
- Dali::StyleMonitor::StyleChangeSignalType mStyleChangeSignal; ///< Emitted when the style changes
-
- TextAbstraction::FontClient mFontClient;
- std::string mDefaultFontFamily; ///< The system default font family
- std::string mDefaultFontStyle; ///< The default font style
- std::string mUserDefinedThemeFilePath; ///< String containing the user defined theme file path
- int mDefaultFontSize; ///< The default accessibility font size e.g. 0 is smallest
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Additional Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::StyleMonitor& GetImplementation(Dali::StyleMonitor& monitor)
-{
- DALI_ASSERT_ALWAYS(monitor && "Monitor handle is empty");
- BaseObject& handle = monitor.GetBaseObject();
- return static_cast<Internal::Adaptor::StyleMonitor&>(handle);
-}
-
-inline const Internal::Adaptor::StyleMonitor& GetImplementation(const Dali::StyleMonitor& monitor)
-{
- DALI_ASSERT_ALWAYS(monitor && "Monitor handle is empty");
- const BaseObject& handle = monitor.GetBaseObject();
- return static_cast<const Internal::Adaptor::StyleMonitor&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_STYLE_MONITOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include "system-settings.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-int GetLongPressTime( int defaultTime )
-{
- return defaultTime;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "system-trace.h"
-
-// EXTERNAL HEADERS
-#include <string>
-#include <dali/devel-api/common/hash.h>
-
-// INTERNAL HEADERS
-#include <dali/integration-api/debug.h>
-
-#ifdef ENABLE_TTRACE
-#include <ttrace.h>
-#else
-
-// Emulate trace calls if ttrace isn't available
-namespace
-{
-const int TTRACE_TAG_GRAPHICS = 1;
-
-void traceAsyncBegin(int tag, int cookie, const char *name, ...)
-{
- Debug::LogMessage(Debug::DebugInfo, "AsyncBegin: %s : cookie %d\n", name, cookie );
-}
-void traceAsyncEnd(int tag, int cookie, const char *name, ...)
-{
- Debug::LogMessage(Debug::DebugInfo, "AsyncEnd: %s : cookie %d\n", name, cookie );
-}
-void traceMark(int tag, const char *name, ...)
-{
- Debug::LogMessage(Debug::DebugInfo, "Marker: %s \n", name);
-}
-} // un-named namespace
-#endif
-
-namespace
-{
-
-int GetCookie( const std::string& description, std::string& markerName )
-{
- // description holds the marker name and postfix of _START or _END
- std::size_t pos = description.find("_START");
- if( pos == std::string::npos )
- {
- pos = description.find("_END");
- }
- if( !pos )
- {
- // if this asserts then check the postfix strings in StatContext.cpp for
- // custom markers and performance-marker.cpp for built-in markers
- DALI_ASSERT_DEBUG(0);
- }
- markerName = description.substr( 0, pos );
-
- std::size_t hash = Dali::CalculateHash( markerName.c_str() );
- return static_cast<int>( hash );
-}
-}
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-SystemTrace::SystemTrace()
-{
-}
-SystemTrace::~SystemTrace()
-{
-}
-
-void SystemTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage )
-{
- PerformanceMarker::MarkerEventType eventType = marker.GetEventType();
-
- if( eventType == PerformanceMarker::SINGLE_EVENT )
- {
- traceMark( TTRACE_TAG_GRAPHICS, traceMessage.c_str() );
- return;
- }
-
- // DALi is multi-threaded so timed events will occur asynchronously
- std::string markerName;
-
- int cookie = GetCookie(traceMessage, markerName );
-
- if( eventType == PerformanceMarker::START_TIMED_EVENT )
- {
- traceAsyncBegin( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() );
- }
- else
- {
- traceAsyncEnd( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() );
- }
-}
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
-#define __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <base/interfaces/trace-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Concrete System Tracing Interface.
- * Used to log trace messages to the system using ttrace
- *
- */
-class SystemTrace : public TraceInterface
-{
-public:
-
- /**
- * Constructor
- */
- SystemTrace();
-
- /**
- * Destructor
- */
- virtual ~SystemTrace();
-
- /**
- * @copydoc KernelTracerInterface::KernelTrace()
- */
- virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage );
-
-};
-
-} // namespace Internal
-
-} // namespace Adaptor
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_TIMER_H__
-#define __DALI_INTERNAL_TIMER_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/timer-interface.h>
-#include <timer.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-class Timer;
-
-typedef IntrusivePtr<Timer> TimerPtr;
-
-/**
- * Implementation of the timer
- */
-class Timer : public BaseObject, public TimerInterface
-{
-public:
- static TimerPtr New( unsigned int milliSec );
-
- /**
- * Constructor
- * @param[in] milliSec Interval in milliseconds.
- */
- Timer( unsigned int milliSec );
-
- /**
- * Destructor.
- */
- virtual ~Timer();
-
-public:
-
- /**
- * @copydoc Dali::Timer::Start()
- */
- virtual void Start();
-
- /**
- * @copydoc Dali::Timer::Stop()
- */
- virtual void Stop();
-
- /**
- * @copydoc Dali::Timer::SetInterval()
- */
- virtual void SetInterval( unsigned int interval );
-
- /**
- * @copydoc Dali::Timer::GetInterval()
- */
- virtual unsigned int GetInterval() const;
-
- /**
- * @copydoc Dali::Timer::IsRunning()
- */
- virtual bool IsRunning() const;
-
- /**
- * Tick
- */
- bool Tick();
-
-public: // Signals
-
- Dali::Timer::TimerSignalType& TickSignal();
-
-private: // Implementation
-
- // not implemented
- Timer( const Timer& );
- Timer& operator=( const Timer& );
-
- /**
- * Resets any stored timer data.
- */
- void ResetTimerData();
-
-private: // Data
-
- Dali::Timer::TimerSignalType mTickSignal;
-
- // To hide away implementation details
- struct Impl;
- Impl* mImpl;
-};
-
-inline Timer& GetImplementation(Dali::Timer& timer)
-{
- DALI_ASSERT_ALWAYS(timer && "Timer handle is empty");
-
- BaseObject& handle = timer.GetBaseObject();
-
- return static_cast<Internal::Adaptor::Timer&>(handle);
-}
-
-inline const Timer& GetImplementation(const Dali::Timer& timer)
-{
- DALI_ASSERT_ALWAYS(timer && "Timer handle is empty");
-
- const BaseObject& handle = timer.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::Timer&>(handle);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_TIMER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "trigger-event-factory.h"
-
-// INTERNAL INCLUDES
-#include <trigger-event.h>
-
-namespace Dali
-{
-
-TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options )
-{
- return new Internal::Adaptor::TriggerEvent( callback, options );
-}
-
-void TriggerEventFactory::DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface )
-{
- Internal::Adaptor::TriggerEvent* triggerEvent( static_cast<Internal::Adaptor::TriggerEvent *>(triggerEventInterface) );
- delete triggerEvent;
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "trigger-event.h"
-
-// EXTERNAL INCLUDES
-#include <sys/eventfd.h>
-#include <unistd.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-
-#include <file-descriptor-monitor.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-TriggerEvent::TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options )
-: mFileDescriptorMonitor( NULL ),
- mCallback( callback ),
- mFileDescriptor( -1 ),
- mOptions( options )
-{
- // Create accompanying file descriptor.
- mFileDescriptor = eventfd(0, EFD_NONBLOCK);
- if (mFileDescriptor >= 0)
- {
- // Now Monitor the created event file descriptor
- mFileDescriptorMonitor = new FileDescriptorMonitor( mFileDescriptor, MakeCallback( this, &TriggerEvent::Triggered ), FileDescriptorMonitor::FD_READABLE );
- }
- else
- {
- DALI_LOG_ERROR("Unable to create TriggerEvent File descriptor\n");
- }
-}
-
-TriggerEvent::~TriggerEvent()
-{
- delete mFileDescriptorMonitor;
- delete mCallback;
-
- if (mFileDescriptor >= 0)
- {
- close(mFileDescriptor);
- mFileDescriptor = 0;
- }
-}
-
-void TriggerEvent::Trigger()
-{
- if (mFileDescriptor >= 0)
- {
- // Increment event counter by 1.
- // Writing to the file descriptor triggers the Dispatch() method in the other thread
- // (if in multi-threaded environment).
-
- uint64_t data = 1;
- int size = write(mFileDescriptor, &data, sizeof(uint64_t));
-
- if (size != sizeof(uint64_t))
- {
- DALI_LOG_ERROR("Unable to write to UpdateEvent File descriptor\n");
- }
- }
- else
- {
- DALI_LOG_WARNING("Attempting to write to an invalid file descriptor\n");
- }
-}
-
-void TriggerEvent::Triggered( FileDescriptorMonitor::EventType eventBitMask )
-{
- if( !( eventBitMask & FileDescriptorMonitor::FD_READABLE ) )
- {
- DALI_ASSERT_ALWAYS( 0 && "Trigger event file descriptor error");
- return;
- }
-
- // Reading from the file descriptor resets the event counter, we can ignore the count.
- uint64_t receivedData;
- size_t size;
- size = read(mFileDescriptor, &receivedData, sizeof(uint64_t));
- if (size != sizeof(uint64_t))
- {
- DALI_LOG_WARNING("Unable to read to UpdateEvent File descriptor\n");
- }
-
- // Call the connected callback
- CallbackBase::Execute( *mCallback );
-
- //check if we should delete ourselves after the trigger
- if( mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER )
- {
- delete this;
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_TRIGGER_EVENT_H__
-#define __DALI_INTERNAL_TRIGGER_EVENT_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/signals/callback.h>
-#include <file-descriptor-monitor.h>
-
-// INTERNAL INCLUDES
-#include <trigger-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-
-/**
- * The TriggerEvent class is used to send events between threads. For example, this can be used
- * to wake up one thread from another thread.
- *
- * Typically, these should be created in the application thread.
- *
- * The observer will be informed whenever the event is triggered.
- *
- * The implementation of TriggerEvent uses an event file descriptor.
- */
-class TriggerEvent : public TriggerEventInterface
-{
-public:
-
- /**
- * Constructor
- * Creates an event file descriptor and starts a GSource which reads from the file
- * descriptor when there is data.
- *
- * @param[in] callback The callback to call
- * @param[in] options Trigger event options.
- * @note The ownership of callback is taken by this class.
- */
- TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options );
-
- /**
- * Destructor
- */
- ~TriggerEvent();
-
-public:
-
- /**
- * Triggers the event.
- *
- * This can be called from one thread in order to wake up another thread.
- */
- void Trigger();
-
-private:
-
- /**
- * @brief Called when our event file descriptor has been written to.
- * @param[in] eventBitMask bit mask of events that occured on the file descriptor
- */
- void Triggered( FileDescriptorMonitor::EventType eventBitMask );
-
-private:
-
- struct Source;
-
-private:
-
- FileDescriptorMonitor* mFileDescriptorMonitor;
- CallbackBase* mCallback;
- int mFileDescriptor;
- TriggerEventInterface::Options mOptions;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_TRIGGER_EVENT_H__
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <video-player-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dlfcn.h>
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/any.h>
-
-// INTERNAL INCLUDES
-#include <native-image-source.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-#if _GLIBCXX_USE_CXX11_ABI
-const char* VIDEO_PLUGIN_SO( "libdali-video-player-plugin.so" );
-#else
-const char* VIDEO_PLUGIN_SO( "libdali-video-player-plugin-cxx03.so" );
-#endif
-
-Dali::BaseHandle Create()
-{
- return Dali::VideoPlayer::New();
-}
-
-Dali::TypeRegistration type( typeid( Dali::VideoPlayer ), typeid( Dali::BaseHandle ), Create );
-
-} // unnamed namespace
-
-VideoPlayerPtr VideoPlayer::New()
-{
- VideoPlayerPtr player = new VideoPlayer();
- return player;
-}
-
-VideoPlayer::VideoPlayer()
-: mPlugin( NULL ),
- mHandle( NULL ),
- mCreateVideoPlayerPtr( NULL ),
- mDestroyVideoPlayerPtr( NULL )
-{
-}
-
-VideoPlayer::~VideoPlayer()
-{
- if( mHandle != NULL )
- {
- if( mDestroyVideoPlayerPtr != NULL )
- {
- mDestroyVideoPlayerPtr( mPlugin );
- }
-
- dlclose( mHandle );
- }
-}
-
-void VideoPlayer::Initialize()
-{
- char* error = NULL;
-
- mHandle = dlopen( VIDEO_PLUGIN_SO, RTLD_LAZY );
-
- error = dlerror();
- if( mHandle == NULL || error != NULL )
- {
- DALI_LOG_ERROR( "VideoPlayer::Initialize(), dlopen error: %s\n", error );
- return;
- }
-
- mCreateVideoPlayerPtr = reinterpret_cast< CreateVideoPlayerFunction >( dlsym( mHandle, "CreateVideoPlayerPlugin" ) );
- if( mCreateVideoPlayerPtr == NULL )
- {
- DALI_LOG_ERROR( "Can't load symbol CreateVideoPlayerPlugin(), error: %s\n", error );
- return;
- }
-
- mPlugin = mCreateVideoPlayerPtr();
-
- if( mPlugin == NULL )
- {
- DALI_LOG_ERROR( "Can't create the VideoPlayerPlugin object\n" );
- return;
- }
-
- mDestroyVideoPlayerPtr = reinterpret_cast< DestroyVideoPlayerFunction >( dlsym( mHandle, "DestroyVideoPlayerPlugin" ) );
- if( mDestroyVideoPlayerPtr == NULL )
- {
- DALI_LOG_ERROR( "Can't load symbol DestroyVideoPlayerPlugin(), error: %s\n", error );
- return;
- }
-
-}
-
-void VideoPlayer::SetUrl( const std::string& url )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetUrl( url );
- }
-}
-
-std::string VideoPlayer::GetUrl()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->GetUrl();
- }
-
- return std::string();
-}
-
-void VideoPlayer::SetLooping(bool looping)
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetLooping( looping );
- }
-}
-
-bool VideoPlayer::IsLooping()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->IsLooping();
- }
-
- return false;
-}
-
-void VideoPlayer::Play()
-{
- if( mPlugin != NULL )
- {
- mPlugin->Play();
- }
-}
-
-void VideoPlayer::Pause()
-{
- if( mPlugin != NULL )
- {
- mPlugin->Pause();
- }
-}
-
-void VideoPlayer::Stop()
-{
- if( mPlugin != NULL )
- {
- mPlugin->Stop();
- }
-}
-
-void VideoPlayer::SetMute( bool mute )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetMute( mute );
- }
-}
-
-bool VideoPlayer::IsMuted()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->IsMuted();
- }
-
- return false;
-}
-
-void VideoPlayer::SetVolume( float left, float right )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetVolume( left, right );
- }
-}
-
-void VideoPlayer::GetVolume( float& left, float& right )
-{
- if( mPlugin != NULL )
- {
- mPlugin->GetVolume( left, right );
- }
-}
-
-void VideoPlayer::SetRenderingTarget( Dali::Any target )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetRenderingTarget( target );
- }
-}
-
-void VideoPlayer::SetPlayPosition( int millisecond )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetPlayPosition( millisecond );
- }
-}
-
-int VideoPlayer::GetPlayPosition()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->GetPlayPosition();
- }
- return 0;
-}
-
-void VideoPlayer::SetDisplayArea( DisplayArea area )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetDisplayArea( area );
- }
-}
-
-void VideoPlayer::SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation )
-{
- if( mPlugin != NULL )
- {
- mPlugin->SetDisplayRotation( rotation );
- }
-}
-
-Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->GetDisplayRotation();
- }
-
- return Dali::VideoPlayerPlugin::ROTATION_NONE;
-}
-
-Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal()
-{
- if( mPlugin != NULL )
- {
- return mPlugin->FinishedSignal();
- }
-
- return mFinishedSignal;
-}
-
-void VideoPlayer::Forward( int millisecond )
-{
- if( mPlugin != NULL )
- {
- mPlugin->Forward( millisecond );
- }
-}
-
-void VideoPlayer::Backward( int millisecond )
-{
- if( mPlugin != NULL )
- {
- mPlugin->Backward( millisecond );
- }
-}
-
-bool VideoPlayer::IsVideoTextureSupported() const
-{
- if( mPlugin != NULL )
- {
- return mPlugin->IsVideoTextureSupported();
- }
-
- return false;
-}
-
-} // namespace Adaptor;
-} // namespace Internal;
-} // namespace Dali;
-
+++ /dev/null
-#ifndef __DALI_VIDEO_PLAYER_IMPL_H__
-#define __DALI_VIDEO_PLAYER_IMPL_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <video-player.h>
-#include <video-player-plugin.h>
-
-namespace Dali
-{
-class Any;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class VideoPlayer;
-
-typedef IntrusivePtr< VideoPlayer > VideoPlayerPtr;
-
-/**
- * @brief VideoPlayer class is used for video playback.
- * @SINCE_1_1.24
- */
-class VideoPlayer: public Dali::BaseObject
-{
-public:
-
- /**
- * @brief Creates a new VideoPlayer handle
- * @SINCE_1_1.24
- * @return VideoPlayer pointer
- */
- static VideoPlayerPtr New();
-
- /**
- * @copydoc Dali::VideoPlayer::SetUrl()
- */
- void SetUrl( const std::string& url );
-
- /**
- * @copydoc Dali::VideoPlayer::GetUrl()
- */
- std::string GetUrl();
-
- /**
- * @copydoc Dali::VideoPlayer::SetLooping()
- */
- void SetLooping(bool looping);
-
- /**
- * @copydoc Dali::VideoPlayer::IsLooping()
- */
- bool IsLooping();
-
- /**
- * @copydoc Dali::VideoPlayer::Play()
- */
- void Play();
-
- /**
- * @copydoc Dali::VideoPlayer::Pause()
- */
- void Pause();
-
- /**
- * @copydoc Dali::VideoPlayer::Stop()
- */
- void Stop();
-
- /**
- * @copydoc Dali::VideoPlayer::SetMute()
- */
- void SetMute( bool mute );
-
- /**
- * @copydoc Dali::VideoPlayer::IsMuted()
- */
- bool IsMuted();
-
- /**
- * @copydoc Dali::VideoPlayer::SetVolume()
- */
- void SetVolume( float left, float right );
-
- /**
- * @copydoc Dali::VideoPlayer::GetVolume()
- */
- void GetVolume( float& left, float& right );
-
- /**
- * @copydoc Dali::VideoPlayer::SetRenderingTarget()
- */
- void SetRenderingTarget( Dali::Any target );
-
- /**
- * @copydoc Dali::VideoPlayer::SetPlayPosition()
- */
- void SetPlayPosition( int millisecond );
-
- /**
- * @copydoc Dali::VideoPlayer::GetPlayPosition()
- */
- int GetPlayPosition();
-
- /**
- * @copydoc Dali::VideoPlayer::SetDisplayArea()
- */
- void SetDisplayArea( DisplayArea area );
-
- /**
- * @copydoc Dali::VideoPlayer::SetSetDisplayRotation()
- */
- void SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation );
-
- /**
- * @copydoc Dali::VideoPlayer::GetDisplayRotation()
- */
- Dali::VideoPlayerPlugin::DisplayRotation GetDisplayRotation();
-
- /**
- * @copydoc Dali::VideoPlayer::FinishedSignal()
- */
- Dali::VideoPlayerPlugin::VideoPlayerSignalType& FinishedSignal();
-
- /**
- * @brief Initializes member data.
- */
- void Initialize();
-
- /**
- * @brief Dali::VideoPlayer::Forward()
- */
- void Forward( int millisecond );
-
- /**
- * @brief Dali::VideoPlayer::Backward()
- */
- void Backward( int millisecond );
-
- /**
- * @brief Dali::VideoPlayer::IsVideoTextureSupported()
- */
- bool IsVideoTextureSupported() const;
-
-private:
-
- /**
- * @brief Constructor.
- * @SINCE_1_1.24
- */
- VideoPlayer();
-
- /**
- * @brief Destructor.
- * @SINCE_1_1.24
- */
- virtual ~VideoPlayer();
-
- // Undefined copy constructor
- VideoPlayer( const VideoPlayer& player );
-
- // Undefined assignment operator
- VideoPlayer& operator=( const VideoPlayer& player );
-
-private:
-
- Dali::VideoPlayerPlugin* mPlugin; ///< Videoplayer plugin handle
- void* mHandle; ///< Handle for the loaded library
-
- typedef Dali::VideoPlayerPlugin* (*CreateVideoPlayerFunction)();
- typedef void (*DestroyVideoPlayerFunction)( Dali::VideoPlayerPlugin* plugin );
-
- CreateVideoPlayerFunction mCreateVideoPlayerPtr;
- DestroyVideoPlayerFunction mDestroyVideoPlayerPtr;
-
- Dali::VideoPlayerPlugin::VideoPlayerSignalType mFinishedSignal;
-};
-
-} // namespace Adaptor
-} // namespace Internal
-
-inline static Internal::Adaptor::VideoPlayer& GetImplementation( Dali::VideoPlayer& player )
-{
- DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast< Internal::Adaptor::VideoPlayer& >( handle );
-}
-
-inline static const Internal::Adaptor::VideoPlayer& GetImplementation( const Dali::VideoPlayer& player )
-{
- DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast< const Internal::Adaptor::VideoPlayer& >( handle );
-}
-
-} // namespace Dali;
-
-#endif
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
-#define __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <virtual-keyboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Implementation of the virtual keyboard namespace
- */
-namespace VirtualKeyboard
-{
-
-/**
- * @copydoc Dali::VirtualKeyboard::Show()
- */
-void Show();
-
-/**
- * @copydoc Dali::VirtualKeyboard::Hide()
- */
-void Hide();
-
-/**
- * @copydoc Dali::VirtualKeyboard::IsVisible()
- */
-bool IsVisible();
-
-/**
- * @copydoc Dali::VirtualKeyboard::ApplySettings()
- */
-void ApplySettings( const Property::Map& settingsMap );
-
-/**
- * @copydoc Dali::VirtualKeyboard::SetReturnKeyType()
- */
-void SetReturnKeyType( const Dali::InputMethod::ActionButton type );
-
-/**
- * @copydoc Dali::VirtualKeyboard::GetReturnKeyType()
- */
-Dali::InputMethod::ActionButton GetReturnKeyType();
-
-/**
- * @copydoc Dali::VirtualKeyboard::EnablePrediction()
- */
-void EnablePrediction(const bool enable);
-
-/**
- * @copydoc Dali::VirtualKeyboard::IsPredictionEnabled()
- */
-bool IsPredictionEnabled();
-
-/**
- * @copydoc Dali::VirtualKeyboard::GetSizeAndPosition()
- */
-Rect<int> GetSizeAndPosition();
-
-/**
- * @copydoc Dali::VirtualKeyboard::RotateKeyboard()
- */
-void RotateTo(int angle);
-
-/**
- * @copydox Dali::VirtualKeyboard::StatusChangedSignal()
- */
-Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal();
-
-/**
- * @copydox Dali::VirtualKeyboard::ResizedSignal()
- */
-Dali::VirtualKeyboard::KeyboardResizedSignalType& ResizedSignal();
-
-/**
- * @copydox Dali::VirtualKeyboard::LanguageChangedSignal()
- */
-Dali::VirtualKeyboard::LanguageChangedSignalType& LanguageChangedSignal();
-
-/**
- * @copydoc Dali::VirtualKeyboard::GetTextDirection
- */
-Dali::VirtualKeyboard::TextDirection GetTextDirection();
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
-#define __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <xf86drm.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/vsync-monitor-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Tizen interface for monitoring VSync
- */
-class VSyncMonitor : public VSyncMonitorInterface
-{
-public:
- /**
- * Default constructor
- */
- VSyncMonitor();
-
- /**
- * Destructor
- */
- virtual ~VSyncMonitor();
-
-public:
-
- /**
- * Set the use hardware flag
- * @param[in] useHardware The new state for the use hardware flag.
- */
- void SetUseHardwareVSync( bool useHardware );
-
- /**
- * Set whether the vsync hardware is available.
- * (This is public to allow callback method to work...)
- */
- void SetHardwareVSyncAvailable(bool available);
-
-private: // From Dali::Internal::Adaptor::VSyncMonitorInterface
-
- /**
- * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::Initialize
- */
- virtual void Initialize();
-
- /**
- * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::Terminate
- */
- virtual void Terminate();
-
- /**
- * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::UseHardware
- */
- virtual bool UseHardware();
-
- /**
- * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::DoSync
- */
- virtual bool DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds );
-
-private:
-
- int mFileDescriptor; ///< DRM dev node file descriptor
- drmVBlank mVBlankInfo;
- // NOTE cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
- unsigned int mUseHardwareVSync; ///< Whether to use hardware vsync
- unsigned int mHardwareVSyncAvailable; ///< Whether hardware vsync is available
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_WINDOW_H__
-#define __DALI_INTERNAL_WINDOW_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <base/lifecycle-observer.h>
-#include <base/interfaces/indicator-interface.h>
-#include <adaptor-impl.h>
-#include <window.h>
-#include <orientation.h>
-#include <render-surface.h>
-#include <drag-and-drop-detector.h>
-
-namespace Dali
-{
-class Adaptor;
-class RenderSurface;
-
-namespace Integration
-{
-class SystemOverlay;
-}
-
-namespace Internal
-{
-namespace Adaptor
-{
-class Orientation;
-
-class Window;
-typedef IntrusivePtr<Window> WindowPtr;
-typedef IntrusivePtr<Orientation> OrientationPtr;
-
-/**
- * Window provides a surface to render onto with orientation & indicator properties.
- */
-class Window : public Dali::BaseObject, public IndicatorInterface::Observer, public LifeCycleObserver
-{
-public:
- typedef Dali::Window::IndicatorSignalType IndicatorSignalType;
- typedef Dali::Window::FocusSignalType FocusSignalType;
- typedef Dali::Window::ResizedSignalType ResizedSignalType;
- typedef Signal< void () > SignalType;
-
- /**
- * Create a new Window. This should only be called once by the Application class
- * @param[in] positionSize The position and size of the window
- * @param[in] name The window title
- * @param[in] className The window class name
- * @param[in] isTransparent Whether window is transparent
- * @return A newly allocated Window
- */
- static Window* New(const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent = false);
-
- /**
- * Pass the adaptor back to the overlay. This allows the window to access Core's overlay.
- * @param[in] adaptor An initialized adaptor
- */
- void SetAdaptor(Dali::Adaptor& adaptor);
-
- /**
- * Get the window surface
- * @return The render surface
- */
- RenderSurface* GetSurface();
-
- /**
- * @copydoc Dali::Window::ShowIndicator()
- */
- void ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode );
-
- /**
- * @copydoc Dali::Window::SetIndicatorBgOpacity()
- */
- void SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacity );
-
- /**
- * @copydoc Dali::Window::RotateIndicator()
- */
- void RotateIndicator( Dali::Window::WindowOrientation orientation );
-
- /**
- * @copydoc Dali::Window::SetClass()
- */
- void SetClass( std::string name, std::string klass );
-
- /**
- * @copydoc Dali::Window::Raise()
- */
- void Raise();
-
- /**
- * @copydoc Dali::Window::Lower()
- */
- void Lower();
-
- /**
- * @copydoc Dali::Window::Activate()
- */
- void Activate();
-
- /**
- * @copydoc Dali::Window::AddAvailableOrientation()
- */
- void AddAvailableOrientation(Dali::Window::WindowOrientation orientation);
-
- /**
- * @copydoc Dali::Window::RemoveAvailableOrientation()
- */
- void RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation);
-
- /**
- * @copydoc Dali::Window::SetAvailableOrientations()
- */
- void SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations);
-
- /**
- * @copydoc Dali::Window::GetAvailableOrientations()
- */
- const std::vector<Dali::Window::WindowOrientation>& GetAvailableOrientations();
-
- /**
- * @copydoc Dali::Window::SetPreferredOrientation()
- */
- void SetPreferredOrientation(Dali::Window::WindowOrientation orientation);
-
- /**
- * @copydoc Dali::Window::GetPreferredOrientation()
- */
- Dali::Window::WindowOrientation GetPreferredOrientation();
-
- /**
- * @copydoc Dali::Window::GetDragAndDropDetector() const
- */
- Dali::DragAndDropDetector GetDragAndDropDetector() const;
-
- /**
- * @copydoc Dali::Window::GetNativeHandle() const
- */
- Dali::Any GetNativeHandle() const;
-
- /**
- * @copydoc Dali::Window::SetAcceptFocus()
- */
- void SetAcceptFocus( bool accept );
-
- /**
- * @copydoc Dali::Window::IsFocusAcceptable()
- */
- bool IsFocusAcceptable() const;
-
- /**
- * @copydoc Dali::Window::Show()
- */
- void Show();
-
- /**
- * @copydoc Dali::Window::Hide()
- */
- void Hide();
-
- /**
- * @copydoc Dali::Window::IsVisible() const
- */
- bool IsVisible() const;
-
- /**
- * @copydoc Dali::Window::GetSupportedAuxiliaryHintCount()
- */
- unsigned int GetSupportedAuxiliaryHintCount() const;
-
- /**
- * @copydoc Dali::Window::GetSupportedAuxiliaryHint()
- */
- std::string GetSupportedAuxiliaryHint( unsigned int index ) const;
-
- /**
- * @copydoc Dali::Window::AddAuxiliaryHint()
- */
- unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value );
-
- /**
- * @copydoc Dali::Window::RemoveAuxiliaryHint()
- */
- bool RemoveAuxiliaryHint( unsigned int id );
-
- /**
- * @copydoc Dali::Window::SetAuxiliaryHintValue()
- */
- bool SetAuxiliaryHintValue( unsigned int id, const std::string& value );
-
- /**
- * @copydoc Dali::Window::GetAuxiliaryHintValue()
- */
- std::string GetAuxiliaryHintValue( unsigned int id ) const;
-
- /**
- * @copydoc Dali::Window::GetAuxiliaryHintId()
- */
- unsigned int GetAuxiliaryHintId( const std::string& hint ) const;
-
- /**
- * @copydoc Dali::Window::SetInputRegion()
- */
- void SetInputRegion( const Rect< int >& inputRegion );
-
- /**
- * @copydoc Dali::Window::SetType()
- */
- void SetType( Dali::Window::Type type );
-
- /**
- * @copydoc Dali::Window::GetType() const
- */
- Dali::Window::Type GetType() const;
-
- /**
- * @copydoc Dali::Window::SetNotificationLevel()
- */
- bool SetNotificationLevel( Dali::Window::NotificationLevel::Type level );
-
- /**
- * @copydoc Dali::Window::GetNotificationLevel()
- */
- Dali::Window::NotificationLevel::Type GetNotificationLevel() const;
-
- /**
- * @copydoc Dali::Window::SetOpaqueState()
- */
- void SetOpaqueState( bool opaque );
-
- /**
- * @copydoc Dali::Window::IsOpaqueState()
- */
- bool IsOpaqueState() const;
-
- /**
- * @copydoc Dali::Window::SetScreenOffMode()
- */
- bool SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode);
-
- /**
- * @copydoc Dali::Window::GetScreenOffMode()
- */
- Dali::Window::ScreenOffMode::Type GetScreenOffMode() const;
-
- /**
- * @copydoc Dali::Window::SetBrightness()
- */
- bool SetBrightness( int brightness );
-
- /**
- * @copydoc Dali::Window::GetBrightness()
- */
- int GetBrightness() const;
-
- /**
- * @copydoc Dali::Window::SetSize()
- */
- void SetSize( Dali::Window::WindowSize size );
-
- /**
- * @copydoc Dali::Window::GetSize()
- */
- Dali::Window::WindowSize GetSize() const;
-
- /**
- * @copydoc Dali::Window::SetPosition()
- */
- void SetPosition( Dali::Window::WindowPosition position );
-
- /**
- * @copydoc Dali::Window::GetPosition()
- */
- Dali::Window::WindowPosition GetPosition() const;
-
- /**
- * @copydoc Dali::Window::SetTransparency()
- */
- void SetTransparency( bool transparent );
-
- /**
- * Called from Orientation after the Change signal has been sent
- */
- void RotationDone( int orientation, int width, int height );
-
- /**
- * Set the indicator visible mode
- */
- void SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode );
-
-private:
- /**
- * Private constructor.
- * @sa Window::New()
- */
- Window();
-
- /**
- * Destructor
- */
- virtual ~Window();
-
- /**
- * Second stage initialization
- */
- void Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className);
-
- /**
- * Shows / hides the indicator bar.
- * Handles close/open if rotation changes whilst hidden
- */
- void DoShowIndicator( Dali::Window::WindowOrientation lastOrientation );
-
- /**
- * Close current indicator and open a connection onto the new indicator service.
- * Effect may not be synchronous if waiting for an indicator update on existing connection.
- */
- void DoRotateIndicator( Dali::Window::WindowOrientation orientation );
-
- /**
- * Change the indicator actor's rotation to match the current orientation
- */
- void SetIndicatorActorRotation();
-
- /**
- * Set the indicator properties on the window
- */
- void SetIndicatorProperties( bool isShown, Dali::Window::WindowOrientation lastOrientation );
-
-private: // IndicatorInterface::Observer interface
-
- /**
- * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorTypeChanged()
- */
- virtual void IndicatorTypeChanged( IndicatorInterface::Type type );
-
- /**
- * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorClosed()
- */
- virtual void IndicatorClosed( IndicatorInterface* indicator);
-
- /**
- * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorVisibilityChanged()
- */
- virtual void IndicatorVisibilityChanged( bool isVisible );
-
-private: // Adaptor::Observer interface
-
- /**
- * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnStart()
- */
- virtual void OnStart();
-
- /**
- * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnPause()
- */
- virtual void OnPause();
-
- /**
- * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnResume()
- */
- virtual void OnResume();
-
- /**
- * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnStop()
- */
- virtual void OnStop();
-
- /**
- * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnDestroy()
- */
- virtual void OnDestroy();
-
-public: // Signals
-
- /**
- * The user should connect to this signal to get a timing when indicator was shown / hidden.
- */
- IndicatorSignalType& IndicatorVisibilityChangedSignal() { return mIndicatorVisibilityChangedSignal; }
-
- /**
- * @copydoc Dali::Window::FocusChangedSignal()
- */
- FocusSignalType& FocusChangedSignal() { return mFocusChangedSignal; }
-
- /**
- * @copydoc Dali::Window::ResizedSignal()
- */
- ResizedSignalType& ResizedSignal() { return mResizedSignal; }
-
- /**
- * This signal is emitted when the window is requesting to be deleted
- */
- SignalType& DeleteRequestSignal() { return mDeleteRequestSignal; }
-
-private:
-
- typedef std::vector< std::pair< std::string, std::string > > AuxiliaryHints;
-
- RenderSurface* mSurface;
- Dali::Window::IndicatorVisibleMode mIndicatorVisible; ///< public state
- bool mIndicatorIsShown:1; ///< private state
- bool mShowRotatedIndicatorOnClose:1;
- bool mStarted:1;
- bool mIsTransparent:1;
- bool mWMRotationAppSet:1;
- bool mEcoreEventHander:1;
- bool mIsFocusAcceptable:1;
- bool mVisible:1;
- bool mIconified:1;
- bool mOpaqueState:1;
- bool mResizeEnabled:1;
- IndicatorInterface* mIndicator;
- Dali::Window::WindowOrientation mIndicatorOrientation;
- Dali::Window::WindowOrientation mNextIndicatorOrientation;
- Dali::Window::IndicatorBgOpacity mIndicatorOpacityMode;
- Integration::SystemOverlay* mOverlay;
- Adaptor* mAdaptor;
- Dali::DragAndDropDetector mDragAndDropDetector;
- Dali::Window::Type mType;
-
- struct EventHandler;
- EventHandler* mEventHandler;
-
- OrientationPtr mOrientation;
- std::vector<Dali::Window::WindowOrientation> mAvailableOrientations;
- Dali::Window::WindowOrientation mPreferredOrientation;
-
- std::vector< std::string > mSupportedAuxiliaryHints;
- AuxiliaryHints mAuxiliaryHints;
-
- // Signals
- IndicatorSignalType mIndicatorVisibilityChangedSignal;
- FocusSignalType mFocusChangedSignal;
- ResizedSignalType mResizedSignal;
- SignalType mDeleteRequestSignal;
-};
-
-} // namespace Adaptor
-} // namepsace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::Window& GetImplementation(Dali::Window& window)
-{
- DALI_ASSERT_ALWAYS( window && "Window handle is empty" );
- BaseObject& object = window.GetBaseObject();
- return static_cast<Internal::Adaptor::Window&>(object);
-}
-
-inline const Internal::Adaptor::Window& GetImplementation(const Dali::Window& window)
-{
- DALI_ASSERT_ALWAYS( window && "Window handle is empty" );
- const BaseObject& object = window.GetBaseObject();
- return static_cast<const Internal::Adaptor::Window&>(object);
-}
-
-} // namespace Dali
-
-
-#endif // __DALI_INTERNAL_WINDOW_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <accessibility-adaptor.h>
-
-// INTERNAL INCLUDES
-#include <accessibility-adaptor-impl.h>
-
-namespace Dali
-{
-
-AccessibilityAdaptor::AccessibilityAdaptor()
-{
-}
-
-AccessibilityAdaptor AccessibilityAdaptor::Get()
-{
- return Internal::Adaptor::AccessibilityAdaptor::Get();
-}
-
-AccessibilityAdaptor::~AccessibilityAdaptor()
-{
-}
-
-Vector2 AccessibilityAdaptor::GetReadPosition() const
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).GetReadPosition();
-}
-
-bool AccessibilityAdaptor::IsEnabled() const
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).IsEnabled();
-}
-
-void AccessibilityAdaptor::SetActionHandler(AccessibilityActionHandler& handler)
-{
- Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).SetActionHandler(handler);
-}
-
-void AccessibilityAdaptor::SetGestureHandler(AccessibilityGestureHandler& handler)
-{
- Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).SetGestureHandler(handler);
-}
-
-bool AccessibilityAdaptor::HandleActionNextEvent(bool allowEndFeedback)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionNextEvent(allowEndFeedback);
-}
-
-bool AccessibilityAdaptor::HandleActionPreviousEvent(bool allowEndFeedback)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPreviousEvent(allowEndFeedback);
-}
-
-bool AccessibilityAdaptor::HandleActionActivateEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionActivateEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadEvent(x, y, allowReadAgain);
-}
-
-bool AccessibilityAdaptor::HandleActionReadNextEvent(bool allowEndFeedback)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadNextEvent(allowEndFeedback);
-}
-
-bool AccessibilityAdaptor::HandleActionReadPreviousEvent(bool allowEndFeedback)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadPreviousEvent(allowEndFeedback);
-}
-
-bool AccessibilityAdaptor::HandleActionUpEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionUpEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionDownEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionDownEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionClearFocusEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionClearFocusEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollEvent(point, timeStamp);
-}
-
-bool AccessibilityAdaptor::HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp)
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionTouchEvent(point, timeStamp);
-}
-
-bool AccessibilityAdaptor::HandleActionBackEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionBackEvent();
-}
-
-void AccessibilityAdaptor::HandleActionEnableEvent()
-{
- Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionEnableEvent();
-}
-
-void AccessibilityAdaptor::HandleActionDisableEvent()
-{
- Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionDisableEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionScrollUpEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollUpEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionScrollDownEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollDownEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionPageLeftEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageLeftEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionPageRightEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageRightEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionPageUpEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageUpEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionPageDownEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageDownEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionMoveToFirstEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionMoveToFirstEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionMoveToLastEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionMoveToLastEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionReadFromTopEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadFromTopEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionReadFromNextEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadFromNextEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionZoomEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionZoomEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadIndicatorInformationEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadPauseResumeEvent();
-}
-
-bool AccessibilityAdaptor::HandleActionStartStopEvent()
-{
- return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionStartStopEvent();
-}
-
-AccessibilityAdaptor::AccessibilityAdaptor( Internal::Adaptor::AccessibilityAdaptor& manager )
-: BaseHandle( &manager )
-{
-}
-
-AccessibilityAdaptor::AccessibilityAdaptor( Internal::Adaptor::AccessibilityAdaptor* manager )
-: BaseHandle( manager )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <adaptors/devel-api/adaptor-framework/application-devel.h>
-#include <adaptors/common/application-impl.h>
-
-namespace Dali
-{
-
-namespace DevelApplication
-{
-
-void PreInitialize( int* argc, char** argv[] )
-{
- Internal::Adaptor::Application::PreInitialize( argc, argv );
-}
-
-} // namespace DevelApplication
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_APPLICATION_DEVEL_H
-#define DALI_APPLICATION_DEVEL_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-#include <application.h>
-#else
-#include <dali/public-api/adaptor-framework/application.h>
-#endif
-
-namespace Dali
-{
-
-namespace DevelApplication
-{
-/**
- * @brief This is used to improve application launch performance.
- * It preloads so files, initializes some functions in advance and makes a window in advance.
- *
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- */
-DALI_IMPORT_API void PreInitialize( int* argc, char** argv[] );
-
-} // namespace DevelApplication
-
-} // namespace Dali
-
-#endif // DALI_APPLICATION_DEVEL_H
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "application-extensions.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <application-impl.h>
-#include <application.h>
-
-namespace Dali
-{
-
-ApplicationExtensions::ApplicationExtensions()
-: mApplication( NULL )
-{
-}
-
-ApplicationExtensions::ApplicationExtensions(Dali::Application* application)
-: mApplication( application )
-{
-}
-
-ApplicationExtensions::~ApplicationExtensions()
-{
-}
-
-void ApplicationExtensions::Init()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoInit();
-}
-
-void ApplicationExtensions::Start()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoStart();
-}
-
-void ApplicationExtensions::Terminate()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoTerminate();
-}
-
-void ApplicationExtensions::Pause()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoPause();
-}
-
-void ApplicationExtensions::Resume()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoResume();
-}
-
-void ApplicationExtensions::LanguageChange()
-{
- Internal::Adaptor::GetImplementation(*mApplication).DoLanguageChange();
-}
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "bitmap-saver.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <platform-abstractions/tizen/image-loaders/loader-jpeg.h>
-#include <platform-abstractions/tizen/image-loaders/loader-png.h>
-#include <platform-abstractions/tizen/tizen-platform-abstraction.h>
-#include <image-encoder.h>
-
-
-namespace Dali
-{
-
-// Pieces needed to save compressed images (temporary location while plumbing):
-namespace
-{
-
-/**
- * Simple function to tell intended image file format from filename
- */
-FileFormat GetFormatFromFileName( const std::string& filename )
-{
- if (filename.length() < 5)
- {
- DALI_LOG_WARNING("Invalid (short) filename.\n");
- }
- FileFormat format(INVALID_FORMAT);
-
- const std::size_t filenameSize = filename.length();
-
- if(filenameSize >= 4){ // Avoid throwing out_of_range or failing silently if exceptions are turned-off on the compare(). (http://www.cplusplus.com/reference/string/string/compare/)
- if( !filename.compare( filenameSize - 4, 4, ".jpg" )
- || !filename.compare( filenameSize - 4, 4, ".JPG" ) )
- {
- format = JPG_FORMAT;
- }
- else if( !filename.compare( filenameSize - 4, 4, ".png" )
- || !filename.compare( filenameSize - 4, 4, ".PNG" ) )
- {
- format = PNG_FORMAT;
- }
- else if( !filename.compare( filenameSize - 4, 4, ".bmp" )
- || !filename.compare( filenameSize - 4, 4, ".BMP" ) )
- {
- format = BMP_FORMAT;
- }
- else if( !filename.compare( filenameSize - 4, 4, ".gif" )
- || !filename.compare( filenameSize - 4, 4, ".GIF" ) )
- {
- format = GIF_FORMAT;
- }
- else if( !filename.compare( filenameSize - 4, 4, ".ico" )
- || !filename.compare( filenameSize - 4, 4, ".ICO" ) )
- {
- format = ICO_FORMAT;
- }
- else if(filenameSize >= 5){
- if( !filename.compare( filenameSize - 5, 5, ".jpeg" )
- || !filename.compare( filenameSize - 5, 5, ".JPEG" ) )
- {
- format = JPG_FORMAT;
- }
- }
- }
-
- return format;
-}
-
-bool EncodeToFormat( const unsigned char* pixelBuffer,
- Vector< unsigned char >& encodedPixels,
- FileFormat formatEncoding,
- std::size_t width,
- std::size_t height,
- Pixel::Format pixelFormat )
-{
- switch( formatEncoding )
- {
- case JPG_FORMAT:
- {
- return TizenPlatform::EncodeToJpeg( pixelBuffer, encodedPixels, width, height, pixelFormat );
- break;
- }
- case PNG_FORMAT:
- {
- return TizenPlatform::EncodeToPng( pixelBuffer, encodedPixels, width, height, pixelFormat );
- break;
- }
- default:
- {
- DALI_LOG_ERROR("Format not supported for image encoding (supported formats are PNG and JPEG)\n");
- break;
- }
- }
- return false;
-}
-} // anonymous namespace
-
-
-bool EncodeToFile(const unsigned char* const pixelBuffer,
- const std::string& filename,
- const Pixel::Format pixelFormat,
- const std::size_t width,
- const std::size_t height )
-{
- DALI_ASSERT_DEBUG(pixelBuffer != 0 && filename.size() > 4 && width > 0 && height > 0);
- Vector< unsigned char > pixbufEncoded;
- const FileFormat format = GetFormatFromFileName( filename );
- const bool encodeResult = EncodeToFormat( pixelBuffer, pixbufEncoded, format, width, height, pixelFormat );
- if(!encodeResult)
- {
- DALI_LOG_ERROR("Encoding pixels failed\n");
- return false;
- }
- return TizenPlatform::SaveFile( filename, pixbufEncoded.Begin(), pixbufEncoded.Count() );
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <clipboard-event-notifier.h>
-
-// INTERNAL INCLUDES
-#include <clipboard-event-notifier-impl.h>
-
-namespace Dali
-{
-
-ClipboardEventNotifier::ClipboardEventNotifier()
-{
-}
-
-ClipboardEventNotifier ClipboardEventNotifier::Get()
-{
- return Internal::Adaptor::ClipboardEventNotifier::Get();
-}
-
-ClipboardEventNotifier::~ClipboardEventNotifier()
-{
-}
-
-const std::string& ClipboardEventNotifier::GetContent() const
-{
- return Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).GetContent();
-}
-
-void ClipboardEventNotifier::SetContent( const std::string& content )
-{
- Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).SetContent(content);
-}
-
-void ClipboardEventNotifier::ClearContent()
-{
- Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).ClearContent();
-}
-
-void ClipboardEventNotifier::EmitContentSelectedSignal()
-{
- Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).EmitContentSelectedSignal();
-}
-
-ClipboardEventNotifier::ClipboardEventSignalType& ClipboardEventNotifier::ContentSelectedSignal()
-{
- return Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).ContentSelectedSignal();
-}
-
-ClipboardEventNotifier::ClipboardEventNotifier( Internal::Adaptor::ClipboardEventNotifier* notifier )
-: BaseHandle( notifier )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <clipboard.h>
-
-// INTERNAL INCLUDES
-#include <clipboard-impl.h>
-
-namespace Dali
-{
-
-Clipboard::Clipboard()
-{
-}
-Clipboard::~Clipboard()
-{
-}
-Clipboard::Clipboard(Internal::Adaptor::Clipboard *impl)
- : BaseHandle(impl)
-{
-}
-
-Clipboard Clipboard::Get()
-{
- return Internal::Adaptor::Clipboard::Get();
-}
-
-bool Clipboard::SetItem( const std::string &itemData)
-{
- return GetImplementation(*this).SetItem( itemData );
-}
-
-void Clipboard::RequestItem()
-{
- GetImplementation(*this).RequestItem();
-}
-
-unsigned int Clipboard::NumberOfItems()
-{
- return GetImplementation(*this).NumberOfItems();
-}
-
-void Clipboard::ShowClipboard()
-{
- GetImplementation(*this).ShowClipboard();
-}
-
-void Clipboard::HideClipboard()
-{
- GetImplementation(*this).HideClipboard(false);
-}
-
-bool Clipboard::IsVisible() const
-{
- return GetImplementation(*this).IsVisible();
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <color-controller.h>
-
-// INTERNAL INCLUDES
-#include <color-controller-impl.h>
-
-namespace Dali
-{
-
-ColorController::ColorController()
-{
-}
-
-ColorController::ColorController(const ColorController& controller)
-: BaseHandle(controller)
-{
-}
-
-ColorController& ColorController::operator=(const ColorController& rhs)
-{
- BaseHandle::operator=(rhs);
- return *this;
-}
-
-ColorController ColorController::Get()
-{
- return Internal::Adaptor::ColorController::Get();
-}
-
-ColorController::~ColorController()
-{
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
-{
- return GetImplementation(*this).RetrieveColor( colorCode, colorValue );
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
-{
- return GetImplementation(*this).RetrieveColor( colorCode, textColor, textOutlineColor, textShadowColor );
-}
-
-ColorController::ColorController(Internal::Adaptor::ColorController* internal)
-: BaseHandle(internal)
-{
-}
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <drag-and-drop-detector.h>
-
-// INTERNAL INCLUDES
-#include <drag-and-drop-detector-impl.h>
-
-namespace Dali
-{
-
-DragAndDropDetector::DragAndDropDetector()
-{
-}
-
-DragAndDropDetector::~DragAndDropDetector()
-{
-}
-
-const std::string& DragAndDropDetector::GetContent() const
-{
- return GetImplementation(*this).GetContent();
-}
-
-Vector2 DragAndDropDetector::GetCurrentScreenPosition() const
-{
- return GetImplementation(*this).GetCurrentScreenPosition();
-}
-
-DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::EnteredSignal()
-{
- return GetImplementation(*this).EnteredSignal();
-}
-
-DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::ExitedSignal()
-{
- return GetImplementation(*this).ExitedSignal();
-}
-
-DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::MovedSignal()
-{
- return GetImplementation(*this).MovedSignal();
-}
-
-DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::DroppedSignal()
-{
- return GetImplementation(*this).DroppedSignal();
-}
-
-DragAndDropDetector::DragAndDropDetector( Internal::Adaptor::DragAndDropDetector* detector )
-: BaseHandle( detector )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "environment-variable.h"
-
-// EXTERNAL INCLUDE
-#include <cstdlib>
-
-namespace Dali
-{
-
-namespace EnvironmentVariable
-{
-
-const char * GetEnvironmentVariable( const char * variable )
-{
- return std::getenv( variable );
-}
-
-} // namespace EnvironmentVariable
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <event-feeder.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace EventFeeder
-{
-
-void FeedTouchPoint( TouchPoint& point, int timeStamp )
-{
- if ( Adaptor::IsAvailable() )
- {
- Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedTouchPoint( point, timeStamp );
- }
-}
-
-void FeedWheelEvent( WheelEvent& wheelEvent )
-{
- if ( Adaptor::IsAvailable() )
- {
- Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedWheelEvent( wheelEvent );
- }
-}
-
-void FeedKeyEvent( KeyEvent& keyEvent )
-{
- if ( Adaptor::IsAvailable() )
- {
- Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedKeyEvent( keyEvent );
- }
-}
-
-} // namespace EventFeeder
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "event-thread-callback.h"
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-struct EventThreadCallback::Impl
-{
- TriggerEventInterface* eventTrigger;
-};
-
-EventThreadCallback::EventThreadCallback( CallbackBase* callback )
-: mImpl( new Impl() )
-{
- mImpl->eventTrigger = NULL;
- if ( Adaptor::IsAvailable() )
- {
- Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() );
- mImpl->eventTrigger = adaptorImpl.GetTriggerEventFactoryInterface().CreateTriggerEvent( callback, TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
- }
-}
-
-EventThreadCallback::~EventThreadCallback()
-{
- if ( Adaptor::IsAvailable() )
- {
- Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() );
- adaptorImpl.GetTriggerEventFactoryInterface().DestroyTriggerEvent( mImpl->eventTrigger );
- }
- delete mImpl;
-}
-
-void EventThreadCallback::Trigger()
-{
- if( mImpl->eventTrigger )
- {
- mImpl->eventTrigger->Trigger();
- }
-}
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <feedback-player.h>
-
-// INTERNAL INCLUDES
-#include <feedback-player-impl.h>
-
-namespace Dali
-{
-
-FeedbackPlayer::FeedbackPlayer()
-{
-}
-
-FeedbackPlayer FeedbackPlayer::Get()
-{
- return Internal::Adaptor::FeedbackPlayer::Get();
-}
-
-FeedbackPlayer::~FeedbackPlayer()
-{
-}
-
-void FeedbackPlayer::PlayMonotone(unsigned int duration)
-{
- GetImplementation(*this).PlayMonotone(duration);
-}
-
-void FeedbackPlayer::PlayFile(const std::string filePath)
-{
- GetImplementation(*this).PlayFile(filePath);
-}
-
-void FeedbackPlayer::Stop()
-{
- GetImplementation(*this).Stop();
-}
-
-int FeedbackPlayer::PlaySound( const std::string& fileName )
-{
- return GetImplementation(*this).PlaySound(fileName);
-}
-
-void FeedbackPlayer::StopSound( int handle )
-{
- GetImplementation(*this).StopSound(handle);
-}
-
-void FeedbackPlayer::PlayFeedbackPattern( int type, int pattern )
-{
- GetImplementation(*this).PlayFeedbackPattern(type, pattern);
-}
-
-bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data)
-{
- return GetImplementation(*this).LoadFile(filename, data);
-}
-
-FeedbackPlayer::FeedbackPlayer( Internal::Adaptor::FeedbackPlayer* player )
-: BaseHandle( player )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "file-loader.h"
-
-
-#include <iostream>
-#include <fstream>
-
-namespace Dali
-{
-
-namespace FileLoader
-{
-
-int ReadFile(const std::string& filename, Dali::Vector<char> & memblock, FileLoader::FileType fileType)
-{
- std::streampos size;
-
- return ReadFile( filename, size, memblock, fileType);
-}
-
-int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector<char> & memblock, FileLoader::FileType fileType)
-{
- int errorCode = 0;
- std::ifstream * file;
-
-
- if( fileType == BINARY )
- {
- file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
- }
- else if( fileType == TEXT )
- {
- file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::ate);
- }
- else
- {
- return errorCode;
- }
-
- if( file->is_open() )
- {
- fileSize = file->tellg();
-
- memblock.Resize( fileSize );
-
- file->seekg (0, std::ios::beg);
- file->read( memblock.Begin(), fileSize );
- file->close();
-
- delete file;
-
- errorCode = 1;
- }
-
- return errorCode;
-}
-
-
-std::streampos GetFileSize(const std::string& filename)
-{
- std::streampos size = 0;
-
- std::ifstream file (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
- if( file.is_open() )
- {
- size = file.tellg();
- file.close();
- }
- return size;
-}
-
-} //FileLoader
-
-} //Dali
+++ /dev/null
-/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Copyright notice for the EFL:
- * Copyright (C) EFL developers (see AUTHORS)
- */
-
-// CLASS HEADER
-#include "gif-loading.h"
-
-// EXTERNAL INCLUDES
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <gif_lib.h>
-#include <cstring>
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/images/pixel-data.h>
-
-#define IMG_TOO_BIG( w, h ) \
- ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
- ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
-
-#define LOADERR( x ) \
- do { \
- DALI_LOG_ERROR( x ); \
- goto on_error; \
- } while ( 0 )
-
-namespace Dali
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
-#endif
-
-const int IMG_MAX_SIZE = 65000;
-
-#if GIFLIB_MAJOR < 5
-const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
-const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
-#endif
-
-struct FrameInfo
-{
- FrameInfo()
- : x( 0 ),
- y( 0 ),
- w( 0 ),
- h( 0 ),
- delay( 0 ),
- transparent( -1 ),
- dispose( DISPOSE_BACKGROUND ),
- interlace( 0 )
- {
- }
-
- int x, y, w, h;
- unsigned short delay; // delay time in 1/100ths of a sec
- short transparent : 10; // -1 == not, anything else == index
- short dispose : 6; // 0, 1, 2, 3 (others invalid)
- short interlace : 1; // interlaced or not
-};
-
-struct ImageFrame
-{
- ImageFrame()
- : index( 0 ),
- data( nullptr ),
- info(),
- loaded( false )
- {
- }
-
- ~ImageFrame()
- {
- }
-
- int index;
- uint32_t *data; /* frame decoding data */
- FrameInfo info; /* special image type info */
- bool loaded : 1;
-};
-
-struct GifAnimationData
-{
- GifAnimationData()
- : frames( ),
- frameCount( 0 ),
- loopCount( 0 ),
- currentFrame( 0 ),
- animated( false )
- {
- }
-
- std::vector<ImageFrame> frames;
- int frameCount;
- int loopCount;
- int currentFrame;
- bool animated;
-};
-
-struct LoaderInfo
-{
- LoaderInfo()
- : gif( nullptr ) ,
- imageNumber ( 0 )
- {
- }
-
- struct FileData
- {
- FileData()
- : fileName( nullptr ),
- globalMap ( nullptr ),
- length( 0 ),
- fileDescriptor( -1 )
- {
- }
-
- const char *fileName; /**< The absolute path of the file. */
- unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
- long long length; /**< The length of the file in bytes. */
- int fileDescriptor; /**< The file descriptor. */
- };
-
- struct FileInfo
- {
- FileInfo()
- : map( nullptr ),
- position( 0 ),
- length( 0 )
- {
- }
-
- unsigned char *map;
- int position, length; // yes - gif uses ints for file sizes.
- };
-
- FileData fileData;
- GifAnimationData animated;
- GifFileType *gif;
- int imageNumber;
- FileInfo fileInfo;
-};
-
-struct ImageProperties
-{
- unsigned int w;
- unsigned int h;
- bool alpha;
-};
-
-/**
- * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
- *
- * @param[in] animated A structure containing GIF animation data
- * @param[in] index Frame index to be searched in GIF
- * @return A pointer to the ImageFrame.
- */
-inline int CombinePixelABGR( int a, int r, int g, int b )
-{
- return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
-}
-
-inline int PixelLookup( ColorMapObject *colorMap, int index )
-{
- return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
-}
-
-/**
- * @brief Brute force find frame index - gifs are normally small so ok for now.
- *
- * @param[in] animated A structure containing GIF animation data
- * @param[in] index Frame index to be searched in GIF
- * @return A pointer to the ImageFrame.
- */
-ImageFrame *FindFrame( const GifAnimationData &animated, int index )
-{
- for( auto &&elem : animated.frames )
- {
- if( elem.index == index )
- {
- return const_cast<ImageFrame *>( &elem );
- }
- }
- return nullptr;
-}
-
-/**
- * @brief Fill in an image with a specific rgba color value.
- *
- * @param[in] data A pointer pointing to an image data
- * @param[in] row A int containing the number of rows in an image
- * @param[in] val A uint32_t containing rgba color value
- * @param[in] x X-coordinate used an offset to calculate pixel position
- * @param[in] y Y-coordinate used an offset to calculate pixel position
- * @param[in] width Width of the image
- * @param[in] height Height of the image
- */
-void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
-{
- int xAxis, yAxis;
- uint32_t *pixelPosition;
-
- for( yAxis = 0; yAxis < height; yAxis++ )
- {
- pixelPosition = data + ((y + yAxis) * row) + x;
- for( xAxis = 0; xAxis < width; xAxis++ )
- {
- *pixelPosition = val;
- pixelPosition++;
- }
- }
-}
-
-/**
- * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
- *
- * @param[in] data A pointer pointing to an image data
- * @param[in] row A int containing the number of rows in an image
- * @param[in] gif A pointer pointing to GIF File Type
- * @param[in] frameInfo A pointer pointing to Frame Information data
- * @param[in] x X-coordinate used an offset to calculate pixel position
- * @param[in] y Y-coordinate used an offset to calculate pixel position
- * @param[in] width Width of the image
- * @param[in] height Height of the image
- */
-void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
-{
- // solid color fill for pre frame region
- if( frameInfo->transparent < 0 )
- {
- ColorMapObject *colorMap;
- int backGroundColor;
-
- // work out color to use from colorMap
- if( gif->Image.ColorMap )
- {
- colorMap = gif->Image.ColorMap;
- }
- else
- {
- colorMap = gif->SColorMap;
- }
- backGroundColor = gif->SBackGroundColor;
- // and do the fill
- FillImage( data, row,
- CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
- colorMap->Colors[backGroundColor].Green,
- colorMap->Colors[backGroundColor].Blue ),
- x, y, w, h );
- }
- // fill in region with 0 (transparent)
- else
- {
- FillImage( data, row, 0, x, y, w, h );
- }
-}
-
-/**
- * @brief Store common fields from gif file info into frame info
- *
- * @param[in] gif A pointer pointing to GIF File Type
- * @param[in] frameInfo A pointer pointing to Frame Information data
- */
-void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
-{
- frameInfo->x = gif->Image.Left;
- frameInfo->y = gif->Image.Top;
- frameInfo->w = gif->Image.Width;
- frameInfo->h = gif->Image.Height;
- frameInfo->interlace = gif->Image.Interlace;
-}
-
-/**
- * @brief Check if image fills "screen space" and if so, if it is transparent
- * at all then the image could be transparent - OR if image doesnt fill,
- * then it could be trasnparent (full coverage of screen). Some gifs will
- * be recognized as solid here for faster rendering, but not all.
- *
- * @param[out] full A boolean to show whether image is transparent or not
- * @param[in] frameInfo A pointer pointing to Frame Information data
- * @param[in] width Width of the image
- * @param[in] height Height of the image
- */
-void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
-{
- if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
- ( frameInfo->w == width ) && ( frameInfo->h == height ) )
- {
- if( frameInfo->transparent >= 0 )
- {
- full = false;
- }
- }
- else
- {
- full = false;
- }
-}
-
-/**
- * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
- */
-void ClipCoordinates( int imageWidth, int imageHeight, int *xin, int *yin, int x0, int y0, int w0, int h0, int *x, int *y, int *w, int *h )
-{
- if( x0 < 0 )
- {
- w0 += x0;
- *xin = -x0;
- x0 = 0;
- }
- if( (x0 + w0) > imageWidth )
- {
- w0 = imageWidth - x0;
- }
- if( y0 < 0 )
- {
- h0 += y0;
- *yin = -y0;
- y0 = 0;
- }
- if( (y0 + h0) > imageHeight )
- {
- h0 = imageHeight - y0;
- }
- *x = x0;
- *y = y0;
- *w = w0;
- *h = h0;
-}
-
-/**
- * @brief Flush out rgba frame images to save memory but skip current,
- * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
- *
- * @param[in] animated A structure containing GIF animation data
- * @param[in] width Width of the image
- * @param[in] height Height of the image
- * @param[in] thisframe The current frame
- * @param[in] prevframe The previous frame
- * @param[in] lastPreservedFrame The last preserved frame
- */
-void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
-{
- DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
-
- // target is the amount of memory we want to be under for stored frames
- int total = 0, target = 512 * 1024;
-
- // total up the amount of memory used by stored frames for this image
- for( auto &&frame : animated.frames )
- {
- if( frame.data )
- {
- total++;
- }
- }
- total *= ( width * height * sizeof( uint32_t ) );
-
- DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
-
- // If we use more than target (512k) for frames - flush
- if( total > target )
- {
- // Clean frames (except current and previous) until below target
- for( auto &&frame : animated.frames )
- {
- if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
- (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
- {
- if( frame.data != nullptr )
- {
- delete[] frame.data;
- frame.data = nullptr;
-
- // subtract memory used and if below target - stop flush
- total -= ( width * height * sizeof( uint32_t ) );
- if( total < target )
- {
- break;
- }
- }
- }
- }
- }
-
- DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
-}
-
-/**
- * @brief allocate frame and frame info and append to list and store fields.
- *
- * @param[in] animated A structure containing GIF animation data
- * @param[in] transparent Transparent index of the new frame
- * @param[in] dispose Dispose mode of new frame
- * @param[in] delay The frame delay of new frame
- * @param[in] index The index of new frame
- */
-FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
-{
- ImageFrame frame;
-
- // record transparent index to be used or -1 if none
- // for this SPECIFIC frame
- frame.info.transparent = transparent;
- // record dispose mode (3 bits)
- frame.info.dispose = dispose;
- // record delay (2 bytes so max 65546 /100 sec)
- frame.info.delay = delay;
- // record the index number we are at
- frame.index = index;
- // that frame is stored AT image/screen size
-
- animated.frames.push_back( frame );
-
- DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
-
- return &( animated.frames.back().info );
-}
-
-/**
- * @brief Copy data from gif file into buffer.
- *
- * @param[in] gifFileType A pointer pointing to GIF File Type
- * @param[out] buffer A pointer to buffer containing GIF raw data
- * @param[in] len The length in bytes to be copied
- * @return The data length of the image in bytes
- */
-int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
-{
- LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
-
- if( fi->position >= fi->length )
- {
- return 0; // if at or past end - no
- }
- if( (fi->position + length) >= fi->length )
- {
- length = fi->length - fi->position;
- }
- memcpy( buffer, fi->map + fi->position, length );
- fi->position += length;
- return length;
-}
-
-/**
- * @brief Decode a gif image into rows then expand to 32bit into the destination
- * data pointer.
- */
-bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
- int transparent, int x, int y, int w, int h, bool fill )
-{
- int intoffset[] = {0, 4, 2, 1};
- int intjump[] = {8, 8, 4, 2};
- int i, xx, yy, pix;
- GifRowType *rows = NULL;
- bool ret = false;
- ColorMapObject *colorMap;
- uint32_t *p;
-
- // what we need is image size.
- SavedImage *sp;
- sp = &gif->SavedImages[ gif->ImageCount - 1 ];
- if( !sp )
- {
- goto on_error;
- }
- w = sp->ImageDesc.Width;
- h = sp->ImageDesc.Height;
-
- // build a blob of memory to have pointers to rows of pixels
- // AND store the decoded gif pixels (1 byte per pixel) as welll
- rows = static_cast<GifRowType *>(malloc( (h * sizeof(GifRowType) ) + ( w * h * sizeof(GifPixelType) )));
- if( !rows )
- {
- goto on_error;
- }
-
- // fill in the pointers at the start
- for( yy = 0; yy < h; yy++ )
- {
- rows[yy] = reinterpret_cast<unsigned char *>(rows) + (h * sizeof(GifRowType)) + (yy * w * sizeof(GifPixelType));
- }
-
- // if gif is interlaced, walk interlace pattern and decode into rows
- if( gif->Image.Interlace )
- {
- for( i = 0; i < 4; i++ )
- {
- for( yy = intoffset[i]; yy < h; yy += intjump[i] )
- {
- if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
- {
- goto on_error;
- }
- }
- }
- }
- // normal top to bottom - decode into rows
- else
- {
- for( yy = 0; yy < h; yy++ )
- {
- if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
- {
- goto on_error;
- }
- }
- }
-
- // work out what colormap to use
- if( gif->Image.ColorMap )
- {
- colorMap = gif->Image.ColorMap;
- }
- else
- {
- colorMap = gif->SColorMap;
- }
-
- // if we need to deal with transparent pixels at all...
- if( transparent >= 0 )
- {
- // if we are told to FILL (overwrite with transparency kept)
- if( fill )
- {
- for( yy = 0; yy < h; yy++ )
- {
- p = data + ((y + yy) * rowpix) + x;
- for( xx = 0; xx < w; xx++ )
- {
- pix = rows[yin + yy][xin + xx];
- if( pix != transparent )
- {
- *p = PixelLookup( colorMap, pix );
- }
- else
- {
- *p = 0;
- }
- p++;
- }
- }
- }
- // paste on top with transparent pixels untouched
- else
- {
- for( yy = 0; yy < h; yy++ )
- {
- p = data + ((y + yy) * rowpix) + x;
- for( xx = 0; xx < w; xx++ )
- {
- pix = rows[yin + yy][xin + xx];
- if( pix != transparent )
- {
- *p = PixelLookup( colorMap, pix );
- }
- p++;
- }
- }
- }
- }
- else
- {
- // walk pixels without worring about transparency at all
- for( yy = 0; yy < h; yy++ )
- {
- p = data + ((y + yy) * rowpix) + x;
- for( xx = 0; xx < w; xx++ )
- {
- pix = rows[yin + yy][xin + xx];
- *p = PixelLookup( colorMap, pix );
- p++;
- }
- }
- }
- ret = true;
-
-on_error:
- if( rows )
- {
- free( rows );
- }
- return ret;
-}
-
-/**
- * @brief Reader header from the gif file and populates structures accordingly.
- *
- * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
- * @param[out] prop A ImageProperties structure for storing information about GIF data.
- * @param[out] error Error code
- * @return The true or false whether reading was successful or not.
- */
-bool ReadHeader( LoaderInfo &loaderInfo,
- ImageProperties &prop, //output struct
- int *error )
-{
- GifAnimationData &animated = loaderInfo.animated;
- LoaderInfo::FileData &fileData = loaderInfo.fileData;
- bool ret = false;
- LoaderInfo::FileInfo fileInfo;
- GifRecordType rec;
- GifFileType *gif = NULL;
- // it is possible which gif file have error midle of frames,
- // in that case we should play gif file until meet error frame.
- int imageNumber = 0;
- int loopCount = -1;
- FrameInfo *frameInfo = NULL;
- bool full = true;
-
- // init prop struct with some default null values
- prop.w = 0;
- prop.h = 0;
-
- fileData.fileDescriptor = open( fileData.fileName, O_RDONLY );
-
- if( fileData.fileDescriptor == -1 )
- {
- return false;
- }
-
- fileData.length = lseek( fileData.fileDescriptor, 0, SEEK_END );
- if( fileData.length <= -1 )
- {
- close( fileData.fileDescriptor );
- return false;
- }
-
- if( lseek( fileData.fileDescriptor, 0, SEEK_SET ) == -1 )
- {
- close( fileData.fileDescriptor );
- return false;
- }
-
- // map the file and store/track info
- fileData.globalMap = reinterpret_cast<unsigned char *>( mmap(NULL, fileData.length, PROT_READ, MAP_SHARED, fileData.fileDescriptor, 0 ));
- fileInfo.map = fileData.globalMap ;
-
- close(fileData.fileDescriptor);
- fileData.fileDescriptor = -1;
-
- if( !fileInfo.map )
- {
- LOADERR("LOAD_ERROR_CORRUPT_FILE");
- }
- fileInfo.length = fileData.length;
- fileInfo.position = 0;
-
-// actually ask libgif to open the file
-#if GIFLIB_MAJOR >= 5
- gif = DGifOpen( &fileInfo, FileRead, NULL );
-#else
- gif = DGifOpen( &fileInfo, FileRead );
-#endif
-
- if (!gif)
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
-
- // get the gif "screen size" (the actual image size)
- prop.w = gif->SWidth;
- prop.h = gif->SHeight;
-
- // if size is invalid - abort here
- if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
- {
- if( IMG_TOO_BIG(prop.w, prop.h) )
- {
- LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
- }
- LOADERR("LOAD_ERROR_GENERIC");
- }
- // walk through gif records in file to figure out info
- do
- {
- if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
- {
- // if we have a gif that ends part way through a sequence
- // (or animation) consider it valid and just break - no error
- if( imageNumber > 1 )
- {
- break;
- }
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
-
- // get image description section
- if( rec == IMAGE_DESC_RECORD_TYPE )
- {
- int img_code;
- GifByteType *img;
-
- // get image desc
- if( DGifGetImageDesc(gif) == GIF_ERROR )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
- // skip decoding and just walk image to next
- if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
- // skip till next...
- while( img )
- {
- img = NULL;
- DGifGetCodeNext( gif, &img );
- }
- // store geometry in the last frame info data
- if( frameInfo )
- {
- StoreFrameInfo( gif, frameInfo );
- CheckTransparency( full, frameInfo, prop.w, prop.h );
- }
- // or if we dont have a frameInfo entry - create one even for stills
- else
- {
- // allocate and save frame with field data
- frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
- if (!frameInfo)
- {
- LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
- }
- // store geometry info from gif image
- StoreFrameInfo( gif, frameInfo );
- // check for transparency/alpha
- CheckTransparency( full, frameInfo, prop.w, prop.h );
- }
- imageNumber++;
- }
- // we have an extension code block - for animated gifs for sure
- else if( rec == EXTENSION_RECORD_TYPE )
- {
- int ext_code;
- GifByteType *ext;
-
- ext = NULL;
- // get the first extension entry
- DGifGetExtension( gif, &ext_code, &ext );
- while( ext )
- {
- // graphic control extension - for animated gif data
- // and transparent index + flag
- if( ext_code == 0xf9 )
- {
- // create frame and store it in image
- int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
- int disposeMode = (ext[1] >> 2) & 0x7;
- int delay = (int(ext[3]) << 8) | int(ext[2]);
- frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
- if( !frameInfo )
- {
- LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
- }
- }
- // netscape extension indicating loop count.
- else if( ext_code == 0xff ) /* application extension */
- {
- if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
- !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
- {
- ext = NULL;
- DGifGetExtensionNext( gif, &ext );
- if( ext[1] == 0x01 )
- {
- loopCount = (int(ext[3]) << 8) | int(ext[2]);
- if( loopCount > 0 )
- {
- loopCount++;
- }
- }
- }
- }
- // and continue onto the next extension entry
- ext = NULL;
- DGifGetExtensionNext( gif, &ext );
- }
- }
- } while( rec != TERMINATE_RECORD_TYPE );
-
- // if the gif main says we have more than one image or our image counting
- // says so, then this image is animated - indicate this
- if( (gif->ImageCount > 1) || (imageNumber > 1) )
- {
- animated.animated = 1;
- animated.loopCount = loopCount;
- }
- animated.frameCount = std::min( gif->ImageCount, imageNumber );
-
- if( !full )
- {
- prop.alpha = 1;
- }
-
- animated.currentFrame = 1;
-
- // no errors in header scan etc. so set err and return value
- *error = 0;
- ret = true;
-
-on_error: // jump here on any errors to clean up
-#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
- if( gif )
- {
- DGifCloseFile( gif, NULL );
- }
-#else
- if( gif )
- {
- DGifCloseFile( gif );
- }
-#endif
-
- return ret;
-}
-
-/**
- * @brief Reader next frame of the gif file and populates structures accordingly.
- *
- * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
- * @param[in/out] prop A ImageProperties structure containing information about gif data.
- * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
- * @param[out] error Error code
- * @return The true or false whether reading was successful or not.
- */
-bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
- unsigned char *pixels, int *error )
-{
- GifAnimationData &animated = loaderInfo.animated;
- LoaderInfo::FileData &fileData = loaderInfo.fileData;
- bool ret = false;
- GifRecordType rec;
- GifFileType *gif = NULL;
- int index = 0, imageNumber = 0;
- FrameInfo *frameInfo;
- ImageFrame *frame = NULL;
- ImageFrame *lastPreservedFrame = NULL;
-
- index = animated.currentFrame;
-
- // if index is invalid for animated image - error out
- if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
- {
- LOADERR("LOAD_ERROR_GENERIC");
- }
-
- // find the given frame index
- frame = FindFrame( animated, index );
- if( frame )
- {
- if( (frame->loaded) && (frame->data) )
- {
- // frame is already there and decoded - jump to end
- goto on_ok;
- }
- }
- else
- {
- LOADERR("LOAD_ERROR_CORRUPT_FILE");
- }
-
-open_file:
- // actually ask libgif to open the file
- gif = loaderInfo.gif;
- if( !gif )
- {
- loaderInfo.fileInfo.map = fileData.globalMap ;
- if( !loaderInfo.fileInfo.map )
- {
- LOADERR("LOAD_ERROR_CORRUPT_FILE");
- }
- loaderInfo.fileInfo.length = fileData.length;
- loaderInfo.fileInfo.position = 0;
-
-#if GIFLIB_MAJOR >= 5
- gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
-#else
- gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
-#endif
- // if gif open failed... get out of here
- if( !gif )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
- loaderInfo.gif = gif;
- loaderInfo.imageNumber = 1;
- }
-
- // if we want to go backwards, we likely need/want to re-decode from the
- // start as we have nothing to build on
- if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
- {
-#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
- if( loaderInfo.gif )
- DGifCloseFile( loaderInfo.gif, NULL );
-#else
- if( loaderInfo.gif )
- DGifCloseFile( loaderInfo.gif );
-#endif
- loaderInfo.gif = NULL;
- loaderInfo.imageNumber = 0;
- goto open_file;
- }
-
- // our current position is the previous frame we decoded from the file
- imageNumber = loaderInfo.imageNumber;
-
- // walk through gif records in file to figure out info
- do
- {
- if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
-
- if( rec == EXTENSION_RECORD_TYPE )
- {
- int ext_code;
- GifByteType *ext = NULL;
- DGifGetExtension( gif, &ext_code, &ext );
-
- while( ext )
- {
- ext = NULL;
- DGifGetExtensionNext( gif, &ext );
- }
- }
- // get image description section
- else if( rec == IMAGE_DESC_RECORD_TYPE )
- {
- int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
- int img_code;
- GifByteType *img;
- ImageFrame *previousFrame = NULL;
- ImageFrame *thisFrame = NULL;
-
- // get image desc
- if( DGifGetImageDesc(gif) == GIF_ERROR )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
-
- // get the previous frame entry AND the current one to fill in
- previousFrame = FindFrame(animated, imageNumber - 1);
- thisFrame = FindFrame(animated, imageNumber);
-
- // if we have a frame AND we're animated AND we have no data...
- if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
- {
- bool first = false;
-
- // allocate it
- thisFrame->data = new uint32_t[prop.w * prop.h];
-
- if( !thisFrame->data )
- {
- LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
- }
-
- // if we have no prior frame OR prior frame data... empty
- if( (!previousFrame) || (!previousFrame->data) )
- {
- first = true;
- frameInfo = &(thisFrame->info);
- memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
- }
- // we have a prior frame to copy data from...
- else
- {
- frameInfo = &( previousFrame->info );
-
- // fix coords of sub image in case it goes out...
- ClipCoordinates( prop.w, prop.h, &xin, &yin,
- frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
- &x, &y, &w, &h );
-
- // if dispose mode is not restore - then copy pre frame
- if( frameInfo->dispose != DISPOSE_PREVIOUS )
- {
- memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
- }
-
- // if dispose mode is "background" then fill with bg
- if( frameInfo->dispose == DISPOSE_BACKGROUND )
- {
- FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
- }
- else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
- {
- int prevIndex = 2;
- do
- {
- // Find last preserved frame.
- lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
- if( ! lastPreservedFrame )
- {
- LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
- }
- prevIndex++;
- } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
-
- if ( lastPreservedFrame )
- {
- memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
- }
- }
- }
- // now draw this frame on top
- frameInfo = &( thisFrame->info );
- ClipCoordinates( prop.w, prop.h, &xin, &yin,
- frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
- &x, &y, &w, &h );
- if( !DecodeImage( gif, thisFrame->data, prop.w,
- xin, yin, frameInfo->transparent,
- x, y, w, h, first) )
- {
- LOADERR("LOAD_ERROR_CORRUPT_FILE");
- }
-
- // mark as loaded and done
- thisFrame->loaded = true;
-
- FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
- }
- // if we hve a frame BUT the image is not animated... different
- // path
- else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
- {
- // if we don't have the data decoded yet - decode it
- if( (!thisFrame->loaded) || (!thisFrame->data) )
- {
- // use frame info but we WONT allocate frame pixels
- frameInfo = &( thisFrame->info );
- ClipCoordinates( prop.w, prop.h, &xin, &yin,
- frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
- &x, &y, &w, &h );
-
- // clear out all pixels
- FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
-
- // and decode the gif with overwriting
- if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
- xin, yin, frameInfo->transparent, x, y, w, h, true) )
- {
- LOADERR("LOAD_ERROR_CORRUPT_FILE");
- }
-
- // mark as loaded and done
- thisFrame->loaded = true;
- }
- // flush mem we don't need (at expense of decode cpu)
- }
- else
- {
- // skip decoding and just walk image to next
- if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
- {
- LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
- }
-
- while( img )
- {
- img = NULL;
- DGifGetCodeNext( gif, &img );
- }
- }
-
- imageNumber++;
- // if we found the image we wanted - get out of here
- if( imageNumber > index )
- {
- break;
- }
- }
- } while( rec != TERMINATE_RECORD_TYPE );
-
- // if we are at the end of the animation or not animated, close file
- loaderInfo.imageNumber = imageNumber;
- if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
- {
-#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
- if( loaderInfo.gif )
- {
- DGifCloseFile( loaderInfo.gif, NULL );
- }
-#else
- if( loaderInfo.gif )
- {
- DGifCloseFile( loaderInfo.gif );
- }
-#endif
-
- loaderInfo.gif = NULL;
- loaderInfo.imageNumber = 0;
- }
-
-on_ok:
- // no errors in header scan etc. so set err and return value
- *error = 0;
- ret = true;
-
- // if it was an animated image we need to copy the data to the
- // pixels for the image from the frame holding the data
- if( animated.animated && frame->data )
- {
- memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
- }
-
-on_error: // jump here on any errors to clean up
- return ret;
-}
-
-} // unnamed namespace
-
-struct GifLoading::Impl
-{
-public:
- Impl( const std::string& url)
- : mUrl( url )
- {
- loaderInfo.gif = nullptr;
- int error;
- loaderInfo.fileData.fileName = mUrl.c_str();
-
- ReadHeader( loaderInfo, imageProperties, &error );
- }
-
- ~Impl()
- {
- if( loaderInfo.fileData.globalMap )
- {
- munmap( loaderInfo.fileData.globalMap , loaderInfo.fileData.length );
- loaderInfo.fileData.globalMap = nullptr;
- }
- }
-
- std::string mUrl;
- LoaderInfo loaderInfo;
- ImageProperties imageProperties;
-};
-
-std::unique_ptr<GifLoading> GifLoading::New( const std::string &url )
-{
- return std::unique_ptr<GifLoading>( new GifLoading( url ) );
-}
-
-GifLoading::GifLoading( const std::string &url )
-: mImpl( new GifLoading::Impl( url ) )
-{
-}
-
-GifLoading::~GifLoading()
-{
- delete mImpl;
-}
-
-bool GifLoading::LoadNextNFrames( int frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
-{
- int error;
- bool ret = false;
-
- const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
-
- DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
-
- for( int i = 0; i < count; ++i )
- {
- auto pixelBuffer = new unsigned char[ bufferSize ];
-
- mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
-
- if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
- {
- if( pixelBuffer )
- {
- pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
- mImpl->imageProperties.w, mImpl->imageProperties.h,
- Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
- ret = true;
- }
- }
- }
-
- return ret;
-}
-
-bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
-{
- if( LoadFrameDelays( frameDelays ) )
- {
- return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
- }
- return false;
-}
-
-ImageDimensions GifLoading::GetImageSize()
-{
- return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.w );
-}
-
-int GifLoading::GetImageCount()
-{
- return mImpl->loaderInfo.animated.frameCount;
-}
-
-bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
-{
- frameDelays.Clear();
-
- for( auto &&elem : mImpl->loaderInfo.animated.frames )
- {
- // Read frame delay time, multiply 10 to change time unit to milliseconds
- frameDelays.PushBack( elem.info.delay * 10 );
- }
-
- return true;
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "image-loading.h"
-
-// INTERNAL INCLUDES
-#include <dali/public-api/object/property-map.h>
-#include "image-loaders/image-loader.h"
-#include <resource-loader/network/file-download.h>
-#include <platform-abstractions/portable/file-reader.h>
-#include "pixel-buffer-impl.h"
-
-
-
-namespace Dali
-{
-
-namespace
-{
-
-// limit maximum image down load size to 50 MB
-const size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024 ;
-
-static unsigned int gMaxTextureSize = 4096;
-
-}
-
-Devel::PixelBuffer LoadImageFromFile( const std::string& url, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection )
-{
- Integration::BitmapResourceType resourceType( size, fittingMode, samplingMode, orientationCorrection );
-
- Internal::Platform::FileReader fileReader( url );
- FILE * const fp = fileReader.GetFile();
- if( fp != NULL )
- {
- Dali::Devel::PixelBuffer bitmap;
- bool success = TizenPlatform::ImageLoader::ConvertStreamToBitmap( resourceType, url, fp, bitmap );
- if( success && bitmap )
- {
- return bitmap;
- }
- }
- return Dali::Devel::PixelBuffer();
-}
-
-ImageDimensions GetClosestImageSize( const std::string& filename,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection )
-{
- ImageDimensions dimension = TizenPlatform::ImageLoader::GetClosestImageSize( filename, size, fittingMode, samplingMode, orientationCorrection );
-
- dimension.SetWidth( std::min( dimension.GetWidth(), static_cast< uint16_t >( GetMaxTextureSize() ) ) );
- dimension.SetHeight( std::min( dimension.GetHeight(), static_cast< uint16_t >( GetMaxTextureSize() ) ) );
-
- return dimension;
-}
-
-
-Devel::PixelBuffer DownloadImageSynchronously( const std::string& url, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection )
-{
- Integration::BitmapResourceType resourceType( size, fittingMode, samplingMode, orientationCorrection );
-
- bool succeeded;
- Dali::Vector<uint8_t> dataBuffer;
- size_t dataSize;
-
- succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( url, dataBuffer, dataSize,
- MAXIMUM_DOWNLOAD_IMAGE_SIZE );
- if( succeeded )
- {
- size_t blobSize = dataBuffer.Size();
-
- DALI_ASSERT_DEBUG( blobSize > 0U );
-
- if( blobSize > 0U )
- {
- // Open a file handle on the memory buffer:
- Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
- FILE * const fp = fileReader.GetFile();
- if ( NULL != fp )
- {
- Dali::Devel::PixelBuffer bitmap;
- bool result = TizenPlatform::ImageLoader::ConvertStreamToBitmap(
- resourceType,
- url,
- fp,
- bitmap );
-
- if ( result && bitmap )
- {
- return bitmap;
- }
- else
- {
- DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" );
- }
- }
- }
- }
- return Dali::Devel::PixelBuffer();
-}
-
-void SetMaxTextureSize( unsigned int size )
-{
- gMaxTextureSize = size;
-}
-
-unsigned int GetMaxTextureSize()
-{
- return gMaxTextureSize;
-}
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_IMAGE_LOADING_H
-#define DALI_IMAGE_LOADING_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/images/image-operations.h>
-
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-// @todo Make dali-adaptor code folder structure mirror the folder structure installed to dali-env
-#include <pixel-buffer.h>
-#else
-#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
-#endif
-
-namespace Dali
-{
-
-/**
- * @brief Load an image synchronously from local file.
- *
- * @note This method is thread safe, i.e. can be called from any thread.
- *
- * @param [in] url The URL of the image file to load.
- * @param [in] size The width and height to fit the loaded image to, 0.0 means whole image
- * @param [in] fittingMode The method used to fit the shape of the image before loading to the shape defined by the size parameter.
- * @param [in] samplingMode The filtering method used when sampling pixels from the input image while fitting it to desired size.
- * @param [in] orientationCorrection Reorient the image to respect any orientation metadata in its header.
- * @return handle to the loaded PixelBuffer object or an empty handle in case loading failed.
- */
-DALI_IMPORT_API Devel::PixelBuffer LoadImageFromFile(
- const std::string& url,
- ImageDimensions size = ImageDimensions( 0, 0 ),
- FittingMode::Type fittingMode = FittingMode::DEFAULT,
- SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR,
- bool orientationCorrection = true );
-
-/**
- * @brief Determine the size of an image that LoadImageFromFile will provide when
- * given the same image loading parameters.
- *
- * This is a synchronous request.
- * This function is used to determine the size of an image before it has loaded.
- * @param[in] filename name of the image.
- * @param[in] size The requested size for the image.
- * @param[in] fittingMode The method to use to map the source image to the desired
- * dimensions.
- * @param[in] samplingMode The image filter to use if the image needs to be
- * downsampled to the requested size.
- * @param[in] orientationCorrection Whether to use image metadata to rotate or
- * flip the image, e.g., from portrait to landscape.
- * @return dimensions that image will have if it is loaded with given parameters.
- */
-DALI_IMPORT_API ImageDimensions GetClosestImageSize(
- const std::string& filename,
- ImageDimensions size = ImageDimensions(0, 0),
- FittingMode::Type fittingMode = FittingMode::DEFAULT,
- SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR ,
- bool orientationCorrection = true );
-
-/**
- * @brief Load an image synchronously from a remote resource.
- *
- * @param [in] url The URL of the image file to load.
- * @param [in] size The width and height to fit the loaded image to, 0.0 means whole image
- * @param [in] fittingMode The method used to fit the shape of the image before loading to the shape defined by the size parameter.
- * @param [in] samplingMode The filtering method used when sampling pixels from the input image while fitting it to desired size.
- * @param [in] orientationCorrection Reorient the image to respect any orientation metadata in its header.
- *
- * @return handle to the loaded PixelBuffer object or an empty handle in case downloading or decoding failed.
- */
-DALI_IMPORT_API Devel::PixelBuffer DownloadImageSynchronously(
- const std::string& url,
- ImageDimensions size = ImageDimensions( 0, 0 ),
- FittingMode::Type fittingMode = FittingMode::DEFAULT,
- SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR,
- bool orientationCorrection = true );
-
-/**
- * @brief Set the maximum texture size. Then size can be kwown by GL_MAX_TEXTURE_SIZE.
- *
- * @param [in] size The maximum texture size to set
- */
-void SetMaxTextureSize( unsigned int size );
-
-/**
- * @brief get the maximum texture size.
- *
- * @return The maximum texture size
- */
-DALI_IMPORT_API unsigned int GetMaxTextureSize();
-
-} // Dali
-
-#endif // DALI_IMAGE_LOADING_H
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <imf-manager.h>
-
-// INTERNAL INCLUDES
-#include <imf-manager-impl.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-ImfManager::ImfManager()
-{
-}
-
-ImfManager::~ImfManager()
-{
-}
-
-ImfManager ImfManager::Get()
-{
- return Internal::Adaptor::ImfManager::Get();
-}
-
-void ImfManager::Activate()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).Activate();
-}
-
-void ImfManager::Deactivate()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).Deactivate();
-}
-
-bool ImfManager::RestoreAfterFocusLost() const
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).RestoreAfterFocusLost();
-}
-
-void ImfManager::SetRestoreAfterFocusLost( bool toggle )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).SetRestoreAfterFocusLost( toggle );
-}
-
-void ImfManager::Reset()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).Reset();
-}
-
-void ImfManager::NotifyCursorPosition()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).NotifyCursorPosition();
-}
-
-void ImfManager::SetCursorPosition( unsigned int SetCursorPosition )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).SetCursorPosition( SetCursorPosition );
-}
-
-unsigned int ImfManager::GetCursorPosition() const
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetCursorPosition();
-}
-
-void ImfManager::SetSurroundingText( const std::string& text )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).SetSurroundingText( text );
-}
-
-const std::string& ImfManager::GetSurroundingText() const
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetSurroundingText();
-}
-
-void ImfManager::NotifyTextInputMultiLine( bool multiLine )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).NotifyTextInputMultiLine( multiLine );
-}
-
-ImfManager::TextDirection ImfManager::GetTextDirection()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetTextDirection();
-}
-
-Rect<int> ImfManager::GetInputMethodArea()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputMethodArea();
-}
-
-void ImfManager::ApplyOptions( const InputMethodOptions& options )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).ApplyOptions( options );
-}
-
-void ImfManager::SetInputPanelData( const std::string& data )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).SetInputPanelData( data );
-}
-
-void ImfManager::GetInputPanelData( std::string& data )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelData( data );
-}
-
-Dali::ImfManager::State ImfManager::GetInputPanelState()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelState();
-}
-
-void ImfManager::SetReturnKeyState( bool visible )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).SetReturnKeyState( visible );
-}
-
-void ImfManager::AutoEnableInputPanel( bool enabled )
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).AutoEnableInputPanel( enabled );
-}
-
-void ImfManager::ShowInputPanel()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).ShowInputPanel();
-}
-
-void ImfManager::HideInputPanel()
-{
- Internal::Adaptor::ImfManager::GetImplementation(*this).HideInputPanel();
-}
-
-Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetKeyboardType();
-}
-
-std::string ImfManager::GetInputPanelLocale()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelLocale();
-}
-
-ImfManager::ImfManagerSignalType& ImfManager::ActivatedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).ActivatedSignal();
-}
-
-ImfManager::ImfEventSignalType& ImfManager::EventReceivedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).EventReceivedSignal();
-}
-
-ImfManager::StatusSignalType& ImfManager::StatusChangedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).StatusChangedSignal();
-}
-
-ImfManager::KeyboardResizedSignalType& ImfManager::ResizedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).ResizedSignal();
-}
-
-ImfManager::LanguageChangedSignalType& ImfManager::LanguageChangedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).LanguageChangedSignal();
-}
-
-ImfManager::KeyboardTypeSignalType& ImfManager::KeyboardTypeChangedSignal()
-{
- return Internal::Adaptor::ImfManager::GetImplementation(*this).KeyboardTypeChangedSignal();
-}
-
-ImfManager::ImfManager(Internal::Adaptor::ImfManager *impl)
- : BaseHandle(impl)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_IMF_MANAGER_H__
-#define __DALI_IMF_MANAGER_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-handle.h>
-#include <dali/public-api/signals/dali-signal.h>
-#include "input-method-options.h"
-
-namespace Dali
-{
-
-namespace Internal DALI_INTERNAL
-{
-namespace Adaptor
-{
-class ImfManager;
-}
-}
-
-/**
- * @brief The ImfManager class
- *
- * Specifically manages the ecore input method framework which enables the virtual or hardware keyboards.
- */
-class DALI_IMPORT_API ImfManager : public BaseHandle
-{
-public:
-
- /**
- * @brief The direction of text.
- */
- enum TextDirection
- {
- LeftToRight,
- RightToLeft,
- };
-
- /**
- * @brief Events that are generated by the IMF.
- */
- enum ImfEvent
- {
- VOID, ///< No event
- PREEDIT, ///< Pre-Edit changed
- COMMIT, ///< Commit recieved
- DELETESURROUNDING, ///< Event to delete a range of characters from the string
- GETSURROUNDING, ///< Event to query string and cursor position
- PRIVATECOMMAND ///< Private command sent from the input panel
- };
-
- /**
- * @brief Enumeration for state of the input panel.
- */
- enum State
- {
- DEFAULT = 0, ///< Unknown state
- SHOW, ///< Input panel is shown
- HIDE, ///< Input panel is hidden
- WILL_SHOW ///< Input panel in process of being shown
- };
-
- /**
- * @brief Enumeration for the type of Keyboard.
- */
- enum KeyboardType
- {
- SOFTWARE_KEYBOARD, ///< Software keyboard (Virtual keyboard) is default
- HARDWARE_KEYBOARD ///< Hardware keyboard
- };
-
- /**
- * @brief This structure is used to pass on data from the IMF regarding predictive text.
- */
- struct ImfEventData
- {
- /**
- * @brief Default Constructor.
- */
- ImfEventData()
- : predictiveString(),
- eventName( VOID ),
- cursorOffset( 0 ),
- numberOfChars ( 0 )
- {
- };
-
- /**
- * @brief Constructor
- *
- * @param[in] aEventName The name of the event from the IMF.
- * @param[in] aPredictiveString The pre-edit or commit string.
- * @param[in] aCursorOffset Start position from the current cursor position to start deleting characters.
- * @param[in] aNumberOfChars The number of characters to delete from the cursorOffset.
- */
- ImfEventData( ImfEvent aEventName, const std::string& aPredictiveString, int aCursorOffset, int aNumberOfChars )
- : predictiveString( aPredictiveString ),
- eventName( aEventName ),
- cursorOffset( aCursorOffset ),
- numberOfChars( aNumberOfChars )
- {
- }
-
- // Data
- std::string predictiveString; ///< The pre-edit or commit string.
- ImfEvent eventName; ///< The name of the event from the IMF.
- int cursorOffset; ///< Start position from the current cursor position to start deleting characters.
- int numberOfChars; ///< number of characters to delete from the cursorOffset.
- };
-
- /**
- * @brief Data required by IMF from the callback
- */
- struct ImfCallbackData
- {
- /**
- * @brief Constructor
- */
- ImfCallbackData()
- : currentText(),
- cursorPosition( 0 ),
- update( false ),
- preeditResetRequired( false )
- {
- }
-
- /**
- * @brief Constructor
- * @param[in] aUpdate True if cursor position needs to be updated
- * @param[in] aCursorPosition new position of cursor
- * @param[in] aCurrentText current text string
- * @param[in] aPreeditResetRequired flag if preedit reset is required.
- */
- ImfCallbackData( bool aUpdate, int aCursorPosition, const std::string& aCurrentText, bool aPreeditResetRequired )
- : currentText( aCurrentText ),
- cursorPosition( aCursorPosition ),
- update( aUpdate ),
- preeditResetRequired( aPreeditResetRequired )
- {
- }
-
- std::string currentText; ///< current text string
- int cursorPosition; ///< new position of cursor
- bool update :1; ///< if cursor position needs to be updated
- bool preeditResetRequired :1; ///< flag if preedit reset is required.
- };
-
- typedef Signal< void (ImfManager&) > ImfManagerSignalType; ///< Keyboard actived signal
- typedef Signal< ImfCallbackData ( ImfManager&, const ImfEventData& ) > ImfEventSignalType; ///< keyboard events
- typedef Signal< void () > VoidSignalType;
- typedef Signal< void ( bool ) > StatusSignalType;
- typedef Signal< void ( KeyboardType ) > KeyboardTypeSignalType; ///< keyboard type
- typedef Signal< void ( int ) > KeyboardResizedSignalType; ///< Keyboard resized signal
- typedef Signal< void ( int ) > LanguageChangedSignalType; ///< Language changed signal
-
-public:
-
- /**
- * @brief Retrieve a handle to the instance of ImfManager.
- * @return A handle to the ImfManager.
- */
- static ImfManager Get();
-
- /**
- * @brief Activate the IMF.
- *
- * It means that the text editing is started at somewhere.
- * If the H/W keyboard isn't connected then it will show the virtual keyboard.
- */
- void Activate();
-
- /**
- * @brief Deactivate the IMF.
- *
- * It means that the text editing is finished at somewhere.
- */
- void Deactivate();
-
- /**
- * @brief Get the restoration status, which controls if the keyboard is restored after the focus lost then regained.
- *
- * If true then keyboard will be restored (activated) after focus is regained.
- * @return restoration status.
- */
- bool RestoreAfterFocusLost() const;
-
- /**
- * @brief Set status whether the IMF has to restore the keyboard after losing focus.
- *
- * @param[in] toggle True means that keyboard should be restored after focus lost and regained.
- */
- void SetRestoreAfterFocusLost( bool toggle );
-
- /**
- * @brief Send message reset the pred-edit state / imf module.
- *
- * Used to interupt pre-edit state maybe due to a touch input.
- */
- void Reset();
-
- /**
- * @brief Notifies IMF context that the cursor position has changed, required for features like auto-capitalisation.
- */
- void NotifyCursorPosition();
-
- /**
- * @brief Sets cursor position stored in VirtualKeyboard, this is required by the IMF context.
- *
- * @param[in] cursorPosition position of cursor
- */
- void SetCursorPosition( unsigned int cursorPosition );
-
- /**
- * @brief Gets cursor position stored in VirtualKeyboard, this is required by the IMF context.
- *
- * @return current position of cursor
- */
- unsigned int GetCursorPosition() const;
-
- /**
- * @brief Method to store the string required by the IMF, this is used to provide predictive word suggestions.
- *
- * @param[in] text The text string surrounding the current cursor point.
- */
- void SetSurroundingText( const std::string& text );
-
- /**
- * @brief Gets current text string set within the IMF manager, this is used to offer predictive suggestions.
- *
- * @return current position of cursor
- */
- const std::string& GetSurroundingText() const;
-
- /**
- * @brief Notifies IMF context that text input is set to multi line or not
- *
- * @param[in] multiLine True if multiline text input is used
- */
- void NotifyTextInputMultiLine( bool multiLine );
-
- /**
- * @brief Returns text direction of the keyboard's current input language.
- * @return The direction of the text.
- */
- TextDirection GetTextDirection();
-
- /**
- * @brief Provides size and position of keyboard.
- *
- * Position is relative to whether keyboard is visible or not.
- * If keyboard is not visible then position will be off the screen.
- * If keyboard is not being shown when this method is called the keyboard is partially setup (IMFContext) to get
- * the values then taken down. So ideally GetInputMethodArea() should be called after Show().
- * @return rect which is keyboard panel x, y, width, height
- */
- Dali::Rect<int> GetInputMethodArea();
-
- /**
- * @brief Set one or more of the Input Method options
- * @param[in] options The options to be applied
- */
- void ApplyOptions( const InputMethodOptions& options );
-
- /**
- * @brief Sets up the input-panel specific data.
- * @param[in] data The specific data to be set to the input panel
- */
- void SetInputPanelData( const std::string& data );
-
- /**
- * @brief Gets the specific data of the current active input panel.
- *
- * Input Panel Data is not always the data which is set by SetInputPanelData().
- * Data can be changed internally in the input panel.
- * It is just used to get a specific data from the input panel to an application.
- * @param[in] data The specific data to be got from the input panel
- */
- void GetInputPanelData( std::string& data );
-
- /**
- * @brief Gets the state of the current active input panel.
- * @return The state of the input panel.
- */
- State GetInputPanelState();
-
- /**
- * @brief Sets the return key on the input panel to be visible or invisible.
- *
- * The default is true.
- * @param[in] visible True if the return key is visible(enabled), false otherwise.
- */
- void SetReturnKeyState( bool visible );
-
- /**
- * @brief Enable to show the input panel automatically when focused.
- * @param[in] enabled If true, the input panel will be shown when focused
- */
- void AutoEnableInputPanel( bool enabled );
-
- /**
- * @brief Shows the input panel.
- */
- void ShowInputPanel();
-
- /**
- * @brief Hides the input panel.
- */
- void HideInputPanel();
-
- /**
- * @brief Gets the keyboard type.
- *
- * The default keyboard type is SOFTWARE_KEYBOARD.
- * @return The keyboard type
- */
- KeyboardType GetKeyboardType();
-
- /**
- * @brief Gets the current language locale of the input panel.
- *
- * ex) en_US, en_GB, en_PH, fr_FR, ...
- * @return The current language locale of the input panel
- */
- std::string GetInputPanelLocale();
-
-public:
-
- // Signals
-
- /**
- * @brief This is emitted when the virtual keyboard is connected to or the hardware keyboard is activated.
- *
- * @return The IMF Activated signal.
- */
- ImfManagerSignalType& ActivatedSignal();
-
- /**
- * @brief This is emitted when the IMF manager receives an event from the IMF.
- *
- * @return The Event signal containing the event data.
- */
- ImfEventSignalType& EventReceivedSignal();
-
- /**
- * @brief Connect to this signal to be notified when the virtual keyboard is shown or hidden.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(bool keyboardShown);
- * @endcode
- * If the parameter keyboardShown is true, then the keyboard has just shown, if it is false, then it
- * has just been hidden.
- * @return The signal to connect to.
- */
- StatusSignalType& StatusChangedSignal();
-
- /**
- * @brief Connect to this signal to be notified when the virtual keyboard is resized.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName( int resolvedResize );
- * @endcode
- * The parameter sends the resolved resize defined by the IMF.
- *
- * User can get changed size by using GetInputMethodArea() in the callback
- * @return The signal to connect to.
- */
- KeyboardResizedSignalType& ResizedSignal();
-
- /**
- * @brief Connect to this signal to be notified when the virtual keyboard's language is changed.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName( int resolvedLanguage );
- * @endcode
- * The parameter sends the resolved language defined by the IMF.
- *
- * User can get the text direction of the language by calling GetTextDirection() in the callback.
- * @return The signal to connect to.
- */
- LanguageChangedSignalType& LanguageChangedSignal();
-
- /**
- * @brief Connect to this signal to be notified when the keyboard type is changed.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName( KeyboardType keyboard );
- * @endcode
- *
- * @return The signal to connect to.
- */
- KeyboardTypeSignalType& KeyboardTypeChangedSignal();
-
- // Construction & Destruction
-
- /**
- * @brief Constructor.
- */
- ImfManager();
-
- /**
- * @brief Destructor
- *
- * This is non-virtual since derived Handle types must not contain data or virtual methods.
- */
- ~ImfManager();
-
- /**
- * @brief This constructor is used by ImfManager::Get().
- *
- * @param[in] imfManager A pointer to the imf Manager.
- */
- explicit DALI_INTERNAL ImfManager( Internal::Adaptor::ImfManager* imfManager );
-};
-
-} // namespace Dali
-
-#endif // __DALI_IMF_MANAGER_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <input-method-options.h>
-
-// INTERNAL INCLUDES
-#include <input-method-devel.h>
-
-using namespace Dali::InputMethod;
-using namespace Dali::InputMethod::Category;
-
-namespace Dali
-{
-
-#define TOKEN_STRING(x) #x
-
-struct InputMethodOptions::Impl
-{
- Impl()
- {
- mPanelLayout = PanelLayout::NORMAL;
- mAutoCapital = AutoCapital::SENTENCE;
- mActionButton = ActionButtonTitle::DEFAULT;
- mVariation = NormalLayout::NORMAL;
- }
-
- PanelLayout::Type mPanelLayout;
- AutoCapital::Type mAutoCapital;
- ActionButtonTitle::Type mActionButton;
- int mVariation:4;
-};
-
-InputMethodOptions::InputMethodOptions()
-{
- mImpl.reset(new Impl());
-}
-
-InputMethodOptions::~InputMethodOptions()
-{
- // destructor cannot be inlined and must be in a unit
- // for unique_ptr to work with forward declaration
-}
-
-bool InputMethodOptions::IsPassword()
-{
- return (mImpl->mPanelLayout == Dali::InputMethod::PanelLayout::PASSWORD);
-}
-
-void InputMethodOptions::ApplyProperty( const Property::Map& settings )
-{
- for ( unsigned int i = 0, count = settings.Count(); i < count; ++i )
- {
- Property::Key key = settings.GetKeyAt( i );
- if( key.type == Property::Key::INDEX )
- {
- continue;
- }
-
- Property::Value item = settings.GetValue(i);
-
- if( key == TOKEN_STRING( PANEL_LAYOUT ) )
- {
- if( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- mImpl->mPanelLayout = static_cast<InputMethod::PanelLayout::Type>(value);
- }
- }
- else if ( key == TOKEN_STRING( AUTO_CAPITALISE ) )
- {
- if ( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- mImpl->mAutoCapital = static_cast<InputMethod::AutoCapital::Type>(value);
- }
- }
- else if ( key == TOKEN_STRING( ACTION_BUTTON ) )
- {
- if ( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- mImpl->mActionButton = static_cast<InputMethod::ActionButtonTitle::Type>(value);
- }
- }
- else if( key == TOKEN_STRING( VARIATION ) )
- {
- if( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- mImpl->mVariation = value;
- }
- }
- else
- {
- }
- }
-}
-
-void InputMethodOptions::RetrieveProperty( Property::Map& settings )
-{
- settings[TOKEN_STRING( PANEL_LAYOUT )] = mImpl->mPanelLayout;
- settings[TOKEN_STRING( AUTO_CAPITALISE )] = mImpl->mAutoCapital;
- settings[TOKEN_STRING( ACTION_BUTTON )] = mImpl->mActionButton;
- settings[TOKEN_STRING( VARIATION )] = mImpl->mVariation;
-}
-
-bool InputMethodOptions::CompareAndSet( InputMethod::Category::Type type, const InputMethodOptions& options, int& index)
-{
- bool updated = false;
-
- switch (type)
- {
- case PANEL_LAYOUT:
- {
- if ( options.mImpl->mPanelLayout != mImpl->mPanelLayout )
- {
- mImpl->mPanelLayout = options.mImpl->mPanelLayout;
- index = static_cast<int>(mImpl->mPanelLayout);
- updated = true;
- }
- break;
- }
- case AUTO_CAPITALISE:
- {
- if ( options.mImpl->mAutoCapital != mImpl->mAutoCapital )
- {
- mImpl->mAutoCapital = options.mImpl->mAutoCapital;
- index = static_cast<int>(mImpl->mAutoCapital);
- updated = true;
- }
- break;
- }
- case ACTION_BUTTON_TITLE:
- {
- if ( options.mImpl->mActionButton != mImpl->mActionButton )
- {
- mImpl->mActionButton = options.mImpl->mActionButton;
- index = static_cast<int>(mImpl->mActionButton);
- updated = true;
- }
- break;
- }
- case VARIATION:
- {
- if ( options.mImpl->mVariation != mImpl->mVariation )
- {
- mImpl->mVariation = options.mImpl->mVariation;
- index = static_cast<int>(mImpl->mVariation);
- updated = true;
- }
- break;
- }
- }
- return updated;
-}
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
-#define __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <memory>
-
-#include <dali/public-api/object/property-map.h>
-
-// INTERNAL INCLUDES
-#include "input-method-devel.h"
-
-namespace Dali
-{
-
-/**
- * Class to handle the Input Method options
- */
-class DALI_IMPORT_API InputMethodOptions
-{
-public:
-
- /**
- * Constructor
- */
- InputMethodOptions(); /// Default InputMethodOptions options
-
- /**
- * Destructor
- */
- ~InputMethodOptions();
-
- /**
- * @brief Returns whether panel layout type is password or not
- * @return true if panel layout type is password, false otherwise.
- */
- bool IsPassword();
-
- /**
- * @brief Apply property map to attribute class, this class will keep the virtualKeyboard settings.
- * @param[in] settings The property map to be applied
- */
- void ApplyProperty( const Property::Map& settings );
-
- /**
- * @brief Retrieve property map from current option
- * @param[out] settings The converted property map
- */
- void RetrieveProperty( Property::Map& settings );
-
-public: // Intended for internal use
- /**
- * @brief Set option respectively
- * @param[in] type The type of source option will be updated
- * @param[in] options The source option to be applied
- * @param[out] index The updated index after applying source option
- * @return true if the value of this option is updated by source option
- */
- DALI_INTERNAL bool CompareAndSet( InputMethod::Category::Type type, const InputMethodOptions& options, int& index );
-
-private:
-
- struct Impl;
- std::unique_ptr<Impl> mImpl;
-};
-
-} // namespace Dali
-
-#endif // __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
+++ /dev/null
-#ifndef DALI_KEY_DEVEL_H
-#define DALI_KEY_DEVEL_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION
-#include <key.h>
-#else
-#include <dali/public-api/adaptor-framework/key.h>
-#endif
-
-namespace Dali
-{
-
-namespace DevelKey
-{
-
-enum Key
-{
- DALI_KEY_INVALID = Dali::DALI_KEY_INVALID,
- DALI_KEY_ESCAPE = Dali::DALI_KEY_ESCAPE,
- DALI_KEY_BACKSPACE = Dali::DALI_KEY_BACKSPACE,
- DALI_KEY_SHIFT_LEFT = Dali::DALI_KEY_SHIFT_LEFT,
- DALI_KEY_SHIFT_RIGHT = Dali::DALI_KEY_SHIFT_RIGHT,
- DALI_KEY_CURSOR_UP = Dali::DALI_KEY_CURSOR_UP,
- DALI_KEY_CURSOR_LEFT = Dali::DALI_KEY_CURSOR_LEFT,
- DALI_KEY_CURSOR_RIGHT = Dali::DALI_KEY_CURSOR_RIGHT,
- DALI_KEY_CURSOR_DOWN = Dali::DALI_KEY_CURSOR_DOWN,
- DALI_KEY_BACK = Dali::DALI_KEY_BACK,
- DALI_KEY_CAMERA = Dali::DALI_KEY_CAMERA,
- DALI_KEY_CONFIG = Dali::DALI_KEY_CONFIG,
- DALI_KEY_POWER = Dali::DALI_KEY_POWER,
- DALI_KEY_PAUSE = Dali::DALI_KEY_PAUSE,
- DALI_KEY_CANCEL = Dali::DALI_KEY_CANCEL,
- DALI_KEY_PLAY_CD = Dali::DALI_KEY_PLAY_CD,
- DALI_KEY_STOP_CD = Dali::DALI_KEY_STOP_CD,
- DALI_KEY_PAUSE_CD = Dali::DALI_KEY_PAUSE_CD,
- DALI_KEY_NEXT_SONG = Dali::DALI_KEY_NEXT_SONG,
- DALI_KEY_PREVIOUS_SONG = Dali::DALI_KEY_PREVIOUS_SONG,
- DALI_KEY_REWIND = Dali::DALI_KEY_REWIND,
- DALI_KEY_FASTFORWARD = Dali::DALI_KEY_FASTFORWARD,
- DALI_KEY_MEDIA = Dali::DALI_KEY_MEDIA,
- DALI_KEY_PLAY_PAUSE = Dali::DALI_KEY_PLAY_PAUSE,
- DALI_KEY_MUTE = Dali::DALI_KEY_MUTE,
- DALI_KEY_MENU = Dali::DALI_KEY_MENU,
- DALI_KEY_HOME = Dali::DALI_KEY_HOME,
- DALI_KEY_HOMEPAGE = Dali::DALI_KEY_HOMEPAGE,
- DALI_KEY_WEBPAGE = Dali::DALI_KEY_WEBPAGE,
- DALI_KEY_MAIL = Dali::DALI_KEY_MAIL,
- DALI_KEY_SCREENSAVER = Dali::DALI_KEY_SCREENSAVER,
- DALI_KEY_BRIGHTNESS_UP = Dali::DALI_KEY_BRIGHTNESS_UP,
- DALI_KEY_BRIGHTNESS_DOWN = Dali::DALI_KEY_BRIGHTNESS_DOWN,
- DALI_KEY_SOFT_KBD = Dali::DALI_KEY_SOFT_KBD,
- DALI_KEY_QUICK_PANEL = Dali::DALI_KEY_QUICK_PANEL,
- DALI_KEY_TASK_SWITCH = Dali::DALI_KEY_TASK_SWITCH,
- DALI_KEY_APPS = Dali::DALI_KEY_APPS,
- DALI_KEY_SEARCH = Dali::DALI_KEY_SEARCH,
- DALI_KEY_VOICE = Dali::DALI_KEY_VOICE,
- DALI_KEY_LANGUAGE = Dali::DALI_KEY_LANGUAGE,
- DALI_KEY_VOLUME_UP = Dali::DALI_KEY_VOLUME_UP,
- DALI_KEY_VOLUME_DOWN = Dali::DALI_KEY_VOLUME_DOWN,
-
- /**
- * @brief Delete key.
- */
- DALI_KEY_DELETE = 119,
-
- /**
- * @brief Control Left key.
- */
- DALI_KEY_CONTROL_LEFT = 37,
-
- /**
- * @brief Control Right key.
- */
- DALI_KEY_CONTROL_RIGHT = 105,
-
- /**
- * @brief Control Return key.
- */
- DALI_KEY_RETURN = 36
-
-};
-
-} // namespace DevelKey
-
-} // namespace Dali
-
-#endif // DALI_KEY_DEVEL_H
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <lifecycle-controller.h>
-
-// INTERNAL INCLUDES
-#include <lifecycle-controller-impl.h>
-
-namespace Dali
-{
-
-LifecycleController::LifecycleController()
-{
-}
-
-LifecycleController::LifecycleController(const LifecycleController& controller)
-: BaseHandle(controller)
-{
-}
-
-LifecycleController LifecycleController::Get()
-{
- return Internal::Adaptor::LifecycleController::Get();
-}
-
-LifecycleController::~LifecycleController()
-{
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::InitSignal()
-{
- return GetImplementation(*this).InitSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::TerminateSignal()
-{
- return GetImplementation(*this).TerminateSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::PauseSignal()
-{
- return GetImplementation(*this).PauseSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::ResumeSignal()
-{
- return GetImplementation(*this).ResumeSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::ResetSignal()
-{
- return GetImplementation(*this).ResetSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::ResizeSignal()
-{
- return GetImplementation(*this).ResizeSignal();
-}
-
-LifecycleController::LifecycleSignalType& LifecycleController::LanguageChangedSignal()
-{
- return GetImplementation(*this).LanguageChangedSignal();
-}
-
-LifecycleController& LifecycleController::operator=(const LifecycleController& monitor)
-{
- if( *this != monitor )
- {
- BaseHandle::operator=(monitor);
- }
- return *this;
-}
-
-LifecycleController::LifecycleController(Internal::Adaptor::LifecycleController* internal)
-: BaseHandle(internal)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <orientation.h>
-
-// INTERNAL INCLUDES
-#include <orientation-impl.h>
-
-namespace Dali
-{
-
-Orientation::Orientation()
-{
-}
-
-Orientation::~Orientation()
-{
-}
-
-Orientation::Orientation(const Orientation& handle)
-: BaseHandle(handle)
-{
-}
-
-Orientation& Orientation::operator=(const Orientation& rhs)
-{
- BaseHandle::operator=(rhs);
- return *this;
-}
-
-int Orientation::GetDegrees() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetDegrees();
-}
-
-float Orientation::GetRadians() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetRadians();
-}
-
-Orientation::OrientationSignalType& Orientation::ChangedSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).ChangedSignal();
-}
-
-Orientation::Orientation( Internal::Adaptor::Orientation* orientation )
-: BaseHandle(orientation)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <performance-logger.h>
-
-// INTERNAL INCLUDES
-#include <performance-logger-impl.h>
-
-namespace Dali
-{
-
-PerformanceLogger::PerformanceLogger()
-{
-}
-
-PerformanceLogger PerformanceLogger::New( const char* name )
-{
- Internal::Adaptor::PerformanceLoggerPtr internal = Internal::Adaptor::PerformanceLogger::New( name );
- return PerformanceLogger(internal.Get());
-}
-
-PerformanceLogger::PerformanceLogger( const PerformanceLogger& performanceLogger )
-: BaseHandle(performanceLogger)
-{
-}
-
-PerformanceLogger& PerformanceLogger::operator=( const PerformanceLogger& performanceLogger )
-{
- // check self assignment
- if( *this != performanceLogger )
- {
- BaseHandle::operator=(performanceLogger);
- }
- return *this;
-}
-
-PerformanceLogger::~PerformanceLogger()
-{
-}
-
-PerformanceLogger PerformanceLogger::DownCast( BaseHandle handle )
-{
- return PerformanceLogger( dynamic_cast<Internal::Adaptor::PerformanceLogger*>( handle.GetObjectPtr() ) );
-}
-
-void PerformanceLogger::AddMarker( Marker markerType )
-{
- Internal::Adaptor::GetImplementation(*this).AddMarker( markerType );
-}
-
-void PerformanceLogger::SetLoggingFrequency( unsigned int logFrequency)
-{
- Internal::Adaptor::GetImplementation(*this).SetLoggingFrequency( logFrequency );
-}
-
-void PerformanceLogger::EnableLogging( bool enable )
-{
- Internal::Adaptor::GetImplementation(*this).EnableLogging( enable );
-}
-
-PerformanceLogger::PerformanceLogger(Internal::Adaptor::PerformanceLogger* PerformanceLogger)
-: BaseHandle(PerformanceLogger)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <physical-keyboard.h>
-
-// INTERNAL INCLUDES
-#include <physical-keyboard-impl.h>
-
-namespace Dali
-{
-
-PhysicalKeyboard::PhysicalKeyboard()
-{
-}
-
-PhysicalKeyboard::~PhysicalKeyboard()
-{
-}
-
-PhysicalKeyboard PhysicalKeyboard::Get()
-{
- // Get the physical keyboard handle
- PhysicalKeyboard handle = Internal::Adaptor::PhysicalKeyboard::Get();
-
- // If it's not been created then create one
- if ( !handle )
- {
- handle = Internal::Adaptor::PhysicalKeyboard::New();
- }
-
- return handle;
-}
-
-bool PhysicalKeyboard::IsAttached() const
-{
- return GetImplementation( *this ).IsAttached();
-}
-
-PhysicalKeyboard::PhysicalKeyboardSignalType& PhysicalKeyboard::StatusChangedSignal()
-{
- return GetImplementation( *this ).StatusChangedSignal();
-}
-
-PhysicalKeyboard::PhysicalKeyboard( Internal::Adaptor::PhysicalKeyboard *impl )
-: BaseHandle(impl)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pixel-buffer.h"
-
-// EXTERNAL INLCUDES
-#include <stdlib.h>
-
-// INTERNAL INCLUDES
-#include <pixel-buffer-impl.h>
-
-namespace Dali
-{
-namespace Devel
-{
-
-PixelBuffer PixelBuffer::New( unsigned int width,
- unsigned int height,
- Dali::Pixel::Format pixelFormat )
-{
- Internal::Adaptor::PixelBufferPtr internal =
- Internal::Adaptor::PixelBuffer::New( width, height, pixelFormat );
- return Devel::PixelBuffer( internal.Get() );
-}
-
-Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer )
-{
- Dali::PixelData pixelData =
- Internal::Adaptor::PixelBuffer::Convert( GetImplementation(pixelBuffer) );
- pixelBuffer.Reset();
- return pixelData;
-}
-
-Dali::PixelData PixelBuffer::CreatePixelData() const
-{
- return GetImplementation(*this).CreatePixelData();
-}
-
-
-PixelBuffer::PixelBuffer()
-{
-}
-
-PixelBuffer::~PixelBuffer()
-{
-}
-
-PixelBuffer::PixelBuffer( Internal::Adaptor::PixelBuffer* internal )
-: BaseHandle( internal )
-{
-}
-
-PixelBuffer::PixelBuffer(const PixelBuffer& handle)
-: BaseHandle( handle )
-{
-}
-
-PixelBuffer& PixelBuffer::operator=(const PixelBuffer& rhs)
-{
- BaseHandle::operator=(rhs);
- return *this;
-}
-
-unsigned int PixelBuffer::GetWidth() const
-{
- return GetImplementation(*this).GetWidth();
-}
-
-unsigned int PixelBuffer::GetHeight() const
-{
- return GetImplementation(*this).GetHeight();
-}
-
-Pixel::Format PixelBuffer::GetPixelFormat() const
-{
- return GetImplementation(*this).GetPixelFormat();
-}
-
-unsigned char* PixelBuffer::GetBuffer()
-{
- return GetImplementation(*this).GetBuffer();
-}
-
-void PixelBuffer::ApplyMask( PixelBuffer mask, float contentScale, bool cropToMask )
-{
- GetImplementation(*this).ApplyMask( GetImplementation( mask ), contentScale, cropToMask );
-}
-
-void PixelBuffer::ApplyGaussianBlur( const float blurRadius )
-{
- GetImplementation(*this).ApplyGaussianBlur( blurRadius );
-}
-
-void PixelBuffer::Crop( uint16_t x, uint16_t y, uint16_t width, uint16_t height )
-{
- GetImplementation(*this).Crop( x, y, ImageDimensions( width, height ) );
-}
-
-void PixelBuffer::Resize( uint16_t width, uint16_t height )
-{
- GetImplementation(*this).Resize( ImageDimensions( width, height ) );
-}
-
-void PixelBuffer::MultiplyColorByAlpha()
-{
- GetImplementation(*this).MultiplyColorByAlpha();
-}
-
-bool PixelBuffer::GetMetadata( Property::Map& metadata ) const
-{
- return GetImplementation(*this).GetMetadata(metadata);
-}
-
-} // namespace Devel
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <singleton-service.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-SingletonService::SingletonService()
-{
-}
-
-SingletonService SingletonService::New()
-{
- return Internal::Adaptor::SingletonService::New();
-}
-
-SingletonService SingletonService::Get()
-{
- return Internal::Adaptor::SingletonService::Get();
-}
-
-SingletonService::~SingletonService()
-{
-}
-
-void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
-{
- GetImplementation( *this ).Register( info, singleton );
-}
-
-void SingletonService::UnregisterAll()
-{
- GetImplementation( *this ).UnregisterAll();
-}
-
-BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
-{
- return GetImplementation( *this ).GetSingleton( info );
-}
-
-SingletonService::SingletonService( Internal::Adaptor::SingletonService* singletonService )
-: BaseHandle( singletonService )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <sound-player.h>
-
-// INTERNAL INCLUDES
-#include <sound-player-impl.h>
-
-namespace Dali
-{
-
-SoundPlayer::SoundPlayer()
-{
-}
-
-SoundPlayer SoundPlayer::Get()
-{
- return Internal::Adaptor::SoundPlayer::Get();
-}
-
-SoundPlayer::~SoundPlayer()
-{
-}
-
-int SoundPlayer::PlaySound(const std::string fileName)
-{
- return GetImplementation(*this).PlaySound(fileName);
-}
-
-void SoundPlayer::Stop(int handle)
-{
- GetImplementation(*this).Stop(handle);
-}
-
-SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal()
-{
- return GetImplementation(*this).SoundPlayFinishedSignal();
-}
-
-SoundPlayer::SoundPlayer( Internal::Adaptor::SoundPlayer* player )
-: BaseHandle( player )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <style-monitor.h>
-
-// INTERNAL INCLUDES
-#include <style-monitor-impl.h>
-
-namespace Dali
-{
-
-StyleMonitor::StyleMonitor()
-{
-}
-
-StyleMonitor::StyleMonitor(const StyleMonitor& monitor)
-: BaseHandle(monitor)
-{
-}
-
-StyleMonitor StyleMonitor::StyleMonitor::Get()
-{
- return Internal::Adaptor::StyleMonitor::Get();
-}
-
-StyleMonitor::~StyleMonitor()
-{
-}
-
-StyleMonitor StyleMonitor::DownCast( BaseHandle handle )
-{
- return StyleMonitor( dynamic_cast<Internal::Adaptor::StyleMonitor*>( handle.GetObjectPtr() ) );
-}
-
-std::string StyleMonitor::GetDefaultFontFamily() const
-{
- return GetImplementation(*this).GetDefaultFontFamily();
-}
-
-std::string StyleMonitor::GetDefaultFontStyle() const
-{
- return GetImplementation(*this).GetDefaultFontStyle();
-}
-
-int StyleMonitor::GetDefaultFontSize() const
-{
- return GetImplementation(*this).GetDefaultFontSize();
-}
-
-const std::string& StyleMonitor::GetTheme() const
-{
- return GetImplementation(*this).GetTheme();
-}
-
-void StyleMonitor::SetTheme(const std::string& themFilePath)
-{
- return GetImplementation(*this).SetTheme(themFilePath);
-}
-
-bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
-{
- return GetImplementation(*this).LoadThemeFile( filename, output );
-}
-
-StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
-{
- return GetImplementation(*this).StyleChangeSignal();
-}
-
-StyleMonitor& StyleMonitor::operator=(const StyleMonitor& monitor)
-{
- if( *this != monitor )
- {
- BaseHandle::operator=(monitor);
- }
- return *this;
-}
-
-StyleMonitor::StyleMonitor(Internal::Adaptor::StyleMonitor* internal)
-: BaseHandle(internal)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_STYLE_MONITOR_H__
-#define __DALI_STYLE_MONITOR_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-#include <dali/public-api/object/base-handle.h>
-#include <dali/public-api/signals/dali-signal.h>
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-// @todo Make dali-adaptor code folder structure mirror the folder structure installed to dali-env
-#include <style-change.h>
-#else
-#include <dali/public-api/adaptor-framework/style-change.h>
-#endif
-
-namespace Dali
-{
-
-namespace Internal DALI_INTERNAL
-{
-namespace Adaptor
-{
-class StyleMonitor;
-}
-}
-
-/**
- * @brief Monitors the platform for style changes.
- *
- * This is a handle to the adaptor's style monitor which holds the platform's style information.
- * It provides a signal when any aspect of the default style changes on the device.
- * @see Adaptor::GetStyleMonitor
- */
-class DALI_IMPORT_API StyleMonitor : public BaseHandle
-{
-public: // Typedefs
-
- typedef Signal< void ( StyleMonitor, StyleChange::Type ) > StyleChangeSignalType; ///< StyleChange Signal type
-
-public: // Creation & Destruction
-
- /**
- * @brief Create an uninitialized StyleMonitor handle.
- *
- * Tthis can be set by retrieving the style monitor from the Adaptor
- * or the Application classes. Calling member functions when
- * uninitialized is not allowed.
- */
- StyleMonitor();
-
- /**
- * @brief Creates a copy of the handle.
- *
- * The copy will point to the same implementation as the original.
- * @param[in] monitor The Style Monitor to copy from.
- */
- StyleMonitor(const StyleMonitor& monitor);
-
- /**
- * @brief Retrieve the initialized instance of the StyleMonitor.
- * @return Handle to StyleMonitor.
- */
- static StyleMonitor Get();
-
- /**
- * @brief Destructor
- *
- * This is non-virtual since derived Handle types must not contain data or virtual methods.
- */
- ~StyleMonitor();
-
- /**
- * @brief Downcast an Object handle to StyleMonitor handle.
- *
- * If handle points to a StyleMonitor object the downcast produces a
- * valid handle. If not the returned handle is left uninitialized.
- *
- * @param[in] handle to An object @return handle to a Timer object
- * or an uninitialized handle
- */
- static StyleMonitor DownCast( BaseHandle handle );
-
-public: // Style Information
-
- /**
- * @brief Retrieves the default font family.
- * @return The default font family.
- */
- std::string GetDefaultFontFamily() const;
-
- /**
- * @brief Retrieves the default font style.
- * @return The default font style.
- */
- std::string GetDefaultFontStyle() const;
-
- /**
- * @brief Retrieves the default font size.
- *
- * This is an logical size, which is mapped to a UI Control specific point-size in stylesheets.
- * For example if zero the smallest size, this could potentially map to TextLabel point-size 8.
- * @return The default font size, or a negative value if not set.
- */
- int GetDefaultFontSize() const;
-
- /**
- * @brief Retrieves the user defined Theme.
- * @return The user defined Theme.
- */
- const std::string& GetTheme() const;
-
- /**
- * @brief Sets an user defined Theme.
- * @param[in] themeFilePath Path of the user defined theme
- */
- void SetTheme(const std::string& themeFilePath);
-
- /**
- * @brief Utility to load a theme file
- * @param filename of the theme
- * @param output to write the contents to
- * @return true if the load is successful
- */
- bool LoadThemeFile( const std::string& filename, std::string& output );
-
-public: // Signals
-
- /**
- * @brief This signal is emitted whenever the style changes on the device.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(StyleMonitor styleMonitor, StyleChange change);
- * @endcode
- * @return The signal to connect to.
- */
- StyleChangeSignalType& StyleChangeSignal();
-
-public: // Operators
-
- /**
- * @brief Assignment operator.
- *
- * The handle points to the same implementation as the one being copied from.
- * @param[in] monitor The Style Monitor to copy from.
- * @return reference to this object
- */
- StyleMonitor& operator=(const StyleMonitor& monitor);
-
-public: // Not intended for application developers
- /**
- * @brief This constructor is used internally to create a handle from an object pointer.
- * @param [in] styleMonitor A pointer the internal style monitor.
- */
- explicit DALI_INTERNAL StyleMonitor(Internal::Adaptor::StyleMonitor* styleMonitor);
-};
-
-} // namespace Dali
-
-#endif // __DALI_STYLE_MONITOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tilt-sensor.h"
-
-// INTERNAL INCLUDES
-#include <tilt-sensor-impl.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-const float TiltSensor::DEFAULT_UPDATE_FREQUENCY = 60.0f;
-
-TiltSensor::TiltSensor()
-{
-}
-
-TiltSensor TiltSensor::Get()
-{
- return Internal::Adaptor::TiltSensor::Get();
-}
-
-TiltSensor::~TiltSensor()
-{
-}
-
-bool TiltSensor::Start()
-{
- return GetImplementation(*this).Start();
-}
-
-void TiltSensor::Stop()
-{
- GetImplementation(*this).Stop();
-}
-
-bool TiltSensor::IsStarted() const
-{
- return GetImplementation(*this).IsStarted();
-}
-
-float TiltSensor::GetRoll() const
-{
- return GetImplementation(*this).GetRoll();
-}
-
-float TiltSensor::GetPitch() const
-{
- return GetImplementation(*this).GetPitch();
-}
-
-Quaternion TiltSensor::GetRotation() const
-{
- return GetImplementation(*this).GetRotation();
-}
-
-TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal()
-{
- return GetImplementation(*this).TiltedSignal();
-}
-
-void TiltSensor::SetUpdateFrequency( float frequencyHertz )
-{
- GetImplementation(*this).SetUpdateFrequency( frequencyHertz );
-}
-
-float TiltSensor::GetUpdateFrequency() const
-{
- return GetImplementation(*this).GetUpdateFrequency();
-}
-
-void TiltSensor::SetRotationThreshold(Radian rotationThreshold)
-{
- GetImplementation(*this).SetRotationThreshold( rotationThreshold );
-}
-
-Radian TiltSensor::GetRotationThreshold() const
-{
- return GetImplementation(*this).GetRotationThreshold();
-}
-
-TiltSensor::TiltSensor( Internal::Adaptor::TiltSensor* sensor )
-: BaseHandle( sensor )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <video-player.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/any.h>
-
-// INTERNAL INCLUDES
-#include <video-player-impl.h>
-
-namespace Dali
-{
-
-VideoPlayer::VideoPlayer()
-{
-}
-
-VideoPlayer::VideoPlayer( Internal::Adaptor::VideoPlayer* internal )
-: BaseHandle( internal )
-{
-}
-
-VideoPlayer::~VideoPlayer()
-{
-}
-
-VideoPlayer VideoPlayer::New()
-{
- Internal::Adaptor::VideoPlayerPtr player = Internal::Adaptor::VideoPlayer::New();
-
- if( player )
- {
- player->Initialize();
- }
-
- return VideoPlayer( player.Get() );
-}
-
-VideoPlayer::VideoPlayer( const VideoPlayer& player )
-: BaseHandle( player )
-{
-}
-
-VideoPlayer& VideoPlayer::operator=( const VideoPlayer& player )
-{
- if( *this != player )
- {
- BaseHandle::operator=( player );
- }
- return *this;
-}
-
-VideoPlayer VideoPlayer::DownCast( BaseHandle handle )
-{
- return VideoPlayer( dynamic_cast< Internal::Adaptor::VideoPlayer* >( handle.GetObjectPtr() ) );
-}
-
-void VideoPlayer::SetUrl( const std::string& url )
-{
- GetImplementation( *this ).SetUrl( url );
-}
-
-std::string VideoPlayer::GetUrl()
-{
- return GetImplementation( *this ).GetUrl();
-}
-
-void VideoPlayer::SetLooping(bool looping)
-{
- GetImplementation( *this ).SetLooping( looping );
-}
-
-bool VideoPlayer::IsLooping()
-{
- return GetImplementation( *this ).IsLooping();
-}
-
-void VideoPlayer::Play()
-{
- GetImplementation( *this ).Play();
-}
-
-void VideoPlayer::Pause()
-{
- GetImplementation( *this ).Pause();
-}
-
-void VideoPlayer::Stop()
-{
- GetImplementation( *this ).Stop();
-}
-
-void VideoPlayer::SetMute( bool mute )
-{
- GetImplementation( *this ).SetMute( mute );
-}
-
-bool VideoPlayer::IsMuted()
-{
- return GetImplementation( *this ).IsMuted();
-}
-
-void VideoPlayer::SetVolume( float left, float right )
-{
- GetImplementation( *this ).SetVolume( left, right );
-}
-
-void VideoPlayer::GetVolume( float& left, float& right )
-{
- GetImplementation( *this ).GetVolume( left, right );
-}
-
-void VideoPlayer::SetRenderingTarget( Any target )
-{
- GetImplementation( *this ).SetRenderingTarget( target );
-}
-
-void VideoPlayer::SetPlayPosition( int millisecond )
-{
- GetImplementation( *this ).SetPlayPosition( millisecond );
-}
-
-int VideoPlayer::GetPlayPosition()
-{
- return GetImplementation( *this ).GetPlayPosition();
-}
-
-void VideoPlayer::SetDisplayArea( DisplayArea area )
-{
- GetImplementation( *this ).SetDisplayArea( area );
-}
-
-void VideoPlayer::SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation )
-{
- GetImplementation( *this ).SetDisplayRotation( rotation );
-}
-
-Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation()
-{
- return GetImplementation( *this ).GetDisplayRotation();
-}
-
-Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal()
-{
- return GetImplementation( *this ).FinishedSignal();
-}
-
-void VideoPlayer::Forward( int millisecond )
-{
- GetImplementation( *this ).Forward( millisecond );
-}
-
-void VideoPlayer::Backward( int millisecond )
-{
- GetImplementation( *this ).Backward( millisecond );
-}
-
-bool VideoPlayer::IsVideoTextureSupported() const
-{
- return GetImplementation( *this ).IsVideoTextureSupported();
-}
-
-} // namespace Dali;
-
+++ /dev/null
-#ifndef __DALI_VIDEO_PLAYER_H__
-#define __DALI_VIDEO_PLAYER_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-handle.h>
-
-//INTERNAL INCLUDES
-#include "video-player-plugin.h"
-
-namespace Dali
-{
-
-class Any;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
- class VideoPlayer;
-} // namespace Adaptor
-
-} // namespace Internal
-
-/**
- * @brief VideoPlayer class is used for video playback.
- * @SINCE_1_1.38
- */
-class DALI_IMPORT_API VideoPlayer: public BaseHandle
-{
-public:
-
- /**
- * @brief Constructor.
- * @SINCE_1_1.38
- */
- VideoPlayer();
-
- /**
- * @brief Destructor.
- * @SINCE_1_1.38
- */
- ~VideoPlayer();
-
- /**
- * @brief Creates a new instance of a VideoPlayer.
- * @SINCE_1_1.38
- */
- static VideoPlayer New();
-
- /**
- * @brief Copy constructor.
- *
- * @SINCE_1_1.38
- * @param[in] player VideoPlayer to copy. The copied player will point at the same implementation
- */
- VideoPlayer( const VideoPlayer& player );
-
- /**
- * @brief Assignment operator.
- *
- * @SINCE_1_1.38
- * @param[in] player The VideoPlayer to assign from.
- * @return The updated VideoPlayer.
- */
- VideoPlayer& operator=( const VideoPlayer& player );
-
- /**
- * @brief Downcast a handle to VideoPlayer handle.
- *
- * If handle points to a VideoPlayer the downcast produces valid
- * handle. If not the returned handle is left uninitialized.
- *
- * @SINCE_1_1.38
- * @param[in] handle Handle to an object
- * @return Handle to a VideoPlayer or an uninitialized handle
- */
- static VideoPlayer DownCast( BaseHandle handle );
-
- /**
- * @brief Sets a URL of the video file to play.
- *
- * @SINCE_1_1.38
- * @param [in] url The url of video file
- */
- void SetUrl( const std::string& url );
-
- /**
- * @brief Returns the URL of the video file.
- * @SINCE_1_1.38
- * @return Url of string type
- */
- std::string GetUrl();
-
- /**
- * @brief Sets the player looping status.
- * @SINCE_1_1.38
- *
- * @param [in] looping The new looping status: true or false
- */
- void SetLooping(bool looping);
-
- /**
- * @brief Returns the player looping status.
- * @SINCE_1_1.38
- *
- * @return True if player is looping, false otherwise.
- */
- bool IsLooping();
-
- /**
- * @brief Starts the video playback.
- * @SINCE_1_1.38
- */
- void Play();
-
- /**
- * @brief Pauses the video playback.
- * @SINCE_1_1.38
- */
- void Pause();
-
- /**
- * @brief Stops the video playback.
- * @SINCE_1_1.38
- */
- void Stop();
-
- /**
- * @brief Sets the player mute status.
- * @SINCE_1_1.38
- * @param[in] mute The new mute status, true is mute.
- */
- void SetMute( bool mute );
-
- /**
- * @brief Returns the player mute status.
- * @SINCE_1_1.38
- * @return True if player is mute.
- */
- bool IsMuted();
-
- /**
- * @brief Sets the player volume.
- * @SINCE_1_1.38
- * @param[in] left The left volume scalar
- * @param[in] right The right volume scalar
- */
- void SetVolume( float left, float right );
-
- /**
- * @brief Returns current volume factor.
- * @SINCE_1_1.38
- * @param[out] left The current left volume scalar
- * @param[out] right The current right volume scalar
- */
- void GetVolume( float& left, float& right );
-
- /**
- * @brief Sets video rendering target.
- * @SINCE_1_1.38
- * @param[in] target The target for video rendering, window surface or native image source
- */
- void SetRenderingTarget( Any target );
-
- /**
- * @brief Sets the position for playback.
- * @SINCE_1_1.38
- *
- * @param[in] millisecond The position for playback
- */
- void SetPlayPosition( int millisecond );
-
- /**
- * @brief Gets the current position in milliseconds.
- * @SINCE_1_1.38
- *
- * @return The current position of playback
- */
- int GetPlayPosition();
-
- /**
- * @brief Sets the area of video display.
- * @SINCE_1_2.46
- * param[in] area The left-top position and size of the video display area
- */
- void SetDisplayArea( DisplayArea area );
-
- /**
- * @brief Sets video display rotation
- * @SINCE_1_1.38
- * @param[in] rotation The rotation of display
- */
- void SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation );
-
- /**
- * @brief Returns rotation of current video display
- * @SINCE_1_1.38
- * @return The rotation of current display
- */
- Dali::VideoPlayerPlugin::DisplayRotation GetDisplayRotation();
-
- /**
- * @brief Connect to this signal to be notified when a video playback have finished.
- *
- * @SINCE_1_1.38
- * @return A signal object to connect with.
- */
- Dali::VideoPlayerPlugin::VideoPlayerSignalType& FinishedSignal();
-
- /**
- * @brief Seeks forward by the specified number of milliseconds.
- *
- * @SINCE_1_2.46
- * @param[in] millisecond The position for forward playback
- */
- void Forward( int millisecond );
-
- /**
- * @brief Seeks backward by the specified number of milliseconds.
- *
- * @SINCE_1_2.46
- * @param[in] millisecond The position for backward playback
- */
- void Backward( int millisecond );
-
- /**
- * @brief Checks whether the video texture is supported
- * @return True if supported, otherwise false.
- */
- bool IsVideoTextureSupported() const;
-
-private: // Not intended for application developers
-
- /**
- * @brief Internal constructor
- * @SINCE_1_1.38
- */
- explicit DALI_INTERNAL VideoPlayer( Internal::Adaptor::VideoPlayer* internal );
-};
-
-} // namespace Dali;
-
-#endif
-
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <virtual-keyboard.h>
-
-// INTERNAL INCLUDES
-#include <virtual-keyboard-impl.h>
-
-namespace Dali
-{
-
-namespace VirtualKeyboard
-{
-
-void Show()
-{
- Internal::Adaptor::VirtualKeyboard::Show();
-}
-
-void Hide()
-{
- Internal::Adaptor::VirtualKeyboard::Hide();
-}
-
-bool IsVisible()
-{
- return Internal::Adaptor::VirtualKeyboard::IsVisible();
-}
-
-void ApplySettings( const Property::Map& settingsMap )
-{
- Internal::Adaptor::VirtualKeyboard::ApplySettings( settingsMap );
-}
-
-void SetReturnKeyType( const InputMethod::ActionButton type )
-{
- Internal::Adaptor::VirtualKeyboard::SetReturnKeyType( type );
-}
-
-InputMethod::ActionButton GetReturnKeyType()
-{
- return Internal::Adaptor::VirtualKeyboard::GetReturnKeyType();
-}
-
-void EnablePrediction(const bool enable)
-{
- Internal::Adaptor::VirtualKeyboard::EnablePrediction(enable);
-}
-
-bool IsPredictionEnabled()
-{
- return Internal::Adaptor::VirtualKeyboard::IsPredictionEnabled();
-}
-
-Rect<int> GetSizeAndPosition()
-{
- return Internal::Adaptor::VirtualKeyboard::GetSizeAndPosition();
-}
-
-void RotateTo(int angle)
-{
- Internal::Adaptor::VirtualKeyboard::RotateTo(angle);
-}
-
-StatusSignalType& StatusChangedSignal()
-{
- return Internal::Adaptor::VirtualKeyboard::StatusChangedSignal();
-}
-
-KeyboardResizedSignalType& ResizedSignal()
-{
- return Internal::Adaptor::VirtualKeyboard::ResizedSignal();
-}
-
-LanguageChangedSignalType& LanguageChangedSignal()
-{
- return Internal::Adaptor::VirtualKeyboard::LanguageChangedSignal();
-}
-
-TextDirection GetTextDirection()
-{
- return Internal::Adaptor::VirtualKeyboard::GetTextDirection();
-}
-
-} // namespace VirtualKeyboard
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_VIRTUAL_KEYBOARD_H__
-#define __DALI_VIRTUAL_KEYBOARD_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/signals/dali-signal.h>
-#include <dali/public-api/object/property-map.h>
-#include <dali/public-api/math/rect.h>
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-// @todo Make dali-adaptor code folder structure mirror the folder structure installed to dali-env
-#include "input-method.h"
-#else
-#include <dali/public-api/adaptor-framework/input-method.h>
-#endif
-
-namespace Dali
-{
-
-/**
- * @brief This namespace is provided for application developers to be able to show and hide the on-screen keyboard.
- *
- * Key events are sent to the actor in focus. Focus is set through the actor Public API.
- */
-namespace VirtualKeyboard
-{
-
-// Types
-
-typedef Signal< void () > VoidSignalType;
-typedef Signal< void ( bool ) > StatusSignalType;
-typedef Signal< void ( int ) > KeyboardResizedSignalType;
-typedef Signal< void ( int ) > LanguageChangedSignalType;
-
-// Enumerations
-
-/**
- * @brief The direction of text.
- */
-enum TextDirection
-{
- LeftToRight,
- RightToLeft,
-};
-
-/**
- * @brief The meaning of the return key.
- */
-enum ReturnKeyType
-{
- DEFAULT,
- DONE,
- GO,
- JOIN,
- LOGIN,
- NEXT,
- SEARCH,
- SEND,
- SIGNIN
-};
-
-// Functions
-/**
- * @brief Show the virtual keyboard.
- */
-DALI_IMPORT_API void Show();
-
-/**
- * @brief Hide the virtual keyboard.
- */
-DALI_IMPORT_API void Hide();
-
-/**
- * @brief Returns whether the virtual keyboard is visible or not.
- * @return true if visible, false otherwise.
- */
-DALI_IMPORT_API bool IsVisible();
-
-/**
- * @brief Set one or more of the Input Method Settings
- * @param[in] settingsMap Map of Settings to be applied.
- */
-DALI_IMPORT_API void ApplySettings( const Property::Map& settingsMap );
-
-/**
- * @brief Set the specific return key into the virtual keyboard.
- * @param[in] type the kind of return key types.
- */
-DALI_IMPORT_API void SetReturnKeyType( const InputMethod::ActionButton type );
-
-/**
- * @brief Retrieve the current return key type.
- * @return the type of retun key.
- */
-DALI_IMPORT_API InputMethod::ActionButton GetReturnKeyType();
-
-/**
- * @brief Enable/disable prediction (predictive text).
- *
- * By default prediction text is enabled.
- * @param[in] enable true or false to enable or disable
- * Prediction can not be changed while the keyboard is visible. It must be set in advance of showing keyboard.
- */
-DALI_IMPORT_API void EnablePrediction(const bool enable);
-
-/**
- * @brief Returns whether prediction is enabled in the virtual keyboard
- * @return true if predictive text enabled, false otherwise.
- */
-DALI_IMPORT_API bool IsPredictionEnabled();
-
-/**
- * @brief Provides size and position of keyboard.
- *
- * Position is relative to whether keyboard is visible or not.
- * If keyboard is not visible then position will be off the screen.
- * If keyboard is not being shown when this method is called the keyboard is partially setup (IMFContext) to get
- * the values then taken down. So ideally GetSizeAndPosition() should be called after Show().
- * @return rect which is keyboard panel x, y, width, height
- */
-DALI_IMPORT_API Dali::Rect<int> GetSizeAndPosition();
-
-/**
- * @brief Rotates the keyboard orientation to the given angle.
- *
- * A value of 0 indicates the portrait orientation.
- * Other valid values are 90, 180, 270.
- * @param angle the angle is in degrees.
- */
-DALI_IMPORT_API void RotateTo(int angle);
-
-/**
- * @brief Returns text direction of the keyboard's current input language.
- * @return The direction of the text.
- */
-DALI_IMPORT_API TextDirection GetTextDirection();
-
-/**
- * @brief Connect to this signal to be notified when the virtual keyboard is shown or hidden.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(bool keyboardShown);
- * @endcode
- * If the parameter keyboardShown is true, then the keyboard has just shown, if it is false, then it
- * has just been hidden.
- * @return The signal to connect to.
- */
-DALI_IMPORT_API StatusSignalType& StatusChangedSignal();
-
-/**
- * @brief Connect to this signal to be notified when the virtual keyboard is resized.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName( int resolvedResize );
- * @endcode
- * The parameter sends the resolved resize defined by the IMF.
- *
- * User can get changed size by using GetSizeAndPosition() in the callback
- * @return The signal to connect to.
- */
-DALI_IMPORT_API KeyboardResizedSignalType& ResizedSignal();
-
-/**
- * @brief Connect to this signal to be notified when the virtual keyboard's language is changed.
- *
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName( int resolvedLanguage );
- * @endcode
- * The parameter sends the resolved language defined by the IMF.
- *
- * User can get the text direction of the language by calling GetTextDirection() in the callback.
- * @return The signal to connect to.
- */
-DALI_IMPORT_API LanguageChangedSignalType& LanguageChangedSignal();
-
-} // namespace VirtualKeyboard
-
-} // namespace Dali
-
-#endif // __DALI_VIRTUAL_KEYBOARD_H__
+++ /dev/null
-devel_api_src_files = \
- $(adaptor_devel_api_dir)/adaptor-framework/accessibility-adaptor.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/application-devel.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/application-extensions.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/bitmap-saver.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/clipboard.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/clipboard-event-notifier.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/color-controller.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/drag-and-drop-detector.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/environment-variable.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/event-feeder.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/event-thread-callback.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/feedback-player.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/file-loader.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/image-loading.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/gif-loading.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/imf-manager.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/input-method-options.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/orientation.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/performance-logger.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/physical-keyboard.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/pixel-buffer.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/singleton-service.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/sound-player.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/style-monitor.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/tilt-sensor.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/lifecycle-controller.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/video-player.cpp \
- $(adaptor_devel_api_dir)/adaptor-framework/virtual-keyboard.cpp
-
-
-devel_api_adaptor_framework_header_files = \
- $(adaptor_devel_api_dir)/adaptor-framework/accessibility-adaptor.h \
- $(adaptor_devel_api_dir)/adaptor-framework/accessibility-action-handler.h \
- $(adaptor_devel_api_dir)/adaptor-framework/accessibility-gesture-handler.h \
- $(adaptor_devel_api_dir)/adaptor-framework/application-devel.h \
- $(adaptor_devel_api_dir)/adaptor-framework/application-extensions.h \
- $(adaptor_devel_api_dir)/adaptor-framework/bitmap-saver.h \
- $(adaptor_devel_api_dir)/adaptor-framework/clipboard-event-notifier.h \
- $(adaptor_devel_api_dir)/adaptor-framework/clipboard.h \
- $(adaptor_devel_api_dir)/adaptor-framework/color-controller.h \
- $(adaptor_devel_api_dir)/adaptor-framework/drag-and-drop-detector.h \
- $(adaptor_devel_api_dir)/adaptor-framework/environment-variable.h \
- $(adaptor_devel_api_dir)/adaptor-framework/event-feeder.h \
- $(adaptor_devel_api_dir)/adaptor-framework/event-thread-callback.h \
- $(adaptor_devel_api_dir)/adaptor-framework/feedback-plugin.h \
- $(adaptor_devel_api_dir)/adaptor-framework/feedback-player.h \
- $(adaptor_devel_api_dir)/adaptor-framework/file-loader.h \
- $(adaptor_devel_api_dir)/adaptor-framework/image-loading.h \
- $(adaptor_devel_api_dir)/adaptor-framework/gif-loading.h \
- $(adaptor_devel_api_dir)/adaptor-framework/imf-manager.h \
- $(adaptor_devel_api_dir)/adaptor-framework/input-method-devel.h \
- $(adaptor_devel_api_dir)/adaptor-framework/input-method-options.h \
- $(adaptor_devel_api_dir)/adaptor-framework/lifecycle-controller.h \
- $(adaptor_devel_api_dir)/adaptor-framework/orientation.h \
- $(adaptor_devel_api_dir)/adaptor-framework/performance-logger.h \
- $(adaptor_devel_api_dir)/adaptor-framework/pixel-buffer.h \
- $(adaptor_devel_api_dir)/adaptor-framework/render-surface.h \
- $(adaptor_devel_api_dir)/adaptor-framework/singleton-service.h \
- $(adaptor_devel_api_dir)/adaptor-framework/sound-player.h \
- $(adaptor_devel_api_dir)/adaptor-framework/style-monitor.h \
- $(adaptor_devel_api_dir)/adaptor-framework/tilt-sensor.h \
- $(adaptor_devel_api_dir)/adaptor-framework/video-player.h \
- $(adaptor_devel_api_dir)/adaptor-framework/video-player-plugin.h \
- $(adaptor_devel_api_dir)/adaptor-framework/key-devel.h \
- $(adaptor_devel_api_dir)/adaptor-framework/key-extension-plugin.h \
- $(adaptor_devel_api_dir)/adaptor-framework/virtual-keyboard.h \
- $(adaptor_devel_api_dir)/adaptor-framework/physical-keyboard.h
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-indicator-impl.h"
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Evas.h>
-#ifdef WAYLAND
-#include <Ecore_Wayland.h>
-#else
-#include <Ecore_X.h>
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <iomanip>
-#include <fstream>
-
-#include <dali/public-api/images/native-image.h>
-#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/common/stage.h>
-#include <dali/public-api/images/buffer-image.h>
-#include <dali/public-api/images/pixel.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-#include <accessibility-adaptor-impl.h>
-#include <native-image-source.h>
-
-using Dali::Vector4;
-
-#if defined(DEBUG_ENABLED)
-#define STATE_DEBUG_STRING(state) (state==DISCONNECTED?"DISCONNECTED":state==CONNECTED?"CONNECTED":"UNKNOWN")
-#endif
-
-namespace
-{
-
-const float SLIDING_ANIMATION_DURATION( 0.2f ); // 200 milli seconds
-const float AUTO_INDICATOR_STAY_DURATION(3.0f); // 3 seconds
-const float SHOWING_DISTANCE_HEIGHT_RATE(0.34f); // 20 pixels
-
-enum
-{
- KEEP_SHOWING = -1,
- HIDE_NOW = 0
-};
-
-const int NUM_GRADIENT_INTERVALS(5); // Number of gradient intervals
-const float GRADIENT_ALPHA[NUM_GRADIENT_INTERVALS+1] = { 0.6f, 0.38f, 0.20f, 0.08f, 0.0f, 0.0f };
-
-#define MAKE_SHADER(A)#A
-
-const char* BACKGROUND_VERTEX_SHADER = MAKE_SHADER(
- attribute mediump vec2 aPosition;
- attribute mediump float aAlpha;
- varying mediump float vAlpha;
- uniform mediump mat4 uMvpMatrix;
- uniform mediump vec3 uSize;
-
- void main()
- {
- mediump vec4 vertexPosition = vec4( aPosition * uSize.xy, 0.0, 1.0 );
- vertexPosition = uMvpMatrix * vertexPosition;
-
- vAlpha = aAlpha;
- gl_Position = vertexPosition;
- }
-);
-
-const char* BACKGROUND_FRAGMENT_SHADER = MAKE_SHADER(
- uniform lowp vec4 uColor;
- varying mediump float vAlpha;
-
- void main()
- {
- gl_FragColor = uColor;
- gl_FragColor.a *= vAlpha;
- }
-);
-
-const char* FOREGROUND_VERTEX_SHADER = DALI_COMPOSE_SHADER(
- attribute mediump vec2 aPosition;\n
- varying mediump vec2 vTexCoord;\n
- uniform mediump mat4 uMvpMatrix;\n
- uniform mediump vec3 uSize;\n
- uniform mediump vec4 sTextureRect;\n
- \n
- void main()\n
- {\n
- gl_Position = uMvpMatrix * vec4(aPosition * uSize.xy, 0.0, 1.0);\n
- vTexCoord = aPosition + vec2(0.5);\n
- }\n
-);
-
-const char* FOREGROUND_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
- varying mediump vec2 vTexCoord;\n
- uniform sampler2D sTexture;\n
- \n
- void main()\n
- {\n
- gl_FragColor = texture2D( sTexture, vTexCoord );\n // the foreground does not apply actor color
- }\n
-);
-
-Dali::Geometry CreateQuadGeometry()
-{
- Dali::Property::Map quadVertexFormat;
- quadVertexFormat["aPosition"] = Dali::Property::VECTOR2;
- Dali::PropertyBuffer vertexData = Dali::PropertyBuffer::New( quadVertexFormat );
-
- const float halfQuadSize = .5f;
- struct QuadVertex { Dali::Vector2 position; };
- QuadVertex quadVertexData[4] = {
- { Dali::Vector2(-halfQuadSize, -halfQuadSize) },
- { Dali::Vector2(-halfQuadSize, halfQuadSize) },
- { Dali::Vector2( halfQuadSize, -halfQuadSize) },
- { Dali::Vector2( halfQuadSize, halfQuadSize) } };
- vertexData.SetData(quadVertexData, 4);
-
- Dali::Geometry quad = Dali::Geometry::New();
- quad.AddVertexBuffer( vertexData );
- quad.SetType( Dali::Geometry::TRIANGLE_STRIP );
- return quad;
-}
-
-const float OPAQUE_THRESHOLD(0.99f);
-const float TRANSPARENT_THRESHOLD(0.05f);
-
-// indicator service name
-const char* INDICATOR_SERVICE_NAME("elm_indicator");
-
-// Copied from ecore_evas_extn_engine.h
-
-#define NBUF 2
-
-enum // opcodes
-{
- OP_RESIZE,
- OP_SHOW,
- OP_HIDE,
- OP_FOCUS,
- OP_UNFOCUS,
- OP_UPDATE,
- OP_UPDATE_DONE,
- OP_SHM_REF0,
- OP_SHM_REF1,
- OP_SHM_REF2,
- OP_PROFILE_CHANGE_REQUEST,
- OP_PROFILE_CHANGE_DONE,
- OP_EV_MOUSE_IN,
- OP_EV_MOUSE_OUT,
- OP_EV_MOUSE_UP,
- OP_EV_MOUSE_DOWN,
- OP_EV_MOUSE_MOVE,
- OP_EV_MOUSE_WHEEL,
- OP_EV_MULTI_UP,
- OP_EV_MULTI_DOWN,
- OP_EV_MULTI_MOVE,
- OP_EV_KEY_UP,
- OP_EV_KEY_DOWN,
- OP_EV_HOLD,
- OP_MSG_PARENT,
- OP_MSG,
- OP_PIXMAP_REF,
-};
-
-// Copied from elm_conform.c
-
-const int MSG_DOMAIN_CONTROL_INDICATOR( 0x10001 );
-const int MSG_ID_INDICATOR_REPEAT_EVENT( 0x10002 );
-const int MSG_ID_INDICATOR_ROTATION( 0x10003 );
-const int MSG_ID_INDICATOR_OPACITY( 0X1004 );
-const int MSG_ID_INDICATOR_TYPE( 0X1005 );
-const int MSG_ID_INDICATOR_START_ANIMATION( 0X10006 );
-
-struct IpcDataUpdate
-{
- int x, w, y, h;
-};
-
-struct IpcDataResize
-{
- int w, h;
-};
-
-struct IpcIndicatorDataAnimation
-{
- unsigned int xwin;
- double duration;
-};
-
-struct IpcDataEvMouseUp
-{
- int b;
- Evas_Button_Flags flags;
- int mask;
- unsigned int timestamp;
- Evas_Event_Flags event_flags;
-
- IpcDataEvMouseUp(unsigned long timestamp)
- : b(1),
- flags(EVAS_BUTTON_NONE),
- mask(0),
- timestamp(static_cast<unsigned int>(timestamp)),
- event_flags(EVAS_EVENT_FLAG_NONE)
- {
- }
-};
-
-struct IpcDataEvMouseDown
-{
- int b;
- Evas_Button_Flags flags;
- int mask;
- unsigned int timestamp;
- Evas_Event_Flags event_flags;
-
- IpcDataEvMouseDown(unsigned long timestamp)
- : b(1),
- flags(EVAS_BUTTON_NONE),
- mask(0),
- timestamp(static_cast<unsigned int>(timestamp)),
- event_flags(EVAS_EVENT_FLAG_NONE)
- {
- }
-};
-
-struct IpcDataEvMouseMove
-{
- int x, y;
- Evas_Button_Flags flags;
- int mask;
- unsigned int timestamp;
- Evas_Event_Flags event_flags;
-
- IpcDataEvMouseMove(const Dali::Vector2& touchPoint, unsigned long timestamp)
- : x(static_cast<Evas_Coord>(touchPoint.x)),
- y(static_cast<Evas_Coord>(touchPoint.y)),
- flags(EVAS_BUTTON_NONE),
- mask(0),
- timestamp(static_cast<unsigned int>(timestamp)),
- event_flags(EVAS_EVENT_FLAG_NONE)
- {
- }
-};
-
-struct IpcDataEvMouseOut
-{
- unsigned int timestamp;
- int mask;
- Evas_Event_Flags event_flags;
-
- IpcDataEvMouseOut(unsigned long timestamp)
- : timestamp(static_cast<unsigned int>(timestamp)),
- mask(0),
- event_flags(EVAS_EVENT_FLAG_NONE)
- {
- }
-};
-
-#ifdef ENABLE_INDICATOR_IMAGE_SAVING
-
-void SaveIndicatorImage( Dali::NativeImageSourcePtr nativeImageSource )
-{
- // Save image data to disk in BMP form.
- static int gFilenameCounter = 0;
- static const char bmpHeader[] = {
- 0x42, 0x4d, 0x0a, 0xcb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x7c, 0x00,
- 0x00, 0x00,
- 0xe0, 0x01, 0x00, 0x00, // Width (480)
- 0x1b, 0x00, 0x00, 0x00, // Height ( 27)
- 0x01, 0x00, 0x20, 0x00, 0x03, 0x00,
- 0x00, 0x00, 0x80, 0xca, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
- 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x42, 0x47, 0x52, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
- };
-
- // This is a BMP header with width & height hard-coded in.
- // The data was first determined by dumping the raw data and inspecting in GIMP, before creating this header data.
- std::vector<unsigned char> buffer;
- unsigned int w = 0;
- unsigned int h = 0;
- Dali::Pixel::Format pixelFormat;
- if( nativeImageSource->GetPixels( buffer, w, h, pixelFormat ) )
- {
- int imageSize = w * h * 4;
- std::stringstream fileName;
- // Give each file an incremental filename.
- fileName << "/opt/usr/media/Images/out-" << std::setfill( '0' ) << std::setw( 5 ) << gFilenameCounter << ".bmp";
-
- std::ofstream outfile( fileName.str().c_str(), std::ofstream::binary );
- if( outfile.is_open() )
- {
- DALI_LOG_WARNING( "Saving Indicator Image w:%d, h:%d, %s\n", w, h, fileName.str().c_str() );
-
- outfile.write( bmpHeader, sizeof( bmpHeader ) / sizeof( bmpHeader[0] ) ); // Size of the BMP header.
- outfile.write( (const char*)buffer.data(), imageSize );
- outfile.close();
- gFilenameCounter++;
- }
- else
- {
- DALI_LOG_ERROR( "COULD NOT OPEN FOR SAVING: %s\n", fileName.str().c_str() );
- }
- }
-}
-
-#endif
-
-} // anonymous namespace
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gIndicatorLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_INDICATOR");
-#endif
-
-// Impl to hide EFL implementation.
-
-struct Indicator::Impl
-{
- enum // operation mode
- {
- INDICATOR_HIDE,
- INDICATOR_STAY_WITH_DURATION
- };
-
- /**
- * Constructor
- */
- Impl(Indicator* indicator)
- : mIndicator(indicator),
- mEcoreEventHandler(NULL)
- {
-#if defined(DALI_PROFILE_MOBILE)
-#if defined(WAYLAND)
- mEcoreEventHandler = ecore_event_handler_add(ECORE_WL_EVENT_INDICATOR_FLICK, EcoreEventIndicator, this);
-#else
- mEcoreEventHandler = ecore_event_handler_add(ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, this);
-#endif
-#endif // WAYLAND && DALI_PROFILE_MOBILE
- }
-
- /**
- * Destructor
- */
- ~Impl()
- {
- if ( mEcoreEventHandler )
- {
- ecore_event_handler_del(mEcoreEventHandler);
- }
- }
-
- static void SetIndicatorVisibility( void* data, int operation )
- {
- Indicator::Impl* indicatorImpl((Indicator::Impl*)data);
-
- if ( indicatorImpl == NULL || indicatorImpl->mIndicator == NULL)
- {
- return;
- }
- if ( operation == INDICATOR_STAY_WITH_DURATION )
- {
- // if indicator is not showing, INDICATOR_FLICK_DONE is given
- if( indicatorImpl->mIndicator->mVisible == Dali::Window::AUTO &&
- !indicatorImpl->mIndicator->mIsShowing )
- {
- indicatorImpl->mIndicator->ShowIndicator( AUTO_INDICATOR_STAY_DURATION );
- }
- }
- else if( operation == INDICATOR_HIDE )
- {
- if( indicatorImpl->mIndicator->mVisible == Dali::Window::AUTO &&
- indicatorImpl->mIndicator->mIsShowing )
- {
- indicatorImpl->mIndicator->ShowIndicator( HIDE_NOW );
- }
- }
- }
-#if defined(DALI_PROFILE_MOBILE)
-#if defined(WAYLAND)
- /**
- * Called when the Ecore indicator event is received.
- */
- static Eina_Bool EcoreEventIndicator( void* data, int type, void* event )
- {
- SetIndicatorVisibility( data, INDICATOR_STAY_WITH_DURATION );
- return ECORE_CALLBACK_PASS_ON;
- }
-#else
- /**
- * Called when the client messages (i.e. quick panel state) are received.
- */
- static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
- {
- Ecore_X_Event_Client_Message* clientMessageEvent((Ecore_X_Event_Client_Message*)event);
-
- if ( clientMessageEvent != NULL )
- {
- if (clientMessageEvent->message_type == ECORE_X_ATOM_E_INDICATOR_FLICK_DONE)
- {
- SetIndicatorVisibility( data, INDICATOR_STAY_WITH_DURATION );
- }
- else if ( clientMessageEvent->message_type == ECORE_X_ATOM_E_MOVE_QUICKPANEL_STATE )
- {
- SetIndicatorVisibility( data, INDICATOR_HIDE );
- }
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-#endif
-#endif // WAYLAND && DALI_PROFILE_MOBILE
-
- // Data
- Indicator* mIndicator;
- Ecore_Event_Handler* mEcoreEventHandler;
-};
-
-Indicator::LockFile::LockFile(const std::string filename)
-: mFilename(filename),
- mErrorThrown(false)
-{
- mFileDescriptor = open(filename.c_str(), O_RDWR);
- if( mFileDescriptor == -1 )
- {
- mFileDescriptor = 0;
- mErrorThrown = true;
- DALI_LOG_ERROR( "### Cannot open %s for indicator lock ###\n", mFilename.c_str() );
- }
-}
-
-Indicator::LockFile::~LockFile()
-{
- // Closing file descriptor also unlocks file.
- if( mFileDescriptor > 0 )
- {
- close( mFileDescriptor );
- }
-}
-
-bool Indicator::LockFile::Lock()
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- bool locked = false;
- if( mFileDescriptor > 0 )
- {
- struct flock filelock;
-
- filelock.l_type = F_RDLCK;
- filelock.l_whence = SEEK_SET;
- filelock.l_start = 0;
- filelock.l_len = 0;
- if( fcntl( mFileDescriptor, F_SETLKW, &filelock ) == -1 )
- {
- mErrorThrown = true;
- DALI_LOG_ERROR( "### Failed to lock with fd : %s ###\n", mFilename.c_str() );
- }
- else
- {
- locked = true;
- }
- }
- else
- {
- mErrorThrown = true;
- DALI_LOG_ERROR( "### Invalid fd ###\n" );
- }
-
- return locked;
-}
-
-void Indicator::LockFile::Unlock()
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- if( mFileDescriptor > 0 )
- {
- struct flock filelock;
-
- filelock.l_type = F_UNLCK;
- filelock.l_whence = SEEK_SET;
- filelock.l_start = 0;
- filelock.l_len = 0;
- if (fcntl(mFileDescriptor, F_SETLKW, &filelock) == -1)
- {
- mErrorThrown = true;
- DALI_LOG_ERROR( "### Failed to lock with fd : %s ###\n", mFilename.c_str() );
- }
- }
-}
-
-bool Indicator::LockFile::RetrieveAndClearErrorStatus()
-{
- bool error = mErrorThrown;
- mErrorThrown = false;
- return error;
-}
-
-Indicator::ScopedLock::ScopedLock(LockFile* lockFile)
-: mLockFile(lockFile),
- mLocked(false)
-{
- if(mLockFile)
- {
- mLocked = mLockFile->Lock();
- }
-}
-
-Indicator::ScopedLock::~ScopedLock()
-{
- if( mLockFile )
- {
- mLockFile->Unlock();
- }
-}
-
-bool Indicator::ScopedLock::IsLocked()
-{
- return mLocked;
-}
-
-Indicator::Indicator( Adaptor* adaptor, Dali::Window::WindowOrientation orientation, IndicatorInterface::Observer* observer )
-: mPixmap( 0 ),
- mGestureDeltaY( 0.0f ),
- mGestureDetected( false ),
- mConnection( this ),
- mOpacityMode( Dali::Window::OPAQUE ),
- mState( DISCONNECTED ),
- mAdaptor(adaptor),
- mServerConnection( NULL ),
- mObserver( observer ),
- mOrientation( orientation ),
- mImageWidth( 0 ),
- mImageHeight( 0 ),
- mVisible( Dali::Window::INVISIBLE ),
- mIsShowing( true ),
- mIsAnimationPlaying( false ),
- mCurrentSharedFile( 0 ),
- mSharedBufferType( BUFFER_TYPE_SHM ),
- mImpl( NULL ),
- mBackgroundVisible( false ),
- mTopMargin( 0 )
-{
- mIndicatorContentActor = Dali::Actor::New();
- mIndicatorContentActor.SetParentOrigin( ParentOrigin::TOP_CENTER );
- mIndicatorContentActor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
-
- // Indicator image handles the touch event including "leave"
- mIndicatorContentActor.SetLeaveRequired( true );
- mIndicatorContentActor.TouchSignal().Connect( this, &Indicator::OnTouch );
- mIndicatorContentActor.SetColor( Color::BLACK );
-
- mIndicatorActor = Dali::Actor::New();
- mIndicatorActor.Add( mIndicatorContentActor );
-
- // Event handler to find out flick down gesture
- mEventActor = Dali::Actor::New();
- mEventActor.SetParentOrigin( ParentOrigin::TOP_CENTER );
- mEventActor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- mIndicatorActor.Add( mEventActor );
-
- // Attach pan gesture to find flick down during hiding.
- // It can prevent the problem that scrollview gets pan gesture even indicator area is touched,
- // since it consumes the pan gesture in advance.
- mPanDetector = Dali::PanGestureDetector::New();
- mPanDetector.DetectedSignal().Connect( this, &Indicator::OnPan );
- mPanDetector.Attach( mEventActor );
-
- Open( orientation );
-
- // register indicator to accessibility adaptor
- Dali::AccessibilityAdaptor accessibilityAdaptor = AccessibilityAdaptor::Get();
- if(accessibilityAdaptor)
- {
- AccessibilityAdaptor::GetImplementation( accessibilityAdaptor ).SetIndicator( this );
- }
- // hide the indicator by default
- mIndicatorActor.SetVisible( false );
-
- // create impl to handle ecore event
- mImpl = new Impl(this);
-}
-
-Indicator::~Indicator()
-{
- if(mImpl)
- {
- delete mImpl;
- mImpl = NULL;
- }
-
- if(mEventActor)
- {
- mEventActor.TouchSignal().Disconnect( this, &Indicator::OnTouch );
- }
- Disconnect();
-}
-
-void Indicator::SetAdaptor(Adaptor* adaptor)
-{
- mAdaptor = adaptor;
- mIndicatorBuffer->SetAdaptor( adaptor );
-}
-
-Dali::Actor Indicator::GetActor()
-{
- return mIndicatorActor;
-}
-
-void Indicator::Open( Dali::Window::WindowOrientation orientation )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // Calls from Window should be set up to ensure we are in a
- // disconnected state before opening a second time.
- DALI_ASSERT_DEBUG( mState == DISCONNECTED );
-
- mOrientation = orientation;
-
- Connect();
-
- // Change background visibility depending on orientation
- if( mOrientation == Dali::Window::LANDSCAPE || mOrientation == Dali::Window::LANDSCAPE_INVERSE )
- {
- if( mBackgroundRenderer )
- {
- mIndicatorContentActor.RemoveRenderer( mBackgroundRenderer );
- mBackgroundVisible = false;
- }
- }
- else
- {
- SetOpacityMode( mOpacityMode );
- }
-}
-
-void Indicator::Close()
-{
- DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "State: %s", STATE_DEBUG_STRING(mState) );
-
- if( mState == CONNECTED )
- {
- Disconnect();
- if( mObserver != NULL )
- {
- mObserver->IndicatorClosed( this );
- }
- }
-
- Dali::Texture emptyTexture;
- SetForegroundImage( emptyTexture );
-}
-
-void Indicator::SetOpacityMode( Dali::Window::IndicatorBgOpacity mode )
-{
- mOpacityMode = mode;
-
- Dali::Geometry geometry = CreateBackgroundGeometry();
- if( geometry )
- {
- if( mBackgroundRenderer )
- {
- if( mBackgroundRenderer.GetGeometry() != geometry )
- {
- mBackgroundRenderer.SetGeometry( geometry );
- }
- }
- else
- {
- if( !mBackgroundShader )
- {
- mBackgroundShader = Dali::Shader::New( BACKGROUND_VERTEX_SHADER, BACKGROUND_FRAGMENT_SHADER, Dali::Shader::Hint::OUTPUT_IS_TRANSPARENT );
- }
-
- mBackgroundRenderer = Dali::Renderer::New( geometry, mBackgroundShader );
- }
-
- if( !mBackgroundVisible )
- {
- mIndicatorContentActor.AddRenderer( mBackgroundRenderer );
- mBackgroundVisible = true;
- }
- }
- else if( mBackgroundRenderer )
- {
- mIndicatorContentActor.RemoveRenderer( mBackgroundRenderer );
- mBackgroundVisible = false;
- }
- UpdateTopMargin();
-}
-
-void Indicator::SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate )
-{
- if ( visibleMode != mVisible || forceUpdate )
- {
- // If we were previously hidden, then we should update the image data before we display the indicator
- if ( mVisible == Dali::Window::INVISIBLE )
- {
- UpdateImageData( mCurrentSharedFile );
- }
-
- if ( visibleMode == Dali::Window::INVISIBLE )
- {
- if (mServerConnection)
- {
- mServerConnection->SendEvent( OP_HIDE, NULL, 0 );
- }
- }
- else
- {
- mIndicatorActor.SetVisible( true );
-
- if( mServerConnection )
- {
- mServerConnection->SendEvent( OP_SHOW, NULL, 0 );
- }
- }
-
- mVisible = visibleMode;
- UpdateTopMargin();
-
- if( mForegroundRenderer && mForegroundRenderer.GetTextures().GetTexture( 0u ) )
- {
- if( CheckVisibleState() && mVisible == Dali::Window::AUTO )
- {
- // hide indicator
- ShowIndicator( AUTO_INDICATOR_STAY_DURATION /* stay n sec */ );
- }
- else if( CheckVisibleState() && mVisible == Dali::Window::VISIBLE )
- {
- // show indicator
- ShowIndicator( KEEP_SHOWING );
- }
- else
- {
- // hide indicator
- ShowIndicator( HIDE_NOW );
- }
- }
- else
- {
- mIsShowing = false;
- }
- }
-}
-
-bool Indicator::IsConnected()
-{
- return ( mState == CONNECTED );
-}
-
-bool Indicator::SendMessage( int messageDomain, int messageId, const void *data, int size )
-{
- if(IsConnected())
- {
- return mServerConnection->SendEvent( OP_MSG, messageDomain, messageId, data, size );
- }
- else
- {
- return false;
- }
-}
-
-bool Indicator::OnTouch(Dali::Actor indicator, const Dali::TouchData& touchData)
-{
- if( mServerConnection )
- {
- // Send touch event to indicator server when indicator is showing
- if( CheckVisibleState() || mIsShowing )
- {
- switch( touchData.GetState(0) )
- {
- case Dali::PointState::DOWN:
- {
- IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
- IpcDataEvMouseDown ipcDown( touchData.GetTime() );
- mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
- mServerConnection->SendEvent( OP_EV_MOUSE_DOWN, &ipcDown, sizeof(ipcDown) );
-
- if( mVisible == Dali::Window::AUTO )
- {
- // Stop hiding indicator
- ShowIndicator( KEEP_SHOWING );
- }
- }
- break;
-
- case Dali::PointState::MOTION:
- {
- IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
- mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
- }
- break;
-
- case Dali::PointState::UP:
- case Dali::PointState::INTERRUPTED:
- {
- IpcDataEvMouseUp ipcUp( touchData.GetTime() );
- mServerConnection->SendEvent( OP_EV_MOUSE_UP, &ipcUp, sizeof(ipcUp) );
-
- if( mVisible == Dali::Window::AUTO )
- {
- // Hide indicator
- ShowIndicator( 0.5f /* hide after 0.5 sec */ );
- }
- }
- break;
-
- case Dali::TouchPoint::Leave:
- {
- IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
- mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
- IpcDataEvMouseUp ipcOut( touchData.GetTime() );
- mServerConnection->SendEvent( OP_EV_MOUSE_OUT, &ipcOut, sizeof(ipcOut) );
- }
- break;
-
- default:
- break;
- }
-
- return true;
- }
- }
-
- return false;
-}
-
-bool Indicator::Connect()
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- DALI_ASSERT_DEBUG( mState == DISCONNECTED );
-
- bool connected = false;
-
- mServerConnection = new ServerConnection( INDICATOR_SERVICE_NAME, 0, false, this );
- if( mServerConnection )
- {
- connected = mServerConnection->IsConnected();
- if( ! connected )
- {
- delete mServerConnection;
- mServerConnection = NULL;
- }
- }
-
- if( !connected )
- {
- StartReconnectionTimer();
- }
- else
- {
- mState = CONNECTED;
- }
-
- return connected;
-}
-
-void Indicator::StartReconnectionTimer()
-{
- if( ! mReconnectTimer )
- {
- mReconnectTimer = Dali::Timer::New(1000);
- mConnection.DisconnectAll();
- mReconnectTimer.TickSignal().Connect( mConnection, &Indicator::OnReconnectTimer );
- }
- mReconnectTimer.Start();
-}
-
-bool Indicator::OnReconnectTimer()
-{
- bool retry = false;
-
- if( mState == DISCONNECTED )
- {
- if( !Connect() )
- {
- retry = true;
- }
- }
-
- return retry;
-}
-
-void Indicator::Disconnect()
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- mState = DISCONNECTED;
-
- delete mServerConnection;
- mServerConnection = NULL;
-
- ClearSharedFileInfo();
-}
-
-void Indicator::Resize( int width, int height )
-{
- if( width < 1 )
- {
- width = 1;
- }
- if( height < 1 )
- {
- height = 1;
- }
-
- if( mImageWidth != width || mImageHeight != height )
- {
- mImageWidth = width;
- mImageHeight = height;
-
- mIndicatorContentActor.SetSize( mImageWidth, mImageHeight );
- mIndicatorActor.SetSize( mImageWidth, mImageHeight );
- mEventActor.SetSize(mImageWidth, mImageHeight);
- UpdateTopMargin();
- }
-}
-
-void Indicator::SetLockFileInfo( Ecore_Ipc_Event_Server_Data *epcEvent )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // epcEvent->ref == w
- // epcEvent->ref_to == h
- // epcEvent->response == buffer num
- // epcEvent->data = lockfile + nul byte
-
- if( (epcEvent->ref > 0) && (epcEvent->ref_to > 0) && (epcEvent->data) &&
- (((unsigned char *)epcEvent->data)[epcEvent->size - 1] == 0) )
- {
- int n = epcEvent->response;
-
- if( n >= 0 && n < SHARED_FILE_NUMBER )
- {
- mCurrentSharedFile = n;
-
- mSharedFileInfo[n].mImageWidth = epcEvent->ref;
- mSharedFileInfo[n].mImageHeight = epcEvent->ref_to;
-
- mSharedFileInfo[n].mLockFileName.clear();
-
- mSharedFileInfo[n].mLockFileName = static_cast< char* >( epcEvent->data );
-
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "SetLockFileInfo: buffer num = %d, w = %d, h = %d, lock = %s\n",
- n, mSharedFileInfo[n].mImageWidth, mSharedFileInfo[n].mImageHeight, mSharedFileInfo[n].mLockFileName.c_str() );
- }
- }
-}
-
-void Indicator::SetSharedImageInfo( Ecore_Ipc_Event_Server_Data *epcEvent )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // epcEvent->ref == shm id
- // epcEvent->ref_to == shm num
- // epcEvent->response == buffer num
- // epcEvent->data = shm ref string + nul byte
-
- if ( (epcEvent->data) &&
- (epcEvent->size > 0) &&
- (((unsigned char *)epcEvent->data)[epcEvent->size - 1] == 0) )
- {
- int n = epcEvent->response;
-
- if( n >= 0 && n < SHARED_FILE_NUMBER )
- {
- mCurrentSharedFile = n;
-
- mSharedFileInfo[n].mSharedFileName.clear();
-
- mSharedFileInfo[n].mSharedFileName = static_cast< char* >( epcEvent->data );
-
- mSharedFileInfo[n].mSharedFileID = epcEvent->ref;
- mSharedFileInfo[n].mSharedFileNumber = epcEvent->ref_to;
-
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "SetSharedImageInfo: buffer num %d, shared file = %s, id = %d, num = %d\n",
- n, mSharedFileInfo[n].mSharedFileName.c_str(), mSharedFileInfo[n].mSharedFileID, mSharedFileInfo[n].mSharedFileNumber );
- }
- }
-}
-
-void Indicator::LoadSharedImage( Ecore_Ipc_Event_Server_Data *epcEvent )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // epcEvent->ref == alpha
- // epcEvent->ref_to == sys
- // epcEvent->response == buffer num
-
- if ( mSharedBufferType != BUFFER_TYPE_SHM )
- {
- return ;
- }
-
- int n = epcEvent->response;
-
- if( n >= 0 && n < SHARED_FILE_NUMBER )
- {
- mCurrentSharedFile = n;
-
- delete mSharedFileInfo[n].mSharedFile;
- mSharedFileInfo[n].mSharedFile = NULL;
-
- delete mSharedFileInfo[n].mLock;
- mSharedFileInfo[n].mLock = NULL;
-
- std::stringstream sharedFileID;
- std::stringstream sharedFileNumber;
-
- sharedFileID << mSharedFileInfo[n].mSharedFileID;
- sharedFileNumber << mSharedFileInfo[n].mSharedFileNumber;
-
- std::string sharedFilename = "/" + mSharedFileInfo[n].mSharedFileName + "-" + sharedFileID.str() + "." + sharedFileNumber.str();
-
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "LoadSharedImage: file name = %s\n", sharedFilename.c_str() );
-
- mSharedFileInfo[n].mSharedFile = SharedFile::New( sharedFilename.c_str(), mSharedFileInfo[n].mImageWidth * mSharedFileInfo[n].mImageWidth * 4, true );
- if( mSharedFileInfo[n].mSharedFile != NULL )
- {
- mSharedFileInfo[n].mLock = new Indicator::LockFile( mSharedFileInfo[n].mLockFileName );
- if( mSharedFileInfo[n].mLock->RetrieveAndClearErrorStatus() )
- {
- DALI_LOG_ERROR( "### Indicator error: Cannot open lock file %s ###\n", mSharedFileInfo[n].mLockFileName.c_str() );
- }
- else
- {
- CreateNewImage( n );
- UpdateVisibility();
- }
- }
- }
-}
-
-void Indicator::LoadPixmapImage( Ecore_Ipc_Event_Server_Data *epcEvent )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // epcEvent->ref == pixmap id
- // epcEvent->ref_to == type
- // epcEvent->response == buffer num
-
- if( (epcEvent->ref > 0) && (epcEvent->ref_to > 0) )
- {
- mSharedBufferType = (BufferType)(epcEvent->ref_to);
-
- ClearSharedFileInfo();
-
- mPixmap = static_cast<PixmapId>(epcEvent->ref);
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "mPixmap [%x]", mPixmap);
-
- CreateNewPixmapImage();
- UpdateVisibility();
- }
-}
-
-void Indicator::UpdateTopMargin()
-{
- int newMargin = (mVisible == Dali::Window::VISIBLE && mOpacityMode == Dali::Window::OPAQUE) ? mImageHeight : 0;
- if (mTopMargin != newMargin)
- {
- mTopMargin = newMargin;
- mAdaptor->IndicatorSizeChanged( mTopMargin );
- }
-}
-
-void Indicator::UpdateVisibility()
-{
- if( CheckVisibleState() )
- {
- // set default indicator type (enable the quick panel)
- OnIndicatorTypeChanged( INDICATOR_TYPE_1 );
- }
- else
- {
- // set default indicator type (disable the quick panel)
- OnIndicatorTypeChanged( INDICATOR_TYPE_2 );
- }
-
- if( !mIsShowing )
- {
- mIndicatorContentActor.SetPosition( 0.0f, -mImageHeight, 0.0f );
- }
-
- SetVisible(mVisible, true);
-}
-
-void Indicator::UpdateImageData( int bufferNumber )
-{
- DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "State: %s mVisible: %s", STATE_DEBUG_STRING(mState), mVisible?"T":"F" );
-
- if( mState == CONNECTED && mVisible )
- {
- if(mPixmap == 0)
- {
- // in case of shm indicator (not pixmap), not sure we can skip it when mIsShowing is false
- CopyToBuffer( bufferNumber );
- }
- else
- {
- if(mIsShowing)
- {
- mAdaptor->RequestUpdateOnce();
- }
- }
- }
-}
-
-bool Indicator::CopyToBuffer( int bufferNumber )
-{
- bool success = false;
-
- if( mSharedFileInfo[bufferNumber].mLock )
- {
- Indicator::ScopedLock scopedLock(mSharedFileInfo[bufferNumber].mLock);
- if( mSharedFileInfo[bufferNumber].mLock->RetrieveAndClearErrorStatus() )
- {
- // Do nothing here.
- }
- else if( scopedLock.IsLocked() )
- {
- unsigned char *src = mSharedFileInfo[bufferNumber].mSharedFile->GetAddress();
- size_t size = static_cast< size_t >( mSharedFileInfo[bufferNumber].mImageWidth ) * mSharedFileInfo[bufferNumber].mImageHeight * 4;
-
- if( mIndicatorBuffer->UpdatePixels( src, size ) )
- {
- mAdaptor->RequestUpdateOnce();
- success = true;
- }
- }
- }
-
- return success;
-}
-
-void Indicator::CreateNewPixmapImage()
-{
- DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "W:%d H:%d", mImageWidth, mImageHeight );
- Dali::NativeImageSourcePtr nativeImageSource = Dali::NativeImageSource::New( mPixmap );
-
-#ifdef ENABLE_INDICATOR_IMAGE_SAVING
- SaveIndicatorImage( nativeImageSource );
-#endif
-
- if( nativeImageSource )
- {
- Dali::Texture texture = Dali::Texture::New( *nativeImageSource );
- SetForegroundImage( texture );
- mIndicatorContentActor.SetSize( mImageWidth, mImageHeight );
- mIndicatorActor.SetSize( mImageWidth, mImageHeight );
- mEventActor.SetSize( mImageWidth, mImageHeight );
- UpdateTopMargin();
- }
- else
- {
- DALI_LOG_WARNING("### Cannot create indicator image - disconnecting ###\n");
- Disconnect();
- if( mObserver != NULL )
- {
- mObserver->IndicatorClosed( this );
- }
- // Don't do connection in this callback - strange things happen!
- StartReconnectionTimer();
- }
-}
-
-void Indicator::CreateNewImage( int bufferNumber )
-{
- DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "W:%d H:%d", mSharedFileInfo[bufferNumber].mImageWidth, mSharedFileInfo[bufferNumber].mImageHeight );
- mIndicatorBuffer = new IndicatorBuffer( mAdaptor, mSharedFileInfo[bufferNumber].mImageWidth, mSharedFileInfo[bufferNumber].mImageHeight, Pixel::BGRA8888 );
- bool success = false;
-
- if( CopyToBuffer( bufferNumber ) ) // Only create images if we have valid image buffer
- {
- Dali::Texture texture = Dali::Texture::New( mIndicatorBuffer->GetNativeImage() );
- if( texture )
- {
- SetForegroundImage( texture );
- success = true;
- }
- }
-
- if( !success )
- {
- DALI_LOG_WARNING("### Cannot create indicator image ###\n");
- }
-}
-
-Dali::Geometry Indicator::CreateBackgroundGeometry()
-{
- switch( mOpacityMode )
- {
- case Dali::Window::TRANSLUCENT:
- if( !mTranslucentGeometry )
- {
- // Construct 5 interval mesh
- // 0 +---+ 1
- // | \ |
- // 2 +---+ 3
- // | \ |
- // 4 +---+ 5
- // | \ |
- // 6 +---+ 7
- // | \ |
- // 8 +---+ 9
- // | \ |
- // 10 +---+ 11
-
- // Create vertices
- struct BackgroundVertex
- {
- Vector2 mPosition;
- float mAlpha;
- };
-
- unsigned int numVertices = 2 * ( NUM_GRADIENT_INTERVALS + 1 );
- BackgroundVertex vertices[ numVertices ];
-
- float d = -0.5f;
- float delta = 1.0f / NUM_GRADIENT_INTERVALS;
- BackgroundVertex* currentVertex = vertices;
- for( int y = 0; y < NUM_GRADIENT_INTERVALS + 1; ++y, d += delta )
- {
- currentVertex->mPosition = Vector2( -0.5f, d );
- currentVertex->mAlpha = GRADIENT_ALPHA[ y ];
- currentVertex++;
-
- currentVertex->mPosition = Vector2( 0.5f, d );
- currentVertex->mAlpha = GRADIENT_ALPHA[ y ];
- currentVertex++;
- }
-
- // Create indices
- unsigned int numIndices = 2 * 3 * NUM_GRADIENT_INTERVALS;
- unsigned short indices[ numIndices ];
-
- unsigned short* currentIndex = indices;
- for( int y = 0; y < NUM_GRADIENT_INTERVALS; ++y )
- {
- *currentIndex++ = (2 * y);
- *currentIndex++ = (2 * y) + 3;
- *currentIndex++ = (2 * y) + 1;
-
- *currentIndex++ = (2 * y);
- *currentIndex++ = (2 * y) + 2;
- *currentIndex++ = (2 * y) + 3;
- }
-
- Dali::Property::Map vertexFormat;
- vertexFormat[ "aPosition" ] = Dali::Property::VECTOR2;
- vertexFormat[ "aAlpha" ] = Dali::Property::FLOAT;
- Dali::PropertyBuffer vertexPropertyBuffer = Dali::PropertyBuffer::New( vertexFormat );
- vertexPropertyBuffer.SetData( vertices, numVertices );
-
- // Create the geometry object
- mTranslucentGeometry = Dali::Geometry::New();
- mTranslucentGeometry.AddVertexBuffer( vertexPropertyBuffer );
- mTranslucentGeometry.SetIndexBuffer( &indices[0], numIndices );
- }
-
- return mTranslucentGeometry;
- case Dali::Window::OPAQUE:
-
- if( !mSolidGeometry )
- {
- // Create vertices
- struct BackgroundVertex
- {
- Vector2 mPosition;
- float mAlpha;
- };
-
- BackgroundVertex vertices[ 4 ] = { { Vector2( -0.5f, -0.5f ), 1.0f }, { Vector2( 0.5f, -0.5f ), 1.0f },
- { Vector2( -0.5f, 0.5f ), 1.0f }, { Vector2( 0.5f, 0.5f ), 1.0f } };
-
- // Create indices
- unsigned short indices[ 6 ] = { 0, 3, 1, 0, 2, 3 };
-
- Dali::Property::Map vertexFormat;
- vertexFormat[ "aPosition" ] = Dali::Property::VECTOR2;
- vertexFormat[ "aAlpha" ] = Dali::Property::FLOAT;
- Dali::PropertyBuffer vertexPropertyBuffer = Dali::PropertyBuffer::New( vertexFormat );
- vertexPropertyBuffer.SetData( vertices, 4 );
-
-
- // Create the geometry object
- mSolidGeometry = Dali::Geometry::New();
- mSolidGeometry.AddVertexBuffer( vertexPropertyBuffer );
- mSolidGeometry.SetIndexBuffer( &indices[0], 6 );
- }
-
- return mSolidGeometry;
- case Dali::Window::TRANSPARENT:
- break;
- }
-
- return Dali::Geometry();
-}
-
-void Indicator::SetForegroundImage( Dali::Texture texture )
-{
- if( !mForegroundRenderer && texture )
- {
- // Create Shader
- Dali::Shader shader = Dali::Shader::New( FOREGROUND_VERTEX_SHADER, FOREGROUND_FRAGMENT_SHADER );
-
- // Create renderer from geometry and material
- Dali::Geometry quad = CreateQuadGeometry();
- mForegroundRenderer = Dali::Renderer::New( quad, shader );
- // Make sure the foreground stays in front of the background
- mForegroundRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, 1.f );
-
- // Set blend function
- mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_SRC_RGB, Dali::BlendFactor::ONE );
- mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_DEST_RGB, Dali::BlendFactor::ONE_MINUS_SRC_ALPHA );
- mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_SRC_ALPHA, Dali::BlendFactor::ONE );
- mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_DEST_ALPHA, Dali::BlendFactor::ONE );
-
- // Create a texture-set and add to renderer
-
- Dali::TextureSet textureSet = Dali::TextureSet::New();
- textureSet.SetTexture( 0u, texture );
- mForegroundRenderer.SetTextures( textureSet );
-
- mIndicatorContentActor.AddRenderer( mForegroundRenderer );
- }
- else if( mForegroundRenderer )
- {
- Dali::TextureSet textureSet = mForegroundRenderer.GetTextures();
- textureSet.SetTexture( 0u, texture );
- }
-
- if( mImageWidth == 0 && mImageHeight == 0 && texture)
- {
- Resize( texture.GetWidth(), texture.GetHeight() );
- }
-}
-
-void Indicator::OnIndicatorTypeChanged( Type indicatorType )
-{
- if( mObserver != NULL )
- {
- mObserver->IndicatorTypeChanged( indicatorType );
- }
-}
-
-void Indicator::DataReceived( void* event )
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
- Ecore_Ipc_Event_Server_Data *epcEvent = static_cast<Ecore_Ipc_Event_Server_Data *>( event );
-
- switch( epcEvent->minor )
- {
- case OP_UPDATE:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_UPDATE\n" );
- if( mIsShowing )
- {
- mAdaptor->RequestUpdateOnce();
- }
- break;
- }
- case OP_UPDATE_DONE:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_UPDATE_DONE [%d]\n", epcEvent->response );
- // epcEvent->response == display buffer #
- UpdateImageData( epcEvent->response );
- break;
- }
- case OP_SHM_REF0:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF0\n" );
- SetSharedImageInfo( epcEvent );
- break;
- }
- case OP_SHM_REF1:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF1\n" );
- SetLockFileInfo( epcEvent );
- break;
- }
- case OP_SHM_REF2:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF2\n" );
- LoadSharedImage( epcEvent );
- break;
- }
- case OP_PIXMAP_REF:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_PIXMAP_REF\n" );
- LoadPixmapImage( epcEvent );
- break;
- }
- case OP_RESIZE:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_RESIZE\n" );
-
- if( (epcEvent->data) && (epcEvent->size >= (int)sizeof(IpcDataResize)) )
- {
- IpcDataResize *newSize = static_cast<IpcDataResize*>( epcEvent->data );
- Resize( newSize->w, newSize->h );
- }
- break;
- }
- case OP_MSG_PARENT:
- {
- int msgDomain = epcEvent->ref;
- int msgId = epcEvent->ref_to;
-
- void *msgData = NULL;
- int msgDataSize = 0;
- msgData = epcEvent->data;
- msgDataSize = epcEvent->size;
-
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_MSG_PARENT. msgDomain = %d\n", msgDomain );
-
- if( msgDomain == MSG_DOMAIN_CONTROL_INDICATOR )
- {
- switch( msgId )
- {
- case MSG_ID_INDICATOR_TYPE:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_MSG_PARENT, INDICATOR_TYPE\n" );
- Type* indicatorType = static_cast<Type*>( epcEvent->data );
- OnIndicatorTypeChanged( *indicatorType );
- break;
- }
-
- case MSG_ID_INDICATOR_START_ANIMATION:
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: MSG_ID_INDICATOR_START_ANIMATION\n" );
-
- if (msgDataSize != (int)sizeof(IpcIndicatorDataAnimation))
- {
- DALI_LOG_ERROR("Message data is incorrect\n");
- break;
- }
-
- IpcIndicatorDataAnimation *animData = static_cast<IpcIndicatorDataAnimation*>(msgData);
-
- if(!CheckVisibleState())
- {
- ShowIndicator( animData->duration /* n sec */ );
- }
- break;
- }
- }
- }
- break;
- }
- }
-}
-
-void Indicator::ConnectionClosed()
-{
- DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
-
- // Will get this callback if the server connection failed to start up.
- delete mServerConnection;
- mServerConnection = NULL;
- mState = DISCONNECTED;
-
- // Attempt to re-connect
- Connect();
-}
-
-bool Indicator::CheckVisibleState()
-{
- if( mOrientation == Dali::Window::LANDSCAPE
- || mOrientation == Dali::Window::LANDSCAPE_INVERSE
- || (mVisible == Dali::Window::INVISIBLE)
- || (mVisible == Dali::Window::AUTO && !mIsShowing) )
- {
- return false;
- }
-
- return true;
-}
-
-void Indicator::ClearSharedFileInfo()
-{
- for( int i = 0; i < SHARED_FILE_NUMBER; i++ )
- {
- delete mSharedFileInfo[i].mLock;
- mSharedFileInfo[i].mLock = NULL;
-
- delete mSharedFileInfo[i].mSharedFile;
- mSharedFileInfo[i].mSharedFile = NULL;
-
- mSharedFileInfo[i].mLockFileName.clear();
- mSharedFileInfo[i].mSharedFileName.clear();
- }
-}
-
-/**
- * duration can be this
- *
- * enum
- * {
- * KEEP_SHOWING = -1,
- * HIDE_NOW = 0
- * };
- */
-void Indicator::ShowIndicator(float duration)
-{
- if( !mIndicatorAnimation )
- {
- mIndicatorAnimation = Dali::Animation::New(SLIDING_ANIMATION_DURATION);
- mIndicatorAnimation.FinishedSignal().Connect(this, &Indicator::OnAnimationFinished);
- }
-
- if(mIsShowing && !EqualsZero(duration))
- {
- // If need to show during showing, do nothing.
- // In 2nd phase (below) will update timer
- }
- else if(!mIsShowing && mIsAnimationPlaying && EqualsZero(duration))
- {
- // If need to hide during hiding or hidden already, do nothing
- }
- else
- {
- mIndicatorAnimation.Clear();
-
- if( EqualsZero(duration) )
- {
- mIndicatorAnimation.AnimateTo( Property( mIndicatorContentActor, Dali::Actor::Property::POSITION ), Vector3(0, -mImageHeight, 0), Dali::AlphaFunction::EASE_OUT );
-
- mIsShowing = false;
-
- OnIndicatorTypeChanged( INDICATOR_TYPE_2 ); // un-toucable
- }
- else
- {
- mIndicatorAnimation.AnimateTo( Property( mIndicatorContentActor, Dali::Actor::Property::POSITION ), Vector3(0, 0, 0), Dali::AlphaFunction::EASE_OUT );
-
- mIsShowing = true;
-
- OnIndicatorTypeChanged( INDICATOR_TYPE_1 ); // touchable
- }
-
- mIndicatorAnimation.Play();
- mIsAnimationPlaying = true;
- }
-
- if(duration > 0)
- {
- if(!mShowTimer)
- {
- mShowTimer = Dali::Timer::New(1000 * duration);
- mShowTimer.TickSignal().Connect(this, &Indicator::OnShowTimer);
- }
- mShowTimer.SetInterval(1000* duration);
- mShowTimer.Start();
-
- if( mVisible == Dali::Window::AUTO )
- {
- // check the stage touch
- Dali::Stage::GetCurrent().TouchSignal().Connect( this, &Indicator::OnStageTouch );
- }
- }
- else
- {
- if(mShowTimer && mShowTimer.IsRunning())
- {
- mShowTimer.Stop();
- }
-
- if( mVisible == Dali::Window::AUTO )
- {
- // check the stage touch
- Dali::Stage::GetCurrent().TouchSignal().Disconnect( this, &Indicator::OnStageTouch );
- }
- }
-}
-
-bool Indicator::OnShowTimer()
-{
- // after time up, hide indicator
- ShowIndicator( HIDE_NOW );
-
- return false;
-}
-
-void Indicator::OnAnimationFinished(Dali::Animation& animation)
-{
- mIsAnimationPlaying = false;
- // once animation is finished and indicator is hidden, take it off stage
- if( mObserver != NULL )
- {
- mObserver->IndicatorVisibilityChanged( mIsShowing ); // is showing?
- }
-}
-
-void Indicator::OnPan( Dali::Actor actor, const Dali::PanGesture& gesture )
-{
- // Nothing to do, but we still want to consume pan
-}
-
-void Indicator::OnStageTouch(const Dali::TouchData& touchData)
-{
- // when stage is touched while indicator is showing temporary, hide it
- if( mIsShowing && ( CheckVisibleState() == false || mVisible == Dali::Window::AUTO ) )
- {
- switch( touchData.GetState(0) )
- {
- case Dali::PointState::DOWN:
- {
- // if touch point is inside the indicator, indicator is not hidden
- if( mImageHeight < int( touchData.GetScreenPosition(0).y ) )
- {
- ShowIndicator( HIDE_NOW );
- }
- break;
- }
-
- default:
- break;
- }
- }
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_INDICATOR_H__
-#define __DALI_INTERNAL_ECORE_INDICATOR_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/animation/animation.h>
-#include <dali/public-api/events/pan-gesture.h>
-#include <dali/public-api/events/pan-gesture-detector.h>
-#include <dali/public-api/events/touch-data.h>
-#include <dali/public-api/rendering/renderer.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/indicator-interface.h>
-#include <indicator-buffer.h>
-#include <ecore-server-connection.h>
-#include <shared-file.h>
-#include <timer.h>
-#include <window.h>
-
-namespace Dali
-{
-namespace Integration
-{
-class Core;
-}
-
-namespace Internal
-{
-namespace Adaptor
-{
-class Adaptor;
-
-typedef unsigned int PixmapId;
-
-/**
- * The Indicator class connects to the indicator server, and gets and draws the indicator
- * for the given orientation.
- */
-class Indicator : public ConnectionTracker, public ServerConnection::Observer, public IndicatorInterface
-{
-public:
-
- enum State
- {
- DISCONNECTED,
- CONNECTED
- };
-
- /**
- * copied from ecore_evas_extn_engine.h
- */
- enum BufferType
- {
- BUFFER_TYPE_SHM = 0, ///< shared memory-based buffer backend
- BUFFER_TYPE_DRI2_PIXMAP, ///< dri2 pixmap-based buffer backend
- BUFFER_TYPE_EVASGL_PIXMAP, ///< pixmap backend for Evas GL only (DEPRECATED)
- BUFFER_TYPE_GL_PIXMAP, ///< double buffered GL pixmap backend
- };
-
-protected:
- /**
- * Class to encapsulate lock file
- */
- class LockFile
- {
- public:
- /**
- * Constructor. open lock file
- */
- LockFile(const std::string filename);
-
- /**
- * Close lock file
- */
- ~LockFile();
-
- /**
- * Grab an exclusive lock on this file
- * @return true if the lock succeeded, false if it failed
- */
- bool Lock();
-
- /**
- * Remove the lock
- */
- void Unlock();
-
- /**
- * Test if there is an error with the lock file, and clears
- * the error flag;
- * @return true if an error was thrown
- */
- bool RetrieveAndClearErrorStatus();
-
- private:
- std::string mFilename;
- int mFileDescriptor;
- bool mErrorThrown;
- };
-
- /**
- * Class to ensure lock/unlock through object destruction
- */
- class ScopedLock
- {
- public:
- /**
- * Constructor - creates a lock on the lockfile
- * @param[in] lockFile The lockfile to use
- */
- ScopedLock( LockFile* lockFile );
-
- /**
- * Destructor - removes the lock (if any) on the lockfile
- */
- ~ScopedLock();
-
- /**
- * Method to test if the locking succeeded
- * @return TRUE if locked
- */
- bool IsLocked();
-
- private:
- LockFile* mLockFile; ///< The lock file to use
- bool mLocked; ///< Whether the lock succeeded
- };
-
-
-public: // Dali::Internal::Adaptor::IndicicatorInterface
- /**
- * @copydoc Dali::Internal::IndicatorInterface::IndicatorInterface
- */
- Indicator( Adaptor* adaptor,
- Dali::Window::WindowOrientation orientation,
- IndicatorInterface::Observer* observer );
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::~IndicatorInterface
- */
- virtual ~Indicator();
-
-
- virtual void SetAdaptor(Adaptor* adaptor);
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::GetActor
- */
- virtual Dali::Actor GetActor();
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::Open
- */
- virtual void Open( Dali::Window::WindowOrientation orientation );
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::Close
- */
- virtual void Close();
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::SetOpacityMode
- */
- virtual void SetOpacityMode( Dali::Window::IndicatorBgOpacity mode );
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::SetVisible
- */
- virtual void SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate = false );
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::IsConnected
- */
- virtual bool IsConnected();
-
- /**
- * @copydoc Dali::Internal::IndicatorInterface::SendMessage
- */
- virtual bool SendMessage( int messageDomain, int messageId, const void *data, int size );
-
-private:
- /**
- * Initialize the indicator actors
- */
- void Initialize();
-
- /**
- * Constructs the renderers used for the background
- */
- Dali::Geometry CreateBackgroundGeometry();
-
- /**
- * Set the texture to be rendered as indicator foreground
- * @param[in] texture The foreground texture.
- */
- void SetForegroundImage( Dali::Texture texture );
-
- /**
- * Touch event callback.
- * It should pass the valid touch event to indicator server
- *
- * @param[in] indicator The indicator actor that was touched
- * @param[in] touchEvent The touch data
- */
- bool OnTouch(Dali::Actor indicator, const Dali::TouchData& touchData);
-
- /**
- * Pan gesture callback.
- * It finds flick down gesture to show hidden indicator image
- *
- * @param[in] actor The actor for gesture
- * @param[in] gesture The gesture event
- */
- void OnPan( Dali::Actor actor, const Dali::PanGesture& gesture );
-
- /**
- * Touch event callback on stage.
- * If stage is touched, hide showing indicator image
- *
- * @param[in] touchEvent The touch data
- */
- void OnStageTouch(const Dali::TouchData& touchData);
-
- /**
- * Connect to the indicator service
- */
- bool Connect();
-
- /**
- * Start the reconnection timer. This will run every second until we reconnect to
- * the indicator service.
- */
- void StartReconnectionTimer();
-
- /**
- * If connection failed, attempt to re-connect every second
- */
- bool OnReconnectTimer();
-
- /**
- * Disconnect from the indicator service
- */
- void Disconnect();
-
- /**
- * Handle Resize event
- * @param[in] width The new width
- * @param[in] height The new height
- */
- void Resize( int width, int height );
-
- /**
- * Set the lock file info.
- * @param[in] epcEvent Current ecore event.
- */
- void SetLockFileInfo( Ecore_Ipc_Event_Server_Data *epcEvent );
-
- /**
- * Set the shared indicator image info
- * @param[in] epcEvent The event containing the image data
- */
- void SetSharedImageInfo( Ecore_Ipc_Event_Server_Data *epcEvent );
-
- /**
- * Load the shared indicator image
- * @param[in] epcEvent The event containing the image data
- */
- void LoadSharedImage( Ecore_Ipc_Event_Server_Data *epcEvent );
-
- /**
- * Load the pixmap indicator image
- * @param[in] epcEvent The event containing the image data
- */
- void LoadPixmapImage( Ecore_Ipc_Event_Server_Data *epcEvent );
-
- /**
- * Update top margin of the stage as much as indicator height
- */
- void UpdateTopMargin();
-
- /**
- * Update the visibility and position of the actors
- */
- void UpdateVisibility();
-
- /**
- * Inform dali that the indicator data has been updated.
- * @param[in] bufferNumber The shared file number
- */
- void UpdateImageData( int bufferNumber );
-
- /**
- * Lock the temporary file, Copy the shared image into IndicatorBuffer
- * and then unlock the temporary file.
- * Caller should ensure we are not writing image to gl texture.
- * @param[in] bufferNumber The shared file number
- */
- bool CopyToBuffer( int bufferNumber );
-
- /**
- * Create a new image for the indicator, and set up signal handling for it.
- * @param[in] bufferNumber The shared file number
- */
- void CreateNewImage( int bufferNumber );
-
- /**
- * Create a new pixmap image for the indicator, and set up signal handling for it.
- */
- void CreateNewPixmapImage();
-
- /**
- * Indicator type has changed.
- * Inform observer
- * @param[in] type The new indicator type
- */
- void OnIndicatorTypeChanged( Type type );
-
- /**
- * Check whether the indicator could be visible or invisible
- * @return true if indicator should be shown
- */
- bool CheckVisibleState();
-
- /**
- * Show/Hide indicator actor with effect
- * @param[in] duration how long need to show the indicator,
- * if it equal to 0, hide the indicator
- * if it less than 0, show always
- */
- void ShowIndicator( float duration );
-
- /**
- * Showing timer callback
- */
- bool OnShowTimer();
-
- /**
- * Showing animation finished callback
- * @param[in] animation
- */
- void OnAnimationFinished( Dali::Animation& animation );
-
-private: // Implementation of ServerConnection::Observer
- /**
- * @copydoc Dali::Internal::Adaptor::ServerConnection::Observer::DataReceived()
- */
- virtual void DataReceived( void* event );
-
- /**
- * @copydoc Dali::Internal::Adaptor::ServerConnection::Observer::DataReceived()
- */
- virtual void ConnectionClosed();
-
-private:
-
- /**
- * Clear shared file info
- */
- void ClearSharedFileInfo();
-
-private:
-
- struct SharedFileInfo
- {
- SharedFileInfo()
- : mLock( NULL ),
- mSharedFile( NULL ),
- mImageWidth( 0 ),
- mImageHeight( 0 ),
- mLockFileName(),
- mSharedFileName(),
- mSharedFileID( 0 ),
- mSharedFileNumber( 0 )
- {
- }
-
- LockFile* mLock; ///< File lock for the shared file
- SharedFile* mSharedFile; ///< Shared file
-
- int mImageWidth; ///< Shared image width
- int mImageHeight; ///< Shared image height
-
- std::string mLockFileName; ///< Lock file name
- std::string mSharedFileName; ///< Shared file name
- int mSharedFileID; ///< Shared file ID
- int mSharedFileNumber; ///< Shared file number
- };
-
- static const int SHARED_FILE_NUMBER = 2; ///< Shared file number
-
- Dali::Geometry mTranslucentGeometry; ///< Geometry used for rendering the translucent background
- Dali::Geometry mSolidGeometry; ///< Geometry used for rendering the opaque background
- Dali::Shader mBackgroundShader; ///< Shader used for rendering the background
-
- IndicatorBufferPtr mIndicatorBuffer; ///< class which handles indicator rendering
- PixmapId mPixmap; ///< Pixmap including indicator content
- Dali::Renderer mForegroundRenderer; ///< Renderer renders the indicator foreground
- Dali::Renderer mBackgroundRenderer; ///< Renderer renders the indicator background
-
- Dali::Actor mIndicatorContentActor; ///< Actor container for image and background
- Dali::Actor mIndicatorActor; ///< Handle to topmost indicator actor
- Dali::Actor mEventActor; ///< Handle to event
- Dali::PanGestureDetector mPanDetector; ///< Pan detector to find flick gesture for hidden indicator
- float mGestureDeltaY; ///< Checking how much panning moved
- bool mGestureDetected; ///< Whether find the flick gesture
-
- Dali::Timer mReconnectTimer; ///< Reconnection timer
- SlotDelegate< Indicator > mConnection;
-
- Dali::Window::IndicatorBgOpacity mOpacityMode; ///< Opacity enum for background
- Indicator::State mState; ///< The connection state
-
- Adaptor* mAdaptor;
- ServerConnection* mServerConnection;
- IndicatorInterface::Observer* mObserver; ///< Upload observer
-
- Dali::Window::WindowOrientation mOrientation;
- int mImageWidth;
- int mImageHeight;
- Dali::Window::IndicatorVisibleMode mVisible; ///< Whether the indicator is visible
-
- Dali::Timer mShowTimer; ///< Timer to show indicator
- bool mIsShowing; ///< Whether the indicator is showing on the screen
- Dali::Animation mIndicatorAnimation; ///< Animation to show/hide indicator image
-
- bool mIsAnimationPlaying; ///< Whether the animation is playing
-
- int mCurrentSharedFile; ///< Current shared file number
- SharedFileInfo mSharedFileInfo[SHARED_FILE_NUMBER]; ///< Table to store shared file info
-
- BufferType mSharedBufferType; ///< Shared buffer type which is used to render indicator
-
- struct Impl; ///< Contains Ecore specific information
- Impl* mImpl; ///< Created on construction and destroyed on destruction.
-
- bool mBackgroundVisible; ///< Indicate whether background is visible
- int mTopMargin; ///< Top margin of the stage for indicator
-};
-
-} // Adaptor
-} // Internal
-} // Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-server-connection.h"
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-
-namespace
-{
-// Copied from ecore_evas_extn_engine.h
-// procotol version - change this as needed
-const int MAJOR( 0x2011 );
-}
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gIndicatorLogFilter;
-#endif
-
-ServerConnection::ServerConnection(
- const char* serviceName,
- int serviceNumber,
- bool isSystem,
- ServerConnection::Observer* observer)
-
-: mConnected(false),
- mObserver(observer)
-{
- Ecore_Ipc_Type ipctype = ECORE_IPC_LOCAL_USER;
-
- ecore_ipc_init();
- mService.name = eina_stringshare_add(serviceName);
- mService.num = serviceNumber;
- mService.isSystem = isSystem;
-
- if( mService.isSystem )
- {
- ipctype = ECORE_IPC_LOCAL_SYSTEM;
- }
-
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: Connecting to %s %d\n", mService.name, mService.num );
-
- mIpcServer = ecore_ipc_server_connect( ipctype, (char *)mService.name, mService.num, this );
-
- if( !mIpcServer )
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "mIpcServer is null\n" );
- ecore_ipc_shutdown();
- }
- else
- {
- mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_ADD,
- &ServerConnection::IpcServerAdd,
- this ) );
-
- mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_DEL,
- &ServerConnection::IpcServerDel,
- this ) );
-
- mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_DATA,
- &ServerConnection::IpcServerData,
- this));
-
- mConnected = true;
- }
-}
-
-ServerConnection::~ServerConnection()
-{
- CloseConnection();
-
- if( mService.name != NULL )
- {
- eina_stringshare_del(mService.name);
- }
-
- for( Handlers::iterator iter = mIpcHandlers.begin(); iter != mIpcHandlers.end(); ++iter )
- {
- ecore_event_handler_del(*iter);
- }
- mIpcHandlers.clear();
-}
-
-bool ServerConnection::IsConnected()
-{
- return mConnected;
-}
-
-void ServerConnection::OnDisconnect()
-{
- mConnected = false;
- mIpcServer = NULL;
- ecore_ipc_shutdown();
- if( mObserver )
- {
- mObserver->ConnectionClosed();
- }
-}
-
-bool ServerConnection::SendEvent( int event, const void *data, int size )
-{
- return SendEvent(event, 0, 0, data, size);
-}
-
-bool ServerConnection::SendEvent( int event, int ref, int ref_to, const void *data, int size )
-{
- if( mIpcServer != NULL && ecore_ipc_server_send(mIpcServer, MAJOR, event, ref, ref_to, 0, data, size) )
- {
- return true;
- }
- else
- {
- return false;
- }
-}
-
-Eina_Bool ServerConnection::IpcServerAdd( void *data, int /*type*/, void *event )
-{
- DALI_LOG_INFO(gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerAdd\n" );
-
- return ECORE_CALLBACK_PASS_ON;
-}
-
-Eina_Bool ServerConnection::IpcServerDel( void *data, int /*type*/, void *event )
-{
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerDel\n" );
-
- Ecore_Ipc_Event_Server_Del *e = static_cast<Ecore_Ipc_Event_Server_Del *>( event );
- ServerConnection* connection = static_cast<ServerConnection*>( data );
-
- if( connection != NULL )
- {
- if( connection->mIpcServer == e->server)
- {
- // No longer have a server connection
- connection->OnDisconnect();
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
-}
-
-Eina_Bool ServerConnection::IpcServerData( void *data, int /*type*/, void *event )
-{
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerData\n" );
-
- Ecore_Ipc_Event_Server_Data *e = static_cast<Ecore_Ipc_Event_Server_Data *>( event );
- ServerConnection* connection = static_cast<ServerConnection*>( data );
-
- if( connection != NULL )
- {
- if( connection != ecore_ipc_server_data_get( e->server ) )
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
- if( e->major != MAJOR )
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
- if( connection->mObserver )
- {
- connection->mObserver->DataReceived( event );
- }
- }
- return ECORE_CALLBACK_PASS_ON;
-}
-
-void ServerConnection::CloseConnection()
-{
- if( mConnected )
- {
- DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: CloseConnection\n" );
-
- if( mIpcServer )
- {
- ecore_ipc_server_del( mIpcServer );
- mIpcServer = NULL;
- }
-
- ecore_ipc_shutdown();
- mConnected = false;
- }
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "virtual-keyboard-impl.h"
-
-// EXTERNAL INCLUDES
-#include <algorithm>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include "ecore-virtual-keyboard.h"
-#include <adaptor.h>
-#include <locale-utils.h>
-#include <imf-manager-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace VirtualKeyboard
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIRTUAL_KEYBOARD");
-#endif
-
-#define TOKEN_STRING(x) #x
-
-//forward declarations
-void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value );
-void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value );
-
-// Signals
-Dali::VirtualKeyboard::StatusSignalType gKeyboardStatusSignal;
-Dali::VirtualKeyboard::VoidSignalType gKeyboardResizeSignal;
-Dali::VirtualKeyboard::VoidSignalType gKeyboardLanguageChangedSignal;
-
-void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
-{
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n" );
-
- gKeyboardStatusSignal.Emit( true );
-
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n" );
-
- gKeyboardStatusSignal.Emit( false );
-
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
- default:
- {
- // Do nothing
- break;
- }
- }
-}
-
-void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback\n" );
-
- // Emit the signal that the language has changed
- gKeyboardLanguageChangedSignal.Emit();
-}
-
-void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n" );
-
- // Emit signal that the keyboard is resized
- gKeyboardResizeSignal.Emit();
-}
-
-} // unnamed namespace
-
-void ConnectCallbacks( Ecore_IMF_Context *imfContext )
-{
- if( imfContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n" );
-
- ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL );
- ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL );
- ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL );
- }
-}
-
-void DisconnectCallbacks( Ecore_IMF_Context *imfContext )
-{
- if( imfContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n" );
-
- ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
- ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
- ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
- }
-}
-
-void Show()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Show() is deprecated and will be removed from next release. Use ImfManager.Activate() instead.\n" );
-
- Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) to show the keyboard
-
- if( imfManager )
- {
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if( imfContext )
- {
- ecore_imf_context_input_panel_show( imfContext );
- }
- }
-}
-
-void Hide()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Hide() is deprecated and will be removed from next release. Use ImfManager.Deactivate() instead.\n" );
-
- if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance*/ )
- {
- Dali::ImfManager imfManager = ImfManager::Get();
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if( imfContext )
- {
- ecore_imf_context_input_panel_hide( imfContext );
- }
- }
-}
-
-bool IsVisible()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IsVisible() is deprecated and will be removed from next release.\n" );
-
- if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance */ )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "IMF IsVisible\n" );
-
- Dali::ImfManager imfManager = ImfManager::Get();
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if ( imfContext )
- {
- if (ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_SHOW ||
- ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW)
- {
- return true;
- }
- }
- }
-
- return false;
-}
-
-void ApplySettings( const Property::Map& settingsMap )
-{
- using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING.
-
- for ( unsigned int i = 0, count = settingsMap.Count(); i < count; ++i )
- {
- Property::Key key = settingsMap.GetKeyAt( i );
- if( key.type == Property::Key::INDEX )
- {
- continue;
- }
-
- Property::Value item = settingsMap.GetValue(i);
-
- if ( key == TOKEN_STRING( ACTION_BUTTON ) )
- {
- if ( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- VirtualKeyboard::SetReturnKeyType( static_cast<InputMethod::ActionButton>(value) );
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" );
- }
- }
-}
-
-void EnablePrediction(const bool enable)
-{
- Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when enabling prediction
-
- if( imfManager )
- {
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if ( imfContext )
- {
- ecore_imf_context_prediction_allow_set( imfContext, (enable)? EINA_TRUE : EINA_FALSE);
- }
- }
-}
-
-bool IsPredictionEnabled()
-{
- if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManger */ )
- {
- Dali::ImfManager imfManager = ImfManager::Get();
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if ( imfContext )
- {
- // predictive text is enabled.
- if ( ecore_imf_context_input_panel_enabled_get( imfContext ) == EINA_TRUE )
- {
- return true;
- }
- }
- }
-
- return false;
-}
-
-Rect<int> GetSizeAndPosition()
-{
- int xPos, yPos, width, height;
-
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetSizeAndPosition() is deprecated and will be removed from next release. Use ImfManager.GetInputMethodArea() instead.\n" );
-
- width = height = xPos = yPos = 0;
- Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) as we may need to do some size related setup in the application
-
- if( imfManager )
- {
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if( imfContext )
- {
- ecore_imf_context_input_panel_geometry_get(imfContext, &xPos, &yPos, &width, &height);
- }
- else
- {
- DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
- // return 0 as real size unknown.
- }
- }
-
- return Rect<int>(xPos,yPos,width,height);
-}
-
-Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: StatusChangedSignal() is deprecated and will be removed from next release. Use ImfManager.StatusChangedSignal() instead.\n" );
-
- Dali::ImfManager imfManager = ImfManager::Get();
- return imfManager.StatusChangedSignal();
-}
-
-Dali::VirtualKeyboard::KeyboardResizedSignalType& ResizedSignal()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ResizedSignal() is deprecated and will be removed from next release. Use ImfManager.ResizedSignal() instead.\n" );
-
- Dali::ImfManager imfManager = ImfManager::Get();
- return imfManager.ResizedSignal();
-}
-
-Dali::VirtualKeyboard::LanguageChangedSignalType& LanguageChangedSignal()
-{
- DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: LanguageChangedSignal() is deprecated and will be removed from next release. Use ImfManager.LanguageChangedSignal() instead.\n" );
-
- Dali::ImfManager imfManager = ImfManager::Get();
- return imfManager.LanguageChangedSignal();
-}
-
-Dali::VirtualKeyboard::TextDirection GetTextDirection()
-{
- Dali::VirtualKeyboard::TextDirection direction ( Dali::VirtualKeyboard::LeftToRight );
-
- if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
- {
- Dali::ImfManager imfManager = ImfManager::Get();
-
- if ( imfManager )
- {
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if ( imfContext )
- {
- char* locale( NULL );
- ecore_imf_context_input_panel_language_locale_get( imfContext, &locale );
-
- if ( locale )
- {
- direction = static_cast< Dali::VirtualKeyboard::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
- free( locale );
- }
- }
- }
- }
- return direction;
-}
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
-#define __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_IMF.h>
-
-// INTERNAL INCLUDES
-#include <virtual-keyboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Implementation of the virtual keyboard namespace
- */
-namespace VirtualKeyboard
-{
-
-/**
- * Connect the virtual keyboard callbacks.
- * To get the virtual keyboard callbacks then you have to connect these callback.
- * If you don't connect callbacks, you can't get virtual keyboard signals.
- * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal.
- */
-void ConnectCallbacks( Ecore_IMF_Context *imfContext );
-
-/**
- * Disconnect the virtual keyboard callbacks.
- * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal.
- */
-void DisconnectCallbacks( Ecore_IMF_Context *imfContext );
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
+++ /dev/null
-# ECore Common
-
-adaptor_ecore_common_internal_src_files = \
- $(adaptor_ecore_common_dir)/ecore-virtual-keyboard.cpp \
- $(adaptor_ecore_common_dir)/ecore-indicator-impl.cpp \
- $(adaptor_ecore_common_dir)/ecore-server-connection.cpp
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "clipboard-impl.h"
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Ecore_Wayland.h>
-#include <dali/public-api/object/any.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-#include <unistd.h>
-
-#ifdef DALI_ELDBUS_AVAILABLE
-#include <Eldbus.h>
-#endif // DALI_ELDBUS_AVAILABLE
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-#define CBHM_DBUS_OBJPATH "/org/tizen/cbhm/dbus"
-#ifndef CBHM_DBUS_INTERFACE
-#define CBHM_DBUS_INTERFACE "org.tizen.cbhm.dbus"
-#endif /* CBHM_DBUS_INTERFACE */
-#define CBHM_COUNT_ALL 0 // ATOM_INDEX_CBHM_COUNT_ALL
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Clipboard
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-struct Clipboard::Impl
-{
- Impl()
- {
- Eldbus_Object *eldbus_obj;
- cbhm_conn = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SESSION);
- eldbus_obj = eldbus_object_get(cbhm_conn, CBHM_DBUS_INTERFACE, CBHM_DBUS_OBJPATH);
- eldbus_proxy = eldbus_proxy_get(eldbus_obj, CBHM_DBUS_INTERFACE);
- eldbus_name_owner_changed_callback_add(cbhm_conn, CBHM_DBUS_INTERFACE, NULL, cbhm_conn, EINA_TRUE);
- eldbus_proxy_signal_handler_add(eldbus_proxy, "ItemClicked", _on_item_clicked, this);
- mVisible = false;
- mIsFirstTimeHidden = true;
- }
-
- ~Impl()
- {
- if (cbhm_conn)
- eldbus_connection_unref(cbhm_conn);
- }
-
- Eldbus_Proxy* cbhm_proxy_get()
- {
- return eldbus_proxy;
- }
-
- Eldbus_Connection* cbhm_connection_get()
- {
- return cbhm_conn;
- }
-
- void SetItem( const std::string &itemData )
- {
- const char *types[10] = {0, };
- int i = -1;
-
- if (itemData.length() == 0)
- {
- return;
- }
- mSendBuffer = itemData;
-
- // ELM_SEL_TYPE_CLIPBOARD - To distinguish clipboard selection in cbhm
- types[++i] = "CLIPBOARD_BEGIN";
-
- types[++i] = "text/plain;charset=utf-8";
-
- // ELM_SEL_TYPE_CLIPBOARD - To distinguish clipboard selection in cbhm
- types[++i] = "CLIPBOARD_END";
- ecore_wl_dnd_selection_set(ecore_wl_input_get(), types);
- }
-
- void RequestItem()
- {
- const char *types[10] = {0, };
- int i = -1;
-
- types[++i] = "text/plain;charset=utf-8";
- ecore_wl_dnd_selection_get(ecore_wl_input_get(), *types);
- }
-
- char *ExcuteSend( void *event )
- {
- Ecore_Wl_Event_Data_Source_Send *ev = (Ecore_Wl_Event_Data_Source_Send *)event;
- int len_buf = mSendBuffer.length();
- int len_remained = len_buf;
- int len_written = 0, ret;
- const char *buf = mSendBuffer.c_str();
-
- while (len_written < len_buf)
- {
- ret = write(ev->fd, buf, len_remained);
- if (ret == -1) break;
- buf += ret;
- len_written += ret;
- len_remained -= ret;
- }
- close(ev->fd);
- return NULL;
- }
-
- char *ExcuteReceive( void *event )
- {
- Ecore_Wl_Event_Selection_Data_Ready *ev = (Ecore_Wl_Event_Selection_Data_Ready *)event;
-
- return (char *)ev->data;
- }
-
- int GetCount()
- {
- Eldbus_Message *reply, *req;
- const char *errname = NULL, *errmsg = NULL;
- int count = -1;
-
- if (!(req = eldbus_proxy_method_call_new(eldbus_proxy, "CbhmGetCount")))
- {
- DALI_LOG_ERROR("Failed to create method call on org.freedesktop.DBus.Properties.Get");
- return -1;
- }
-
- eldbus_message_ref(req);
- eldbus_message_arguments_append(req, "i", CBHM_COUNT_ALL) ;
- reply = eldbus_proxy_send_and_block(eldbus_proxy, req, 100);
- if (!reply || eldbus_message_error_get(reply, &errname, &errmsg))
- {
- DALI_LOG_ERROR("Unable to call method org.freedesktop.DBus.Properties.Get: %s %s",
- errname, errmsg);
- eldbus_message_unref(req);
- return -1;
- }
-
- if (!eldbus_message_arguments_get(reply, "i", &count))
- {
- DALI_LOG_ERROR("Cannot get arguments from eldbus");
- eldbus_message_unref(req);
- return -1;
- }
-
- eldbus_message_unref(req);
- DALI_LOG_ERROR("cbhm item count(%d)", count);
- return count;
- }
-
- void ShowClipboard()
- {
- eldbus_proxy_call(cbhm_proxy_get(), "CbhmShow", NULL, NULL, -1, "s", "0");
- mIsFirstTimeHidden = true;
- mVisible = true;
- }
-
- void HideClipboard( bool skipFirstHide )
- {
- if ( skipFirstHide && mIsFirstTimeHidden )
- {
- mIsFirstTimeHidden = false;
- return;
- }
- eldbus_proxy_call(cbhm_proxy_get(), "CbhmHide", NULL, NULL, -1, "");
- mIsFirstTimeHidden = false;
- mVisible = false;
- }
-
- bool IsVisible() const
- {
- return mVisible;
- }
-
- static void _on_item_clicked(void *data, const Eldbus_Message *msg EINA_UNUSED)
- {
- static_cast<Clipboard::Impl*>(data)->RequestItem();
- }
-
- Eldbus_Proxy *eldbus_proxy;
- Eldbus_Connection *cbhm_conn;
-
- std::string mSendBuffer;
- bool mVisible;
- bool mIsFirstTimeHidden;
-};
-
-Clipboard::Clipboard(Impl* impl)
-: mImpl(impl)
-{
-}
-
-Clipboard::~Clipboard()
-{
- delete mImpl;
-}
-
-Dali::Clipboard Clipboard::Get()
-{
- Dali::Clipboard clipboard;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) );
- if(handle)
- {
- // If so, downcast the handle
- clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) );
- }
- else
- {
- Clipboard::Impl* impl( new Clipboard::Impl() );
- clipboard = Dali::Clipboard( new Clipboard(impl) );
- service.Register( typeid(Dali::Clipboard), clipboard );
- }
- }
-
- return clipboard;
-}
-
-bool Clipboard::SetItem(const std::string &itemData )
-{
- mImpl->SetItem( itemData );
- return true;
-}
-
-/*
- * Request clipboard service to give an item
- */
-void Clipboard::RequestItem()
-{
- mImpl->RequestItem();
-}
-
-/*
- * Get number of items in clipboard
- */
-unsigned int Clipboard::NumberOfItems()
-{
- return mImpl->GetCount();
-}
-
-void Clipboard::ShowClipboard()
-{
- mImpl->ShowClipboard();
-}
-
-void Clipboard::HideClipboard(bool skipFirstHide)
-{
- mImpl->HideClipboard(skipFirstHide);
-}
-
-bool Clipboard::IsVisible() const
-{
- return mImpl->IsVisible();
-}
-
-char* Clipboard::ExcuteBuffered( bool type, void *event )
-{
- return (type ? mImpl->ExcuteSend( event ) : mImpl->ExcuteReceive( event ));
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "display-connection-impl.h"
-
-// EXTERNAL_HEADERS
-#include <Ecore_Wayland.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL HEADERS
-#include <native-render-surface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-DisplayConnection* DisplayConnection::New()
-{
- DisplayConnection* pDisplayConnection(new DisplayConnection());
-
- return pDisplayConnection;
-}
-
-DisplayConnection::DisplayConnection()
-: mDisplay( NULL ),
- mSurfaceType( RenderSurface::ECORE_RENDER_SURFACE )
-{
-}
-
-DisplayConnection::~DisplayConnection()
-{
- if( mSurfaceType == RenderSurface::NATIVE_RENDER_SURFACE )
- {
- ReleaseNativeDisplay();
- }
-}
-
-Any DisplayConnection::GetDisplay()
-{
- return Any( mDisplay );
-}
-
-void DisplayConnection::ConsumeEvents()
-{
-}
-
-bool DisplayConnection::InitializeEgl(EglInterface& egl)
-{
- EglImplementation& eglImpl = static_cast<EglImplementation&>(egl);
-
- if( !eglImpl.InitializeGles( mDisplay ) )
- {
- DALI_LOG_ERROR("Failed to initialize GLES.\n");
- return false;
- }
-
- return true;
-}
-
-void DisplayConnection::SetSurfaceType( RenderSurface::Type type )
-{
- mSurfaceType = type;
-
- if( mSurfaceType == RenderSurface::NATIVE_RENDER_SURFACE )
- {
- mDisplay = GetNativeDisplay();
- }
- else
- {
- mDisplay = reinterpret_cast< EGLNativeDisplayType >( ecore_wl_display_get() );
- }
-}
-
-void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
-{
- // calculate DPI
- float xres, yres;
-
- // 1 inch = 25.4 millimeters
- xres = ecore_wl_dpi_get();
- yres = ecore_wl_dpi_get();
-
- dpiHorizontal = int(xres + 0.5f); // rounding
- dpiVertical = int(yres + 0.5f);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_WAYLAND_DIPLAY_CONNECTION_H__
-#define __DALI_INTERNAL_ECORE_WAYLAND_DIPLAY_CONNECTION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wayland-egl.h>
-#include <Ecore_Wayland.h>
-#include <wl-types.h>
-
-// INTERNAL INCLUDES
-#include <base/display-connection.h>
-#include <dali/public-api/object/base-object.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-class DisplayConnection;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * DisplayConnection implementation
- */
-class DisplayConnection : public Dali::BaseObject
-{
-public:
-
- /**
- * @brief Default constructor
- */
- DisplayConnection();
-
- /**
- * @brief Create an initialized DisplayConnection.
- *
- * @return A handle to a newly allocated DisplayConnection resource.
- */
- static DisplayConnection* New();
-
-public:
-
- /**
- * @copydoc Dali::DisplayConnection::GetDisplay
- */
- Any GetDisplay();
-
- /**
- * @copydoc Dali::DisplayConnection::GetDpi
- */
- static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
-
- /**
- * @copydoc Dali::DisplayConnection::ConsumeEvents
- */
- void ConsumeEvents();
-
- /**
- * @copydoc Dali::DisplayConnection::InitializeEgl
- */
- bool InitializeEgl(EglInterface& egl);
-
- /**
- * @brief Sets surface type
- */
- void SetSurfaceType( RenderSurface::Type type );
-
-public:
-
- /**
- * Destructor
- */
- virtual ~DisplayConnection();
-
-protected:
-
- /**
- * @brief Gets display connection for native surface
- */
- EGLNativeDisplayType GetNativeDisplay();
-
- /**
- * @brief Release display connection for native surface
- */
- void ReleaseNativeDisplay();
-
- // Undefined
- DisplayConnection(const DisplayConnection&);
-
- // Undefined
- DisplayConnection& operator=(const DisplayConnection& rhs);
-
-private:
- EGLNativeDisplayType mDisplay; ///< Wayland-display for rendering
- RenderSurface::Type mSurfaceType;
-};
-
-} // namespace Adaptor
-
-} // namespace internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ECORE_X_DIPLAY_CONNECTION_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <events/event-handler.h>
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Ecore_Input.h>
-#include <ecore-wl-render-surface.h>
-#include <cstring>
-
-#include <sys/time.h>
-
-#ifndef DALI_PROFILE_UBUNTU
-#include <vconf.h>
-#include <vconf-keys.h>
-#endif // DALI_PROFILE_UBUNTU
-
-#ifdef DALI_ELDBUS_AVAILABLE
-#include <Eldbus.h>
-#endif // DALI_ELDBUS_AVAILABLE
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/events/device.h>
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/events/key-event.h>
-#include <dali/public-api/events/wheel-event.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/events/key-event-integ.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <dali/integration-api/events/hover-event-integ.h>
-#include <dali/integration-api/events/wheel-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-manager.h>
-#include <window-render-surface.h>
-#include <clipboard-impl.h>
-#include <key-impl.h>
-#include <physical-keyboard-impl.h>
-#include <style-monitor-impl.h>
-#include <base/core-event-interface.h>
-#include <virtual-keyboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-namespace
-{
-Integration::Log::Filter* gTouchEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_TOUCH");
-Integration::Log::Filter* gDragAndDropLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DND");
-Integration::Log::Filter* gImfLogging = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_IMF");
-Integration::Log::Filter* gSelectionEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_SELECTION");
-} // unnamed namespace
-#endif
-
-
-namespace
-{
-
-// DBUS accessibility
-const char* BUS = "org.enlightenment.wm-screen-reader";
-const char* INTERFACE = "org.tizen.GestureNavigation";
-const char* PATH = "/org/tizen/GestureNavigation";
-
-const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 );
-
-const unsigned int BYTES_PER_CHARACTER_FOR_ATTRIBUTES = 3;
-
-/**
- * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h.
- * This function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Modifiers enums.
- * @param[in] ecoreModifier the Ecore_Event_Modifier input.
- * @return the Ecore_IMF_Keyboard_Modifiers output.
- */
-Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier)
-{
- int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE.
-
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR;
- }
-
- return static_cast<Ecore_IMF_Keyboard_Modifiers>( modifier );
-}
-
-
-// Copied from x server
-static unsigned int GetCurrentMilliSeconds(void)
-{
- struct timeval tv;
-
- struct timespec tp;
- static clockid_t clockid;
-
- if (!clockid)
- {
-#ifdef CLOCK_MONOTONIC_COARSE
- if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 &&
- (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0)
- {
- clockid = CLOCK_MONOTONIC_COARSE;
- }
- else
-#endif
- if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
- {
- clockid = CLOCK_MONOTONIC;
- }
- else
- {
- clockid = ~0L;
- }
- }
- if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
- {
- return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
- }
-
- gettimeofday(&tv, NULL);
- return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
-}
-
-#ifndef DALI_PROFILE_UBUNTU
-const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced.
-#endif // DALI_PROFILE_UBUNTU
-
-/**
- * Get the device name from the provided ecore key event
- */
-void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result )
-{
- const char* ecoreDeviceName = ecore_device_name_get( keyEvent->dev );
-
- if ( ecoreDeviceName )
- {
- result = ecoreDeviceName;
- }
-}
-
-/**
- * Get the device class from the provided ecore event
- */
-void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass )
-{
- switch( ecoreDeviceClass )
- {
- case ECORE_DEVICE_CLASS_SEAT:
- {
- deviceClass = Device::Class::USER;
- break;
- }
- case ECORE_DEVICE_CLASS_KEYBOARD:
- {
- deviceClass = Device::Class::KEYBOARD;
- break;
- }
- case ECORE_DEVICE_CLASS_MOUSE:
- {
- deviceClass = Device::Class::MOUSE;
- break;
- }
- case ECORE_DEVICE_CLASS_TOUCH:
- {
- deviceClass = Device::Class::TOUCH;
- break;
- }
- case ECORE_DEVICE_CLASS_PEN:
- {
- deviceClass = Device::Class::PEN;
- break;
- }
- case ECORE_DEVICE_CLASS_POINTER:
- {
- deviceClass = Device::Class::POINTER;
- break;
- }
- case ECORE_DEVICE_CLASS_GAMEPAD:
- {
- deviceClass = Device::Class::GAMEPAD;
- break;
- }
- default:
- {
- deviceClass = Device::Class::NONE;
- break;
- }
- }
-}
-
-void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass )
-{
- switch( ecoreDeviceSubclass )
- {
- case ECORE_DEVICE_SUBCLASS_FINGER:
- {
- deviceSubclass = Device::Subclass::FINGER;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_FINGERNAIL:
- {
- deviceSubclass = Device::Subclass::FINGERNAIL;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_KNUCKLE:
- {
- deviceSubclass = Device::Subclass::KNUCKLE;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_PALM:
- {
- deviceSubclass = Device::Subclass::PALM;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_HAND_SIZE:
- {
- deviceSubclass = Device::Subclass::HAND_SIDE;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_HAND_FLAT:
- {
- deviceSubclass = Device::Subclass::HAND_FLAT;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_PEN_TIP:
- {
- deviceSubclass = Device::Subclass::PEN_TIP;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_TRACKPAD:
- {
- deviceSubclass = Device::Subclass::TRACKPAD;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_TRACKPOINT:
- {
- deviceSubclass = Device::Subclass::TRACKPOINT;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_TRACKBALL:
- {
- deviceSubclass = Device::Subclass::TRACKBALL;
- break;
- }
-#ifdef OVER_TIZEN_VERSION_4
- case ECORE_DEVICE_SUBCLASS_REMOCON:
- {
- deviceSubclass = Device::Subclass::REMOCON;
- break;
- }
- case ECORE_DEVICE_SUBCLASS_VIRTUAL_KEYBOARD:
- {
- deviceSubclass = Device::Subclass::VIRTUAL_KEYBOARD;
- break;
- }
-#endif
- default:
- {
- deviceSubclass = Device::Subclass::NONE;
- break;
- }
- }
-}
-
-} // unnamed namespace
-
-// Impl to hide EFL implementation.
-struct EventHandler::Impl
-{
- // Construction & Destruction
-
- /**
- * Constructor
- */
- Impl( EventHandler* handler, Ecore_Wl_Window* window )
- : mHandler( handler ),
- mEcoreEventHandler(),
- mWindow( window ),
- mRotationAngle( 0 ),
- mWindowWidth( 0 ),
- mWindowHeight( 0 )
-#ifdef DALI_ELDBUS_AVAILABLE
- , mSystemConnection( NULL )
-#endif // DALI_ELDBUS_AVAILABLE
- {
- // Only register for touch and key events if we have a window
- if ( window != 0 )
- {
- // Register Touch events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, handler ) );
-
- // Register Mouse wheel events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, handler ) );
-
- // Register Focus events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, handler ) );
-
- // Register Key events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, handler ) );
-
- // Register Selection event - clipboard selection
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, handler ) );
-
- // Register Rotate event
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ROTATE, EcoreEventRotate, handler) );
-
- // Register Detent event
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_DETENT_ROTATE, EcoreEventDetent, handler) );
-
-#ifndef DALI_PROFILE_UBUNTU
- // Register Vconf notify - font name and size
- vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontNameChanged, handler );
- vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, handler );
-#endif // DALI_PROFILE_UBUNTU
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Initialize ElDBus.
- DALI_LOG_INFO( gImfLogging, Debug::General, "Starting DBus Initialization\n" );
-
- // Pass in handler.
- EcoreElDBusInitialisation( handler );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "Finished DBus Initialization\n" );
-#endif // DALI_ELDBUS_AVAILABLE
- }
- }
-
- /**
- * Destructor
- */
- ~Impl()
- {
-#ifndef DALI_PROFILE_UBUNTU
- vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged );
- vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontNameChanged );
-#endif // DALI_PROFILE_UBUNTU
-
- for( std::vector<Ecore_Event_Handler*>::iterator iter = mEcoreEventHandler.begin(), endIter = mEcoreEventHandler.end(); iter != endIter; ++iter )
- {
- ecore_event_handler_del( *iter );
- }
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Close down ElDBus connections.
- if( mSystemConnection )
- {
- eldbus_connection_unref( mSystemConnection );
- }
-#endif // DALI_ELDBUS_AVAILABLE
- }
-
- // Static methods
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Touch Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a touch down is received.
- */
- static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- PointState::Type state ( PointState::DOWN );
-
- // Check if the buttons field is set and ensure it's the primary touch button.
- // If this event was triggered by buttons other than the primary button (used for touch), then
- // just send an interrupted event to Core.
- if ( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) )
- {
- state = PointState::INTERRUPTED;
- }
-
- Device::Class::Type deviceClass;
- Device::Subclass::Type deviceSubclass;
-
- GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
- GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
-
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( state );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- point.SetDeviceClass( deviceClass );
- point.SetDeviceSubclass( deviceSubclass );
-
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a touch up is received.
- */
- static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- Device::Class::Type deviceClass;
- Device::Subclass::Type deviceSubclass;
-
- GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
- GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
-
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( PointState::UP );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- point.SetDeviceClass( deviceClass );
- point.SetDeviceSubclass( deviceSubclass );
-
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a touch motion is received.
- */
- static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Move *touchEvent( (Ecore_Event_Mouse_Move*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- Device::Class::Type deviceClass;
- Device::Subclass::Type deviceSubclass;
-
- GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
- GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
-
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( PointState::MOTION );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- point.SetDeviceClass( deviceClass );
- point.SetDeviceSubclass( deviceSubclass );
-
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a touch is canceled.
- */
- static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if( touchEvent->window == (unsigned int)ecore_wl_window_id_get( handler->mImpl->mWindow ) )
- {
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( PointState::INTERRUPTED );
- point.SetScreenPosition( Vector2( 0.0f, 0.0f ) );
- handler->SendEvent( point, touchEvent->timestamp );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventMouseButtonCancel\n" );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a mouse wheel is received.
- */
- static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Wheel *mouseWheelEvent( (Ecore_Event_Mouse_Wheel*)event );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT Ecore_Event_Mouse_Wheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z);
-
- EventHandler* handler( (EventHandler*)data );
- if ( mouseWheelEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- WheelEvent wheelEvent( WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp );
- handler->SendWheelEvent( wheelEvent );
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Key Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a key down is received.
- */
- static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyDown \n" );
-
- EventHandler* handler( (EventHandler*)data );
- Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
- bool eventHandled( false );
-
- // If a device key then skip ecore_imf_context_filter_event.
- if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
- {
- Ecore_IMF_Context* imfContext = NULL;
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
- }
-
- if ( imfContext )
- {
- // We're consuming key down event so we have to pass to IMF so that it can parse it as well.
- Ecore_IMF_Event_Key_Down ecoreKeyDownEvent;
- ecoreKeyDownEvent.keyname = keyEvent->keyname;
- ecoreKeyDownEvent.key = keyEvent->key;
- ecoreKeyDownEvent.string = keyEvent->string;
- ecoreKeyDownEvent.compose = keyEvent->compose;
- ecoreKeyDownEvent.timestamp = keyEvent->timestamp;
- ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
- ecoreKeyDownEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
- ecoreKeyDownEvent.dev_name = ecore_device_name_get( keyEvent->dev );
- ecoreKeyDownEvent.dev_class = static_cast<Ecore_IMF_Device_Class>( ecore_device_class_get( keyEvent->dev ) );
- ecoreKeyDownEvent.dev_subclass = static_cast<Ecore_IMF_Device_Subclass>( ecore_device_subclass_get( keyEvent->dev ) );
-
- std::string checkDevice;
- GetDeviceName( keyEvent, checkDevice );
-
- // If the device is IME and the focused key is the direction keys, then we should send a key event to move a key cursor.
- if( ( checkDevice == "ime" ) && ( ( !strncmp( keyEvent->keyname, "Left", 4 ) ) ||
- ( !strncmp( keyEvent->keyname, "Right", 5 ) ) ||
- ( !strncmp( keyEvent->keyname, "Up", 2 ) ) ||
- ( !strncmp( keyEvent->keyname, "Down", 4 ) ) ) )
- {
- eventHandled = 0;
- }
- else
- {
- eventHandled = ecore_imf_context_filter_event( imfContext,
- ECORE_IMF_EVENT_KEY_DOWN,
- (Ecore_IMF_Event *) &ecoreKeyDownEvent );
- }
-
- // If the event has not been handled by IMF then check if we should reset our IMF context
- if( !eventHandled )
- {
- if ( !strcmp( keyEvent->keyname, "Escape" ) ||
- !strcmp( keyEvent->keyname, "Return" ) ||
- !strcmp( keyEvent->keyname, "KP_Enter" ) )
- {
- ecore_imf_context_reset( imfContext );
- }
- }
- }
- }
-
- // If the event wasn't handled then we should send a key event.
- if ( !eventHandled )
- {
- if ( keyEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- std::string keyName( keyEvent->keyname );
- std::string keyString( "" );
- int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname);
- keyCode = (keyCode == -1) ? 0 : keyCode;
- int modifier( keyEvent->modifiers );
- unsigned long time = keyEvent->timestamp;
- if (!strncmp(keyEvent->keyname, "Keycode-", 8))
- keyCode = atoi(keyEvent->keyname + 8);
-
- // Ensure key event string is not NULL as keys like SHIFT have a null string.
- if ( keyEvent->string )
- {
- keyString = keyEvent->string;
- }
-
- std::string deviceName;
- Device::Class::Type deviceClass;
- Device::Subclass::Type deviceSubclass;
-
- GetDeviceName( keyEvent, deviceName );
- GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass );
- GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass );
-
- DALI_LOG_INFO( gImfLogging, Debug::Verbose, "EVENT EcoreEventKeyDown - >>EcoreEventKeyDown deviceName(%s) deviceClass(%d)\n", deviceName.c_str(), deviceClass );
-
- Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Down, deviceName, deviceClass, deviceSubclass );
- handler->SendEvent( keyEvent );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a key up is received.
- */
- static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyUp\n" );
-
- EventHandler* handler( (EventHandler*)data );
- Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
- bool eventHandled( false );
-
- // Device keys like Menu, home, back button must skip ecore_imf_context_filter_event.
- if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
- {
- Ecore_IMF_Context* imfContext = NULL;
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
- }
-
- if ( imfContext )
- {
- // We're consuming key up event so we have to pass to IMF so that it can parse it as well.
- Ecore_IMF_Event_Key_Up ecoreKeyUpEvent;
- ecoreKeyUpEvent.keyname = keyEvent->keyname;
- ecoreKeyUpEvent.key = keyEvent->key;
- ecoreKeyUpEvent.string = keyEvent->string;
- ecoreKeyUpEvent.compose = keyEvent->compose;
- ecoreKeyUpEvent.timestamp = keyEvent->timestamp;
- ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
- ecoreKeyUpEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
- ecoreKeyUpEvent.dev_name = ecore_device_name_get( keyEvent->dev );
- ecoreKeyUpEvent.dev_class = static_cast<Ecore_IMF_Device_Class>( ecore_device_class_get( keyEvent->dev ) );
- ecoreKeyUpEvent.dev_subclass = static_cast<Ecore_IMF_Device_Subclass>( ecore_device_subclass_get( keyEvent->dev ) );
-
- eventHandled = ecore_imf_context_filter_event( imfContext,
- ECORE_IMF_EVENT_KEY_UP,
- (Ecore_IMF_Event *) &ecoreKeyUpEvent );
- }
- }
-
- // If the event wasn't handled then we should send a key event.
- if ( !eventHandled )
- {
- if ( keyEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- std::string keyName( keyEvent->keyname );
- std::string keyString( "" );
- int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname);
- keyCode = (keyCode == -1) ? 0 : keyCode;
- int modifier( keyEvent->modifiers );
- unsigned long time = keyEvent->timestamp;
- if (!strncmp(keyEvent->keyname, "Keycode-", 8))
- keyCode = atoi(keyEvent->keyname + 8);
-
- // Ensure key event string is not NULL as keys like SHIFT have a null string.
- if ( keyEvent->string )
- {
- keyString = keyEvent->string;
- }
-
- std::string deviceName;
- Device::Class::Type deviceClass;
- Device::Subclass::Type deviceSubclass;
-
- GetDeviceName( keyEvent, deviceName );
- GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass );
- GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass );
-
- Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Up, deviceName, deviceClass, deviceSubclass );
- handler->SendEvent( keyEvent );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Window Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when the window gains focus.
- */
- static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Focus_In* focusInEvent( (Ecore_Wl_Event_Focus_In*)event );
- EventHandler* handler( (EventHandler*)data );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusIn \n" );
-
- // If the window gains focus and we hid the keyboard then show it again.
- if ( focusInEvent->win == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventWindowFocusIn - >>WindowFocusGained \n" );
-
- if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
- {
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
- if( imfManagerImpl.RestoreAfterFocusLost() )
- {
- imfManagerImpl.Activate();
- }
- }
- }
- Dali::Clipboard clipboard = Clipboard::Get();
- clipboard.HideClipboard();
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window loses focus.
- */
- static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Focus_Out* focusOutEvent( (Ecore_Wl_Event_Focus_Out*)event );
- EventHandler* handler( (EventHandler*)data );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusOut \n" );
-
- // If the window loses focus then hide the keyboard.
- if ( focusOutEvent->win == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
- {
- if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
- {
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
- if( imfManagerImpl.RestoreAfterFocusLost() )
- {
- imfManagerImpl.Deactivate();
- }
- }
- }
-
- // Hiding clipboard event will be ignored once because window focus out event is always received on showing clipboard
- Dali::Clipboard clipboard = Clipboard::Get();
- if ( clipboard )
- {
- Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
- clipBoardImpl.HideClipboard(true);
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window is damaged.
- */
- static Eina_Bool EcoreEventWindowDamaged(void *data, int type, void *event)
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window properties are changed.
- * We are only interested in the font change.
- */
-
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Drag & Drop Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a dragged item enters our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndEnter( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndEnter\n" );
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved within our window.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndPosition( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndPosition\n" );
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item leaves our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndLeave( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndLeave\n" );
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the dragged item is dropped within our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndDrop( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndDrop\n" );
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved from our window and the target window has done processing it.
- * This is when items are dragged FROM our window.
- */
- static Eina_Bool EcoreEventDndFinished( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndFinished\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved from our window and the target window has sent us a status.
- * This is when items are dragged FROM our window.
- */
- static Eina_Bool EcoreEventDndStatus( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndStatus\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the client messages (i.e. the accessibility events) are received.
- */
- static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // ElDBus Accessibility Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Callback for Ecore ElDBus accessibility events.
- static void OnEcoreElDBusAccessibilityNotification( void *context EINA_UNUSED, const Eldbus_Message *message )
- {
- EventHandler* handler = static_cast< EventHandler* >( context );
- // Ignore any accessibility events when paused.
- if( handler->mPaused )
- {
- return;
- }
-
- if( !handler->mAccessibilityAdaptor )
- {
- DALI_LOG_ERROR( "Invalid accessibility adaptor\n" );
- return;
- }
-
- AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
- if( !accessibilityAdaptor )
- {
- DALI_LOG_ERROR( "Cannot access accessibility adaptor\n" );
- return;
- }
-
- int gestureValue;
- int xS, yS, xE, yE;
- int state; // 0 - begin, 1 - ongoing, 2 - ended, 3 - aborted
- int eventTime;
-
- // The string defines the arg-list's respective types.
- if( !eldbus_message_arguments_get( message, "iiiiiiu", &gestureValue, &xS, &yS, &xE, &yE, &state, &eventTime ) )
- {
- DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" );
- }
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Name: %d Args: %d,%d,%d,%d State: %d\n", gestureValue, xS, yS, xE, yE );
-
- // Create a touch point object.
- TouchPoint::State touchPointState( TouchPoint::Down );
- if( state == 0 )
- {
- touchPointState = TouchPoint::Down; // Mouse down.
- }
- else if( state == 1 )
- {
- touchPointState = TouchPoint::Motion; // Mouse move.
- }
- else if( state == 2 )
- {
- touchPointState = TouchPoint::Up; // Mouse up.
- }
- else
- {
- touchPointState = TouchPoint::Interrupted; // Error.
- }
-
- // Send touch event to accessibility adaptor.
- TouchPoint point( 0, touchPointState, (float)xS, (float)yS );
-
- // Perform actions based on received gestures.
- // Note: This is seperated from the reading so we can have other input readers without changing the below code.
- switch( gestureValue )
- {
- case 0: // OneFingerHover
- {
- // Focus, read out.
- accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
- break;
- }
- case 1: // TwoFingersHover
- {
- // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
- accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
- break;
- }
- case 2: // ThreeFingersHover
- {
- // Read from top item on screen continuously.
- accessibilityAdaptor->HandleActionReadFromTopEvent();
- break;
- }
- case 3: // OneFingerFlickLeft
- {
- // Move to previous item.
- accessibilityAdaptor->HandleActionReadPreviousEvent();
- break;
- }
- case 4: // OneFingerFlickRight
- {
- // Move to next item.
- accessibilityAdaptor->HandleActionReadNextEvent();
- break;
- }
- case 5: // OneFingerFlickUp
- {
- // Move to previous item.
- accessibilityAdaptor->HandleActionPreviousEvent();
- break;
- }
- case 6: // OneFingerFlickDown
- {
- // Move to next item.
- accessibilityAdaptor->HandleActionNextEvent();
- break;
- }
- case 7: // TwoFingersFlickUp
- {
- // Scroll up the list.
- accessibilityAdaptor->HandleActionScrollUpEvent();
- break;
- }
- case 8: // TwoFingersFlickDown
- {
- // Scroll down the list.
- accessibilityAdaptor->HandleActionScrollDownEvent();
- break;
- }
- case 9: // TwoFingersFlickLeft
- {
- // Scroll left to the previous page
- accessibilityAdaptor->HandleActionPageLeftEvent();
- break;
- }
- case 10: // TwoFingersFlickRight
- {
- // Scroll right to the next page
- accessibilityAdaptor->HandleActionPageRightEvent();
- break;
- }
- case 11: // ThreeFingersFlickLeft
- {
- // Not exist yet
- break;
- }
- case 12: // ThreeFingersFlickRight
- {
- // Not exist yet
- break;
- }
- case 13: // ThreeFingersFlickUp
- {
- // Not exist yet
- break;
- }
- case 14: // ThreeFingersFlickDown
- {
- // Not exist yet
- break;
- }
- case 15: // OneFingerSingleTap
- {
- // Focus, read out.
- accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
- break;
- }
- case 16: // OneFingerDoubleTap
- {
- // Activate selected item / active edit mode.
- accessibilityAdaptor->HandleActionActivateEvent();
- break;
- }
- case 17: // OneFingerTripleTap
- {
- // Zoom
- accessibilityAdaptor->HandleActionZoomEvent();
- break;
- }
- case 18: // TwoFingersSingleTap
- {
- // Pause/Resume current speech
- accessibilityAdaptor->HandleActionReadPauseResumeEvent();
- break;
- }
- case 19: // TwoFingersDoubleTap
- {
- // Start/Stop current action
- accessibilityAdaptor->HandleActionStartStopEvent();
- break;
- }
- case 20: // TwoFingersTripleTap
- {
- // Read information from indicator
- accessibilityAdaptor->HandleActionReadIndicatorInformationEvent();
- break;
- }
- case 21: // ThreeFingersSingleTap
- {
- // Read from top item on screen continuously.
- accessibilityAdaptor->HandleActionReadFromTopEvent();
- break;
- }
- case 22: // ThreeFingersDoubleTap
- {
- // Read from next item continuously.
- accessibilityAdaptor->HandleActionReadFromNextEvent();
- break;
- }
- case 23: // ThreeFingersTripleTap
- {
- // Not exist yet
- break;
- }
- case 24: // OneFingerFlickLeftReturn
- {
- // Scroll up to the previous page
- accessibilityAdaptor->HandleActionPageUpEvent();
- break;
- }
- case 25: // OneFingerFlickRightReturn
- {
- // Scroll down to the next page
- accessibilityAdaptor->HandleActionPageDownEvent();
- break;
- }
- case 26: // OneFingerFlickUpReturn
- {
- // Move to the first item on screen
- accessibilityAdaptor->HandleActionMoveToFirstEvent();
- break;
- }
- case 27: // OneFingerFlickDownReturn
- {
- // Move to the last item on screen
- accessibilityAdaptor->HandleActionMoveToLastEvent();
- break;
- }
- case 28: // TwoFingersFlickLeftReturn
- {
- // Not exist yet
- break;
- }
- case 29: // TwoFingersFlickRightReturn
- {
- // Not exist yet
- break;
- }
- case 30: // TwoFingersFlickUpReturn
- {
- // Not exist yet
- break;
- }
- case 31: // TwoFingersFlickDownReturn
- {
- // Not exist yet
- break;
- }
- case 32: // ThreeFingersFlickLeftReturn
- {
- // Not exist yet
- break;
- }
- case 33: // ThreeFingersFlickRightReturn
- {
- // Not exist yet
- break;
- }
- case 34: // ThreeFingersFlickUpReturn
- {
- // Not exist yet
- break;
- }
- case 35: // ThreeFingersFlickDownReturn
- {
- // Not exist yet
- break;
- }
- }
- }
-
- void EcoreElDBusInitialisation( void *handle )
- {
- Eldbus_Object *object;
- Eldbus_Proxy *manager;
-
- if( !( mSystemConnection = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SYSTEM) ) )
- {
- DALI_LOG_ERROR( "Unable to get system bus\n" );
- }
-
- object = eldbus_object_get( mSystemConnection, BUS, PATH );
- if( !object )
- {
- DALI_LOG_ERROR( "Getting object failed\n" );
- return;
- }
-
- manager = eldbus_proxy_get( object, INTERFACE );
- if( !manager )
- {
- DALI_LOG_ERROR( "Getting proxy failed\n" );
- return;
- }
-
- if( !eldbus_proxy_signal_handler_add( manager, "GestureDetected", OnEcoreElDBusAccessibilityNotification, handle ) )
- {
- DALI_LOG_ERROR( "No signal handler returned\n" );
- }
- }
-#endif // DALI_ELDBUS_AVAILABLE
-
- /**
- * Called when the source window notifies us the content in clipboard is selected.
- */
- static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionClear\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the source window sends us about the selected content.
- * For example, when dragged items are dragged INTO our window or when items are selected in the clipboard.
- */
- static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionNotify\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the source window notifies us the content in clipboard is selected.
- */
- static Eina_Bool EcoreEventDataSend( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDataSend\n" );
-
- Dali::Clipboard clipboard = Clipboard::Get();
- if ( clipboard )
- {
- Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
- clipBoardImpl.ExcuteBuffered( true, event );
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the source window sends us about the selected content.
- * For example, when item is selected in the clipboard.
- */
- static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDataReceive\n" );
-
- EventHandler* handler( (EventHandler*)data );
- Dali::Clipboard clipboard = Clipboard::Get();
- char *selectionData = NULL;
- if ( clipboard )
- {
- Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
- selectionData = clipBoardImpl.ExcuteBuffered( false, event );
- }
- if ( selectionData && handler->mClipboardEventNotifier )
- {
- ClipboardEventNotifier& clipboardEventNotifier( ClipboardEventNotifier::GetImplementation( handler->mClipboardEventNotifier ) );
- std::string content( selectionData, strlen(selectionData) );
-
- clipboardEventNotifier.SetContent( content );
- clipboardEventNotifier.EmitContentSelectedSignal();
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /*
- * Called when rotate event is recevied
- */
- static Eina_Bool EcoreEventRotate( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::Concise, "EcoreEventRotate\n" );
-
- EventHandler* handler( (EventHandler*)data );
- Ecore_Wl_Event_Window_Rotate* ev( (Ecore_Wl_Event_Window_Rotate*)event );
-
- if( ev->win != (unsigned int)ecore_wl_window_id_get( handler->mImpl->mWindow ) )
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
- RotationEvent rotationEvent;
- rotationEvent.angle = ev->angle;
- rotationEvent.winResize = 0;
-
- if( ev->angle == 0 || ev->angle == 180 )
- {
- rotationEvent.width = ev->w;
- rotationEvent.height = ev->h;
- }
- else
- {
- rotationEvent.width = ev->h;
- rotationEvent.height = ev->w;
- }
-
- handler->SendRotationPrepareEvent( rotationEvent );
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /*
- * Called when detent event is recevied
- */
- static Eina_Bool EcoreEventDetent( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDetent\n" );
- EventHandler* handler( (EventHandler*)data );
- Ecore_Event_Detent_Rotate *e((Ecore_Event_Detent_Rotate *)event);
- int direction = (e->direction == ECORE_DETENT_DIRECTION_CLOCKWISE) ? 1 : -1;
- int timeStamp = e->timestamp;
-
- WheelEvent wheelEvent( WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2(0.0f, 0.0f), direction, timeStamp );
- handler->SendWheelEvent( wheelEvent );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Font Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Called when a font name is changed.
- */
- static void VconfNotifyFontNameChanged( keynode_t* node, void* data )
- {
- EventHandler* handler = static_cast<EventHandler*>( data );
- handler->SendEvent( StyleChange::DEFAULT_FONT_CHANGE );
- }
-
- /**
- * Called when a font size is changed.
- */
- static void VconfNotifyFontSizeChanged( keynode_t* node, void* data )
- {
- EventHandler* handler = static_cast<EventHandler*>( data );
- handler->SendEvent( StyleChange::DEFAULT_FONT_SIZE_CHANGE );
- }
-
- void ConvertTouchPosition( Integration::Point& point )
- {
- Vector2 position = point.GetScreenPosition();
- Vector2 convertedPosition;
-
- switch( mRotationAngle )
- {
- case 90:
- {
- convertedPosition.x = mWindowWidth - position.y;
- convertedPosition.y = position.x;
- break;
- }
- case 180:
- {
- convertedPosition.x = mWindowWidth - position.x;
- convertedPosition.y = mWindowHeight - position.y;
- break;
- }
- case 270:
- {
- convertedPosition.x = position.y;
- convertedPosition.y = mWindowHeight - position.x;
- break;
- }
- default:
- {
- convertedPosition = position;
- break;
- }
- }
-
- point.SetScreenPosition( convertedPosition );
- }
-
- // Data
- EventHandler* mHandler;
- std::vector<Ecore_Event_Handler*> mEcoreEventHandler;
- Ecore_Wl_Window* mWindow;
- int mRotationAngle;
- int mWindowWidth;
- int mWindowHeight;
-#ifdef DALI_ELDBUS_AVAILABLE
- Eldbus_Connection* mSystemConnection;
-#endif // DALI_ELDBUS_AVAILABLE
-};
-
-EventHandler::EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector )
-: mCoreEventInterface( coreEventInterface ),
- mGestureManager( gestureManager ),
- mStyleMonitor( StyleMonitor::Get() ),
- mDamageObserver( damageObserver ),
- mRotationObserver( NULL ),
- mDragAndDropDetector( dndDetector ),
- mAccessibilityAdaptor( AccessibilityAdaptor::Get() ),
- mClipboardEventNotifier( ClipboardEventNotifier::Get() ),
- mClipboard( Clipboard::Get() ),
- mImpl( NULL ),
- mPaused( false )
-{
- Ecore_Wl_Window* window = 0;
-
- // this code only works with the Ecore RenderSurface so need to downcast
- ECore::WindowRenderSurface* ecoreSurface = dynamic_cast< ECore::WindowRenderSurface* >( surface );
- if( ecoreSurface )
- {
- window = ecoreSurface->GetWlWindow();
- }
-
- mImpl = new Impl(this, window);
-}
-
-EventHandler::~EventHandler()
-{
- if(mImpl)
- {
- delete mImpl;
- }
-
- mGestureManager.Stop();
-}
-
-void EventHandler::SendEvent(Integration::Point& point, unsigned long timeStamp)
-{
- if(timeStamp < 1)
- {
- timeStamp = GetCurrentMilliSeconds();
- }
-
- mImpl->ConvertTouchPosition( point );
-
- Integration::TouchEvent touchEvent;
- Integration::HoverEvent hoverEvent;
- Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent(point, timeStamp, touchEvent, hoverEvent);
- if(type != Integration::TouchEventCombiner::DispatchNone )
- {
- DALI_LOG_INFO(gTouchEventLogFilter, Debug::General, "%d: Device %d: Button state %d (%.2f, %.2f)\n", timeStamp, point.GetDeviceId(), point.GetState(), point.GetScreenPosition().x, point.GetScreenPosition().y);
-
- // First the touch and/or hover event & related gesture events are queued
- if(type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( touchEvent );
- mGestureManager.SendEvent(touchEvent);
- }
-
- if(type == Integration::TouchEventCombiner::DispatchHover || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( hoverEvent );
- }
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
- }
-}
-
-void EventHandler::SendEvent(Integration::KeyEvent& keyEvent)
-{
- Dali::PhysicalKeyboard physicalKeyboard = PhysicalKeyboard::Get();
- if ( physicalKeyboard )
- {
- if ( ! KeyLookup::IsDeviceButton( keyEvent.keyName.c_str() ) )
- {
- GetImplementation( physicalKeyboard ).KeyReceived( keyEvent.time > 1 );
- }
- }
-
- // Create send KeyEvent to Core.
- mCoreEventInterface.QueueCoreEvent( keyEvent );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendWheelEvent( WheelEvent& wheelEvent )
-{
- // Create WheelEvent and send to Core.
- Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >(wheelEvent.type), wheelEvent.direction, wheelEvent.modifiers, wheelEvent.point, wheelEvent.z, wheelEvent.timeStamp );
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendEvent( StyleChange::Type styleChange )
-{
- DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" );
- GetImplementation( mStyleMonitor ).StyleChanged(styleChange);
-}
-
-void EventHandler::SendEvent( const DamageArea& area )
-{
- mDamageObserver.OnDamaged( area );
-}
-
-void EventHandler::SendRotationPrepareEvent( const RotationEvent& event )
-{
- if( mRotationObserver != NULL )
- {
- mImpl->mRotationAngle = event.angle;
- mImpl->mWindowWidth = event.width;
- mImpl->mWindowHeight = event.height;
-
- mRotationObserver->OnRotationPrepare( event );
- mRotationObserver->OnRotationRequest();
- }
-}
-
-void EventHandler::SendRotationRequestEvent( )
-{
- // No need to separate event into prepare and request in wayland
-}
-
-void EventHandler::FeedTouchPoint( TouchPoint& point, int timeStamp)
-{
- Integration::Point convertedPoint( point );
- SendEvent(convertedPoint, timeStamp);
-}
-
-void EventHandler::FeedWheelEvent( WheelEvent& wheelEvent )
-{
- SendWheelEvent( wheelEvent );
-}
-
-void EventHandler::FeedKeyEvent( KeyEvent& event )
-{
- Integration::KeyEvent convertedEvent( event );
- SendEvent( convertedEvent );
-}
-
-void EventHandler::FeedEvent( Integration::Event& event )
-{
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Reset()
-{
- mCombiner.Reset();
-
- // Any touch listeners should be told of the interruption.
- Integration::TouchEvent event;
- Integration::Point point;
- point.SetState( PointState::INTERRUPTED );
- event.AddPoint( point );
-
- // First the touch event & related gesture events are queued
- mCoreEventInterface.QueueCoreEvent( event );
- mGestureManager.SendEvent( event );
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Pause()
-{
- mPaused = true;
- Reset();
-}
-
-void EventHandler::Resume()
-{
- mPaused = false;
- Reset();
-}
-
-void EventHandler::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
-{
- mDragAndDropDetector = detector;
-}
-
-void EventHandler::SetRotationObserver( RotationObserver* observer )
-{
- mRotationObserver = observer;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-# wayland
-
-adaptor_ecore_wayland_tizen_internal_src_files = \
- $(adaptor_ecore_wayland_dir)/clipboard-impl-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/display-connection-impl-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/event-handler-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/framework-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/imf-manager-impl-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/key-mapping-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/pixmap-render-surface-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/render-surface-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/virtual-keyboard-impl-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/window-impl-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/window-render-surface-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/key-grab-ecore-wl.cpp
-
-adaptor_ecore_wayland_tizen_common_internal_default_profile_src_files = \
- $(adaptor_ecore_wayland_dir)/render-surface-factory-ecore-wl.cpp \
- $(adaptor_ecore_wayland_dir)/system-settings-ecore-wl.cpp
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "framework.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-void Framework::InitThreads()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <imf-manager-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/events/key-event.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <input-method-devel.h>
-#include <adaptor.h>
-#include <locale-utils.h>
-#include <window-render-surface.h>
-#include <adaptor-impl.h>
-#include <singleton-service-impl.h>
-
-#define TOKEN_STRING(x) #x
-
-Ecore_IMF_Input_Panel_Layout panelLayoutMap[] =
-{
- ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL,
- ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER,
- ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL,
- ECORE_IMF_INPUT_PANEL_LAYOUT_URL,
- ECORE_IMF_INPUT_PANEL_LAYOUT_PHONENUMBER,
- ECORE_IMF_INPUT_PANEL_LAYOUT_IP,
- ECORE_IMF_INPUT_PANEL_LAYOUT_MONTH,
- ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBERONLY,
- ECORE_IMF_INPUT_PANEL_LAYOUT_HEX,
- ECORE_IMF_INPUT_PANEL_LAYOUT_TERMINAL,
- ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD,
- ECORE_IMF_INPUT_PANEL_LAYOUT_DATETIME,
- ECORE_IMF_INPUT_PANEL_LAYOUT_EMOTICON,
- ECORE_IMF_INPUT_PANEL_LAYOUT_VOICE
-};
-
-Ecore_IMF_Autocapital_Type autoCapitalMap[] =
-{
- ECORE_IMF_AUTOCAPITAL_TYPE_NONE,
- ECORE_IMF_AUTOCAPITAL_TYPE_WORD,
- ECORE_IMF_AUTOCAPITAL_TYPE_SENTENCE,
- ECORE_IMF_AUTOCAPITAL_TYPE_ALLCHARACTER,
-};
-
-Ecore_IMF_Input_Panel_Return_Key_Type returnKeyTypeMap[] =
-{
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND,
- ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN
-};
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
-#endif
-
-// Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
-size_t Utf8SequenceLength(const unsigned char leadByte)
-{
- size_t length = 0;
-
- if ((leadByte & 0x80) == 0 ) //ASCII character (lead bit zero)
- {
- length = 1;
- }
- else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
- {
- length = 2;
- }
- else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
- {
- length = 3;
- }
- else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
- {
- length = 4;
- }
-
- return length;
-}
-
-// Static function calls used by ecore 'c' style callback registration
-void Commit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->CommitReceived( data, imfContext, event_info );
- }
-}
-
-void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->PreEditChanged( data, imfContext, event_info );
- }
-}
-
-Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- return imfManager->RetrieveSurrounding( data, imfContext, text, cursorPosition );
- }
- else
- {
- return false;
- }
-}
-
-void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
-{
- if (!data)
- {
- return;
- }
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
- {
- imfManager->StatusChangedSignal().Emit( true );
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
- {
- imfManager->StatusChangedSignal().Emit( false );
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
- default:
- {
- // Do nothing
- break;
- }
- }
-}
-
-void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
-{
- if (!data)
- {
- return;
- }
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- // Emit the signal that the language has changed
- imfManager->LanguageChangedSignal().Emit( value );
-}
-
-void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
-{
- if (!data)
- {
- return;
- }
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- // Emit signal that the keyboard is resized
- imfManager->ResizedSignal().Emit( value );
-}
-
-void InputPanelKeyboardTypeChangedCallback( void *data, Ecore_IMF_Context *context, int value )
-{
- if( !data )
- {
- return;
- }
-
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE:
- {
- // Emit Signal that the keyboard type is changed to Software Keyboard
- imfManager->KeyboardTypeChangedSignal().Emit( Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD );
- break;
- }
- case ECORE_IMF_INPUT_PANEL_HW_KEYBOARD_MODE:
- {
- // Emit Signal that the keyboard type is changed to Hardware Keyboard
- imfManager->KeyboardTypeChangedSignal().Emit( Dali::ImfManager::KeyboardType::HARDWARE_KEYBOARD );
- break;
- }
- }
-}
-
-/**
- * Called when an IMF delete surrounding event is received.
- * Here we tell the application that it should delete a certain range.
- */
-void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->DeleteSurrounding( data, imfContext, event_info );
- }
-}
-
-/**
- * Called when the input method sends a private command.
- */
-void PrivateCommand( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->SendPrivateCommand( data, imfContext, event_info );
- }
-}
-
-BaseHandle Create()
-{
- return ImfManager::Get();
-}
-
-TypeRegistration IMF_MANAGER_TYPE( typeid(Dali::ImfManager), typeid(Dali::BaseHandle), Create );
-
-} // unnamed namespace
-
-bool ImfManager::IsAvailable()
-{
- bool available( false );
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- available = service.GetSingleton( typeid( Dali::ImfManager ) );
- }
-
- return available;
-}
-
-Dali::ImfManager ImfManager::Get()
-{
- Dali::ImfManager manager;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
- if( handle )
- {
- // If so, downcast the handle
- manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
- }
- else if ( Adaptor::IsAvailable() )
- {
- // Create instance and register singleton only if the adaptor is available
-
- Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
- Any nativeWindow = adaptorImpl.GetNativeWindowHandle();
-
- // The Ecore_Wl_Window needs to use the ImfManager.
- // Only when the render surface is window, we can get the Ecore_Wl_Window.
- Ecore_Wl_Window *ecoreWwin( AnyCast< Ecore_Wl_Window* >( nativeWindow ) );
- if (ecoreWwin)
- {
- // If we fail to get Ecore_Wl_Window, we can't use the ImfManager correctly.
- // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
- // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
-
- manager = Dali::ImfManager( new ImfManager( ecoreWwin ) );
- service.Register( typeid( manager ), manager );
- }
- else
- {
- DALI_LOG_ERROR("Failed to get native window handle\n");
- }
- }
- }
-
- return manager;
-}
-
-ImfManager::ImfManager( Ecore_Wl_Window *ecoreWlwin )
-: mIMFContext(),
- mIMFCursorPosition( 0 ),
- mSurroundingText(),
- mRestoreAfterFocusLost( false ),
- mIdleCallbackConnected( false )
-{
- ecore_imf_init();
- CreateContext( ecoreWlwin );
-
- ConnectCallbacks();
-}
-
-ImfManager::~ImfManager()
-{
- DisconnectCallbacks();
-
- DeleteContext();
- ecore_imf_shutdown();
-}
-
-
-void ImfManager::CreateContext( Ecore_Wl_Window *ecoreWlwin )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CreateContext\n" );
-
- const char *contextId = ecore_imf_context_default_id_get();
- if( contextId )
- {
- mIMFContext = ecore_imf_context_add( contextId );
-
- if( mIMFContext )
- {
- if( ecoreWlwin )
- {
- ecore_imf_context_client_window_set( mIMFContext,
- reinterpret_cast<void*>( ecore_wl_window_id_get(ecoreWlwin)) );
- }
- }
- else
- {
- DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
- }
- }
- else
- {
- DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
- }
-}
-
-void ImfManager::DeleteContext()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteContext\n" );
-
- if ( mIMFContext )
- {
- ecore_imf_context_del( mIMFContext );
- mIMFContext = NULL;
- }
-}
-
-// Callbacks for predicitive text support.
-void ImfManager::ConnectCallbacks()
-{
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ConnectCallbacks\n" );
-
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this );
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this );
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this );
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand, this );
-
- ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, this );
- ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, this );
- ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, this );
- ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback, this );
-
- ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this);
- }
-}
-
-void ImfManager::DisconnectCallbacks()
-{
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DisconnectCallbacks\n" );
-
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit );
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit );
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding );
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand );
-
- ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
- ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
- ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
- ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback );
-
- // We do not need to unset the retrieve surrounding callback.
- }
-}
-
-void ImfManager::Activate()
-{
- // Reset mIdleCallbackConnected
- mIdleCallbackConnected = false;
-
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Activate\n" );
-
- ecore_imf_context_focus_in( mIMFContext );
-
- // emit keyboard activated signal
- Dali::ImfManager handle( this );
- mActivatedSignal.Emit( handle );
- }
-}
-
-void ImfManager::Deactivate()
-{
- if( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Deactivate\n" );
-
- Reset();
- ecore_imf_context_focus_out( mIMFContext );
- }
-
- // Reset mIdleCallbackConnected
- mIdleCallbackConnected = false;
-}
-
-void ImfManager::Reset()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Reset\n" );
-
- if ( mIMFContext )
- {
- ecore_imf_context_reset( mIMFContext );
- }
-}
-
-Ecore_IMF_Context* ImfManager::GetContext()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetContext\n" );
-
- return mIMFContext;
-}
-
-bool ImfManager::RestoreAfterFocusLost() const
-{
- return mRestoreAfterFocusLost;
-}
-
-void ImfManager::SetRestoreAfterFocusLost( bool toggle )
-{
- mRestoreAfterFocusLost = toggle;
-}
-
-/**
- * Called when an IMF Pre-Edit changed event is received.
- * We are still predicting what the user is typing. The latest string is what the IMF module thinks
- * the user wants to type.
- */
-void ImfManager::PreEditChanged( void*, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged\n" );
-
- char* preEditString( NULL );
- int cursorPosition( 0 );
- Eina_List* attrs = NULL;
- Eina_List* l = NULL;
-
- Ecore_IMF_Preedit_Attr* attr;
-
- // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string.
- // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string.
- ecore_imf_context_preedit_string_with_attributes_get( imfContext, &preEditString, &attrs, &cursorPosition );
-
- if ( attrs )
- {
- // iterate through the list of attributes getting the type, start and end position.
- for ( l = attrs, (attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ))
- {
-#ifdef DALI_PROFILE_UBUNTU
- if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB3 ) // (Ecore_IMF)
-#else // DALI_PROFILE_UBUNTU
- if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB4 ) // (Ecore_IMF)
-#endif // DALI_PROFILE_UBUNTU
- {
- // check first byte so know how many bytes a character is represented by as keyboard returns cursor position in bytes. Which is different for some languages.
-
- size_t visualCharacterIndex = 0;
- size_t byteIndex = 0;
-
- // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
- const char leadByte = preEditString[byteIndex];
- while( leadByte != '\0' )
- {
- // attr->end_index is provided as a byte position not character and we need to know the character position.
- const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character.
- if ( byteIndex == attr->end_index )
- {
- cursorPosition = visualCharacterIndex;
- break;
- // end loop as found cursor position that matches byte position
- }
- else
- {
- byteIndex += currentSequenceLength; // jump to next character
- visualCharacterIndex++; // increment character count so we know our position for when we get a match
- }
-
- DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( preEditString ));
- }
- }
- }
- }
-
- if ( Dali::Adaptor::IsAvailable() )
- {
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::PREEDIT, preEditString, cursorPosition, 0 );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if ( callbackData.update )
- {
- SetCursorPosition( callbackData.cursorPosition );
- SetSurroundingText( callbackData.currentText );
-
- NotifyCursorPosition();
- }
-
- if ( callbackData.preeditResetRequired )
- {
- Reset();
- }
- }
- free( preEditString );
-}
-
-void ImfManager::CommitReceived( void*, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitReceived\n" );
-
- if ( Dali::Adaptor::IsAvailable() )
- {
- const std::string keyString( static_cast<char*>( event_info ) );
-
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::COMMIT, keyString, 0, 0 );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if( callbackData.update )
- {
- SetCursorPosition( callbackData.cursorPosition );
- SetSurroundingText( callbackData.currentText );
-
- NotifyCursorPosition();
- }
- }
-}
-
-/**
- * Called when an IMF retrieve surround event is received.
- * Here the IMF module wishes to know the string we are working with and where within the string the cursor is
- * We need to signal the application to tell us this information.
- */
-Eina_Bool ImfManager::RetrieveSurrounding( void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::RetrieveSurrounding\n" );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::GETSURROUNDING, std::string(), 0, 0 );
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
-
- if( callbackData.update )
- {
- if( text )
- {
- // The memory allocated by strdup() can be freed by ecore_imf_context_surrounding_get() internally.
- *text = strdup( callbackData.currentText.c_str() );
- }
-
- if( cursorPosition )
- {
- mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
- *cursorPosition = mIMFCursorPosition;
- }
- }
-
- return EINA_TRUE;
-}
-
-/**
- * Called when an IMF delete surrounding event is received.
- * Here we tell the application that it should delete a certain range.
- */
-void ImfManager::DeleteSurrounding( void* data, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurrounding\n" );
-
- if( Dali::Adaptor::IsAvailable() )
- {
- Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast<Ecore_IMF_Event_Delete_Surrounding*>( event_info );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::DELETESURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars );
- Dali::ImfManager handle( this );
- mEventSignal.Emit( handle, imfData );
- }
-}
-
-/**
- * Called when the input method sends a private command.
- */
-void ImfManager::SendPrivateCommand( void* data, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SendPrivateCommand\n" );
-
- if( Dali::Adaptor::IsAvailable() )
- {
- const char* privateCommandSendEvent = static_cast<const char*>( event_info );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::PRIVATECOMMAND, privateCommandSendEvent, 0, 0 );
- Dali::ImfManager handle( this );
- mEventSignal.Emit( handle, imfData );
- }
-}
-
-void ImfManager::NotifyCursorPosition()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition );
- }
-}
-
-void ImfManager::SetCursorPosition( unsigned int cursorPosition )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetCursorPosition\n" );
-
- mIMFCursorPosition = static_cast<int>( cursorPosition );
-}
-
-unsigned int ImfManager::GetCursorPosition() const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetCursorPosition\n" );
-
- return static_cast<unsigned int>( mIMFCursorPosition );
-}
-
-void ImfManager::SetSurroundingText( const std::string& text )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetSurroundingText\n" );
-
- mSurroundingText = text;
-}
-
-const std::string& ImfManager::GetSurroundingText() const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetSurroundingText\n" );
-
- return mSurroundingText;
-}
-
-void ImfManager::NotifyTextInputMultiLine( bool multiLine )
-{
- Ecore_IMF_Input_Hints currentHint = ecore_imf_context_input_hint_get(mIMFContext);
- ecore_imf_context_input_hint_set( mIMFContext,
- static_cast< Ecore_IMF_Input_Hints >( multiLine ?
- (currentHint | ECORE_IMF_INPUT_HINT_MULTILINE) :
- (currentHint & ~ECORE_IMF_INPUT_HINT_MULTILINE)));
-}
-
-Dali::ImfManager::TextDirection ImfManager::GetTextDirection()
-{
- Dali::ImfManager::TextDirection direction ( Dali::ImfManager::LeftToRight );
-
- if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
- {
- if ( mIMFContext )
- {
- char* locale( NULL );
- ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale );
-
- if ( locale )
- {
- direction = static_cast< Dali::ImfManager::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
- free( locale );
- }
- }
- }
- return direction;
-}
-
-Rect<int> ImfManager::GetInputMethodArea()
-{
- int xPos, yPos, width, height;
-
- width = height = xPos = yPos = 0;
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height );
- }
- else
- {
- DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
- // return 0 as real size unknown.
- }
-
- return Rect<int>(xPos,yPos,width,height);
-}
-
-void ImfManager::ApplyOptions( const InputMethodOptions& options )
-{
- using namespace Dali::InputMethod::Category;
-
- int index;
-
- if (mIMFContext == NULL)
- {
- DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n");
- return;
- }
-
- if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) )
- {
- ecore_imf_context_input_panel_layout_set( mIMFContext, panelLayoutMap[index] );
- }
- if ( mOptions.CompareAndSet(AUTO_CAPITALISE, options, index) )
- {
- ecore_imf_context_autocapital_type_set( mIMFContext, autoCapitalMap[index] );
- }
- if ( mOptions.CompareAndSet(ACTION_BUTTON_TITLE, options, index) )
- {
- ecore_imf_context_input_panel_return_key_type_set( mIMFContext, returnKeyTypeMap[index] );
- }
- if ( mOptions.CompareAndSet(VARIATION, options, index) )
- {
- ecore_imf_context_input_panel_layout_variation_set( mIMFContext, index );
- }
-}
-
-void ImfManager::SetInputPanelData( const std::string& data )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetInputPanelData\n" );
-
- if( mIMFContext )
- {
- int length = data.length();
- ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length );
- }
-}
-
-void ImfManager::GetInputPanelData( std::string& data )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelData\n" );
-
- if( mIMFContext )
- {
- int length = 4096; // The max length is 4096 bytes
- Dali::Vector< char > buffer;
- buffer.Resize( length );
- ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length );
- data = std::string( buffer.Begin(), buffer.End() );
- }
-}
-
-Dali::ImfManager::State ImfManager::GetInputPanelState()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelState\n" );
-
- if( mIMFContext )
- {
- int value;
- value = ecore_imf_context_input_panel_state_get( mIMFContext );
-
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
- {
- return Dali::ImfManager::SHOW;
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
- {
- return Dali::ImfManager::HIDE;
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
- {
- return Dali::ImfManager::WILL_SHOW;
- break;
- }
-
- default:
- {
- return Dali::ImfManager::DEFAULT;
- }
- }
- }
- return Dali::ImfManager::DEFAULT;
-}
-
-void ImfManager::SetReturnKeyState( bool visible )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetReturnKeyState\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible );
- }
-}
-
-void ImfManager::AutoEnableInputPanel( bool enabled )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::AutoEnableInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled );
- }
-}
-
-void ImfManager::ShowInputPanel()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ShowInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_show( mIMFContext );
- }
-}
-
-void ImfManager::HideInputPanel()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::HideInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_hide( mIMFContext );
- }
-}
-
-Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetKeyboardType\n" );
-
-#ifdef OVER_TIZEN_VERSION_4
- if( mIMFContext )
- {
- int value;
- value = ecore_imf_context_keyboard_mode_get( mIMFContext );
-
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE:
- {
- return Dali::ImfManager::SOFTWARE_KEYBOARD;
- break;
- }
- case ECORE_IMF_INPUT_PANEL_HW_KEYBOARD_MODE:
- {
- return Dali::ImfManager::HARDWARE_KEYBOARD;
- break;
- }
- }
- }
-#endif // OVER_TIZEN_VERSION_4
- return Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD;
-}
-
-std::string ImfManager::GetInputPanelLocale()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelLocale\n" );
-
- std::string locale = "";
-
- if( mIMFContext )
- {
- char* value = NULL;
- ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value );
-
- if( value )
- {
- std::string valueCopy( value );
- locale = valueCopy;
-
- // The locale string retrieved must be freed with free().
- free( value );
- }
- }
- return locale;
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-#ifndef __DALI_INTERNAL_IMF_MANAGER_H
-#define __DALI_INTERNAL_IMF_MANAGER_H
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_IMF.h>
-#include <Ecore.h>
-#include <Ecore_Wayland.h>
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/object/base-object.h>
-#include <dali/integration-api/events/key-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <imf-manager.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class DALI_IMPORT_API ImfManager : public Dali::BaseObject
-{
-public:
- typedef Dali::ImfManager::ImfManagerSignalType ImfManagerSignalType;
- typedef Dali::ImfManager::ImfEventSignalType ImfEventSignalType;
- typedef Dali::ImfManager::StatusSignalType ImfStatusSignalType;
- typedef Dali::ImfManager::VoidSignalType ImfVoidSignalType;
- typedef Dali::ImfManager::KeyboardTypeSignalType ImfKeyboardTypeSignalType;
- typedef Dali::ImfManager::KeyboardResizedSignalType KeyboardResizedSignalType;
- typedef Dali::ImfManager::LanguageChangedSignalType LanguageChangedSignalType;
-
-public:
-
- /**
- * Check whether the ImfManager is available.
- * @return true if available, false otherwise
- */
- static bool IsAvailable();
-
- /**
- * Get the IMF manager instance, it creates the instance if it has not already been created.
- * Internally, a check should be made using IsAvailable() before this is called as we do not want
- * to create an instance if not needed by applications.
- * @see IsAvailable()
- */
- static Dali::ImfManager Get();
-
- /**
- * Connect Callbacks required for IMF.
- * If you don't connect imf callbacks, you can't get the key events.
- * The events are PreeditChanged, Commit, DeleteSurrounding and PrivateCommand.
- */
- void ConnectCallbacks();
-
- /**
- * Disconnect Callbacks attached to imf context.
- */
- void DisconnectCallbacks();
-
- /**
- * @copydoc Dali::ImfManager::Activate()
- */
- void Activate();
-
- /**
- * @copydoc Dali::ImfManager::Deactivate()
- */
- void Deactivate();
-
- /**
- * @copydoc Dali::ImfManager::Reset()
- */
- void Reset();
-
- /**
- * @copydoc Dali::ImfManager::GetContext()
- */
- Ecore_IMF_Context* GetContext();
-
- /**
- * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
- */
- bool RestoreAfterFocusLost() const;
-
- /**
- * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
- */
- void SetRestoreAfterFocusLost( bool toggle );
-
- /**
- * @copydoc Dali::ImfManager::PreEditChanged()
- */
- void PreEditChanged( void *data, Ecore_IMF_Context *imfContext, void *event_info );
-
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- void CommitReceived( void *data, Ecore_IMF_Context *imfContext, void *event_info );
-
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- Eina_Bool RetrieveSurrounding( void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition );
-
- /**
- * @copydoc Dali::ImfManager::DeleteSurrounding()
- */
- void DeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info );
-
- /**
- * @copydoc Dali::ImfManager::SendPrivateCommand()
- */
- void SendPrivateCommand( void* data, Ecore_IMF_Context* imfContext, void* event_info );
-
- // Cursor related
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- void NotifyCursorPosition();
-
- /**
- * @copydoc Dali::ImfManager::SetCursorPosition()
- */
- void SetCursorPosition( unsigned int cursorPosition );
-
- /**
- * @copydoc Dali::ImfManager::GetCursorPosition()
- */
- unsigned int GetCursorPosition() const;
-
- /**
- * @copydoc Dali::ImfManager::SetSurroundingText()
- */
- void SetSurroundingText( const std::string& text );
-
- /**
- * @copydoc Dali::ImfManager::GetSurroundingText()
- */
- const std::string& GetSurroundingText() const;
-
- /**
- * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
- */
- void NotifyTextInputMultiLine( bool multiLine );
-
- /**
- * @copydoc Dali::ImfManager::GetTextDirection()
- */
- Dali::ImfManager::TextDirection GetTextDirection();
-
- /**
- * @copydoc Dali::ImfManager::GetInputMethodArea()
- */
- Dali::Rect<int> GetInputMethodArea();
-
- /**
- * @copydoc Dali::ImfManager::ApplyOptions()
- */
- void ApplyOptions( const InputMethodOptions& options );
-
- /**
- * @copydoc Dali::ImfManager::SetInputPanelData()
- */
- void SetInputPanelData( const std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelData()
- */
- void GetInputPanelData( std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelState()
- */
- Dali::ImfManager::State GetInputPanelState();
-
- /**
- * @copydoc Dali::ImfManager::SetReturnKeyState()
- */
- void SetReturnKeyState( bool visible );
-
- /**
- * @copydoc Dali::ImfManager::AutoEnableInputPanel()
- */
- void AutoEnableInputPanel( bool enabled );
-
- /**
- * @copydoc Dali::ImfManager::ShowInputPanel()
- */
- void ShowInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::HideInputPanel()
- */
- void HideInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::GetKeyboardType()
- */
- Dali::ImfManager::KeyboardType GetKeyboardType();
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelLocale()
- */
- std::string GetInputPanelLocale();
-
-public: // Signals
-
- /**
- * @copydoc Dali::ImfManager::ActivatedSignal()
- */
- ImfManagerSignalType& ActivatedSignal() { return mActivatedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::EventReceivedSignal()
- */
- ImfEventSignalType& EventReceivedSignal() { return mEventSignal; }
-
- /**
- * @copydoc Dali::ImfManager::StatusChangedSignal()
- */
- ImfStatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; }
-
- /**
- * @copydoc Dali::ImfManager::ResizedSignal()
- */
- KeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; }
-
- /**
- * @copydoc Dali::ImfManager::LanguageChangedSignal()
- */
- LanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::KeyboardTypeChangedSignal()
- */
- ImfKeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; }
-
-protected:
-
- /**
- * Destructor.
- */
- virtual ~ImfManager();
-
-private:
- /**
- * Context created the first time and kept until deleted.
- * @param[in] ecoreWlwin, The window is created by application.
- */
- void CreateContext( Ecore_Wl_Window *ecoreWlwin );
-
- /**
- * @copydoc Dali::ImfManager::DeleteContext()
- */
- void DeleteContext();
-
-private:
- // Undefined
- ImfManager( Ecore_Wl_Window *ecoreWlwin );
- ImfManager( const ImfManager& );
- ImfManager& operator=( ImfManager& );
-
-private:
- Ecore_IMF_Context* mIMFContext;
- int mIMFCursorPosition;
- std::string mSurroundingText;
-
- bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
- bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected.
-
- std::vector<Dali::Integration::KeyEvent> mKeyEvents; ///< Stores key events to be sent from idle call-back.
- InputMethodOptions mOptions;
-
- ImfManagerSignalType mActivatedSignal;
- ImfEventSignalType mEventSignal;
- ImfStatusSignalType mKeyboardStatusSignal;
- KeyboardResizedSignalType mKeyboardResizeSignal;
- LanguageChangedSignalType mKeyboardLanguageChangedSignal;
- ImfKeyboardTypeSignalType mKeyboardTypeChangedSignal;
-
-public:
-
-inline static Internal::Adaptor::ImfManager& GetImplementation(Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<Internal::Adaptor::ImfManager&>(handle);
-}
-
-inline static const Internal::Adaptor::ImfManager& GetImplementation(const Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- const BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::ImfManager&>(handle);
-}
-
-};
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_IMF_MANAGER_H
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <key-grab.h>
-
-// EXTERNAL INCLUDES
-#include <Ecore_Wayland.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <window.h>
-#include <key-impl.h>
-
-#include <iostream>
-#include <string.h>
-
-using namespace std;
-
-namespace Dali
-{
-
-namespace KeyGrab
-{
-
-bool GrabKeyTopmost( Window window, Dali::KEY daliKey )
-{
- return GrabKey( window, daliKey, TOPMOST);
-}
-
-
-bool UngrabKeyTopmost( Window window, Dali::KEY daliKey )
-{
- return UngrabKey( window, daliKey );
-}
-
-
-bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode )
-{
- Ecore_Wl_Window_Keygrab_Mode wlGrabMode;
- if( grabMode == TOPMOST )
- {
- wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_TOPMOST;
- }
- else if( grabMode == SHARED )
- {
- wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_SHARED;
- }
- else if( grabMode == OVERRIDE_EXCLUSIVE )
- {
- wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_OVERRIDE_EXCLUSIVE;
- }
- else if( grabMode == EXCLUSIVE )
- {
- wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_EXCLUSIVE;
- }
- else
- {
- return false;
- }
-
- return ecore_wl_window_keygrab_set( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ),
- Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ),
- 0, 0, 0, wlGrabMode );
-}
-
-
-bool UngrabKey( Window window, Dali::KEY daliKey )
-{
- return ecore_wl_window_keygrab_unset( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ),
- Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ),
- 0, 0 );
-}
-
-
-bool GrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, const Dali::Vector<KeyGrabMode>& grabModeVector, Dali::Vector<bool>& returnVector)
-{
- const Dali::Vector<bool>::SizeType returnCount = returnVector.Count();
- const Dali::Vector<Dali::KEY>::SizeType keyCount = daliKeyVector.Count();
- const Dali::Vector<KeyGrabMode>::SizeType keyGrabModeCount = grabModeVector.Count();
-
- if( keyCount != keyGrabModeCount || keyCount != returnCount || keyCount == 0 )
- {
- return false;
- }
-
- eina_init();
-
- Eina_List* keyList = NULL;
- {
- for( Dali::Vector<float>::SizeType index = 0; index < keyCount; ++index )
- {
- Ecore_Wl_Window_Keygrab_Info info;
- info.key = const_cast<char*>(Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKeyVector[index] ));
-
- switch( grabModeVector[index] )
- {
- case TOPMOST:
- {
- info.mode = ECORE_WL_WINDOW_KEYGRAB_TOPMOST;
- break;
- }
- case SHARED:
- {
- info.mode = ECORE_WL_WINDOW_KEYGRAB_SHARED;
- break;
- }
- case OVERRIDE_EXCLUSIVE:
- {
- info.mode = ECORE_WL_WINDOW_KEYGRAB_OVERRIDE_EXCLUSIVE;
- break;
- }
- case EXCLUSIVE:
- {
- info.mode = ECORE_WL_WINDOW_KEYGRAB_EXCLUSIVE;
- break;
- }
- default:
- {
- info.mode = ECORE_WL_WINDOW_KEYGRAB_UNKNOWN;
- break;
- }
- }
-
- keyList = eina_list_append( keyList, &info );
- }
- }
-
- Eina_List* grabList = ecore_wl_window_keygrab_list_set( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ), keyList );
-
- returnVector.Resize( keyCount, true );
-
- Eina_List* l = NULL;
- Eina_List* m = NULL;
- void *listData = NULL;
- void *data = NULL;
- if( grabList != NULL )
- {
- EINA_LIST_FOREACH( grabList, m, data )
- {
- Dali::Vector<float>::SizeType index = 0;
- EINA_LIST_FOREACH( keyList, l, listData )
- {
- if((static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData))->key == NULL)
- {
- DALI_LOG_ERROR("input key list has null data!");
- break;
- }
-
- if( strcmp( static_cast<char*>(data), static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData)->key ) == 0 )
- {
- returnVector[index] = false;
- }
- ++index;
- }
- }
- }
-
- eina_list_free( keyList );
- eina_list_free( grabList );
- eina_shutdown();
-
- return true;
-}
-
-bool UngrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, Dali::Vector<bool>& returnVector)
-{
- const Dali::Vector<bool>::SizeType returnCount = returnVector.Count();
- const Dali::Vector<Dali::KEY>::SizeType keyCount = daliKeyVector.Count();
-
- if( keyCount != returnCount ||keyCount == 0 )
- {
- return false;
- }
-
- eina_init();
-
- Eina_List* keyList = NULL;
- {
- for( Dali::Vector<float>::SizeType index = 0; index < keyCount; ++index )
- {
- Ecore_Wl_Window_Keygrab_Info info;
- info.key = const_cast<char*>(Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKeyVector[index] ));
- keyList = eina_list_append( keyList, &info );
- }
- }
-
- Eina_List* ungrabList = ecore_wl_window_keygrab_list_unset( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ), keyList );
-
- returnVector.Resize( keyCount, true );
-
- Eina_List* l = NULL;
- Eina_List* m = NULL;
- void *listData = NULL;
- void *data = NULL;
-
- if( ungrabList != NULL )
- {
- EINA_LIST_FOREACH( ungrabList, m, data )
- {
- Dali::Vector<float>::SizeType index = 0;
- EINA_LIST_FOREACH( keyList, l, listData )
- {
- if( strcmp( static_cast<char*>(data), static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData)->key ) == 0 )
- {
- returnVector[index] = false;
- }
- ++index;
- }
- }
- }
-
- eina_list_free( keyList );
- eina_list_free( ungrabList );
- eina_shutdown();
-
- return true;
-}
-
-} // namespace KeyGrab
-
-} // namespace Dali
-
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "key-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-// matches a DALI_KEY enum, to a key name
-KeyLookup KeyLookupTable[]=
-{
- // more than one key name can be assigned to a single dali-key code
- // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
-
- { "Escape", DALI_KEY_ESCAPE , false },
- { "Menu", DALI_KEY_MENU, false },
-
- // Now literal strings are used as key names instead of defined symbols in utilX,
- // since these definition in utilX.h is deprecated
- { "XF86Camera", DALI_KEY_CAMERA, false },
- { "XF86Camera_Full", DALI_KEY_CONFIG, false },
- { "XF86PowerOff", DALI_KEY_POWER, true },
- { "XF86Standby", DALI_KEY_PAUSE, false },
- { "Cancel", DALI_KEY_CANCEL, false },
- { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
- { "XF86AudioStop", DALI_KEY_STOP_CD, false },
- { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
- { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
- { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
- { "XF86AudioRewind", DALI_KEY_REWIND, false },
- { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
- { "XF86AudioMedia", DALI_KEY_MEDIA, false },
- { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
- { "XF86AudioMute", DALI_KEY_MUTE, false },
- { "XF86Menu", DALI_KEY_MENU, true },
- { "XF86Home", DALI_KEY_HOME, true },
- { "XF86Back", DALI_KEY_BACK, true },
- { "XF86Send", DALI_KEY_MENU, true },
- { "XF86Phone", DALI_KEY_HOME, true },
- { "XF86Stop", DALI_KEY_BACK, true },
- { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
- { "XF86WWW", DALI_KEY_WEBPAGE, false },
- { "XF86Mail", DALI_KEY_MAIL, false },
- { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
- { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
- { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
- { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
- { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
- { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
- { "XF86Apps", DALI_KEY_APPS, false },
- { "XF86Search", DALI_KEY_SEARCH, false },
- { "XF86Voice", DALI_KEY_VOICE, false },
- { "Hangul", DALI_KEY_LANGUAGE, false },
- { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
- { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
-
- { "BackSpace", DALI_KEY_BACKSPACE, false },
- { "Left", DALI_KEY_CURSOR_LEFT, false },
- { "Right", DALI_KEY_CURSOR_RIGHT, false },
- { "left", DALI_KEY_CURSOR_LEFT, false }, // To be removed after the key name is fixed in the platform
- { "right", DALI_KEY_CURSOR_RIGHT, false }, // To be removed after the key name is fixed in the platform
- { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
- { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
- { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
- { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
- { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
- { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
-};
-
-const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pixmap-render-surface.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-#include <base/display-connection.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gRenderSurfaceLogFilter;
-#endif
-
-namespace ECore
-{
-
-PixmapRenderSurface::PixmapRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: EcoreWlRenderSurface( positionSize, surface, name, isTransparent )
-{
- Init( surface );
-}
-
-PixmapRenderSurface::~PixmapRenderSurface()
-{
- // release the surface if we own one
- if( mOwnSurface )
- {
- //TODO: if we did create the pixmap, delete the pixmap
- }
-}
-
-Ecore_Wl_Window* PixmapRenderSurface::GetDrawable()
-{
- return NULL;
-}
-
-Any PixmapRenderSurface::GetSurface()
-{
- return Any( NULL );
-}
-
-void PixmapRenderSurface::InitializeEgl( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- eglImpl.ChooseConfig(false, mColorDepth);
-}
-
-void PixmapRenderSurface::CreateEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- // create the EGL surface
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- // FIXME
-}
-
-void PixmapRenderSurface::DestroyEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.DestroySurface();
-}
-
-bool PixmapRenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- // a new surface for the new pixmap
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- // FIXME
- return false;
-}
-
-void PixmapRenderSurface::StartRender()
-{
- // FIXME
-}
-
-bool PixmapRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
-{
- // nothing to do for pixmaps
- return true;
-}
-
-void PixmapRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- // flush gl instruction queue
- glAbstraction.Flush();
-
- // create damage for client applications which wish to know the update timing
- if( mRenderNotification )
- {
- // use notification trigger
- // Tell the event-thread to render the pixmap
- mRenderNotification->Trigger();
- }
- else
- {
- // FIXME
- }
-
- // Do render synchronisation
- // AcquireLock( replacingSurface ? SYNC_MODE_NONE : SYNC_MODE_WAIT );
-}
-
-void PixmapRenderSurface::StopRender()
-{
- // FIXME
-}
-
-void PixmapRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
-{
- // Nothing to do
-}
-
-void PixmapRenderSurface::CreateWlRenderable()
-{
- // check we're creating one with a valid size
- DALI_ASSERT_ALWAYS( mPositionSize.width > 0 && mPositionSize.height > 0 && "Pixmap size is invalid" );
-
- // FIXME
-}
-
-void PixmapRenderSurface::UseExistingRenderable( unsigned int surfaceId )
-{
- // FIXME
-}
-
-void PixmapRenderSurface::SetSyncMode( SyncMode syncMode )
-{
- // FIXME
-}
-
-void PixmapRenderSurface::AcquireLock()
-{
- // FIXME
-}
-
-void PixmapRenderSurface::ReleaseLock()
-{
- // FIXME
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-wl-render-surface.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_ECORE_WL_RENDER_SURFACE");
-#endif
-
-namespace ECore
-{
-
-EcoreWlRenderSurface::EcoreWlRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: mPositionSize( positionSize ),
- mTitle( name ),
- mRenderNotification( NULL ),
- mColorDepth( isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24 ),
- mOwnSurface( false )
-{
-}
-
-void EcoreWlRenderSurface::Init( Any surface )
-{
- // see if there is a surface in Any surface
- unsigned int surfaceId = GetSurfaceId( surface );
-
- // if the surface is empty, create a new one.
- if ( surfaceId == 0 )
- {
- // we own the surface about to created
- ecore_wl_init(NULL);
- mOwnSurface = true;
- CreateWlRenderable();
- }
- else
- {
- // XLib should already be initialized so no point in calling XInitThreads
- UseExistingRenderable( surfaceId );
- }
-
-#ifdef DEBUG_ENABLED
- // prints out 'INFO: DALI: new EcoreWlRenderSurface, created display xx, used existing surface xx
- // we can not use LOG_INFO because the surface can be created before Dali Core is created.
- // TODO: Overy tizen 3.0, we don't use X anymore. Change this for Tizen 3.0
- /*
- printf( "INFO: DALI: new EcoreWlRenderSurface, %s %s surface %X \n",
- mOwnSurface?"created":"used existing",
- Dali::RenderSurface::PIXMAP==mType?" pixmap" :"window",
- AnyCast<Ecore_X_Drawable>( GetSurface() ) );
- */
-#endif
-}
-
-EcoreWlRenderSurface::~EcoreWlRenderSurface()
-{
- if( mOwnSurface )
- {
- ecore_wl_shutdown();
- }
-}
-
-void EcoreWlRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification)
-{
- mRenderNotification = renderNotification;
-}
-
-Ecore_Wl_Window* EcoreWlRenderSurface::GetWlWindow()
-{
- return 0;
-}
-
-Ecore_Wl_Window* EcoreWlRenderSurface::GetDrawable()
-{
- return 0;
-}
-
-PositionSize EcoreWlRenderSurface::GetPositionSize() const
-{
- return mPositionSize;
-}
-
-void EcoreWlRenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
- // nothing to do in base class
-}
-
-void EcoreWlRenderSurface::SetViewMode( ViewMode viewMode )
-{
-}
-
-unsigned int EcoreWlRenderSurface::GetSurfaceId( Any surface ) const
-{
- unsigned int surfaceId = 0;
-
- if ( surface.Empty() == false )
- {
- // check we have a valid type
- DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (Ecore_Wl_Window *) ) )
- && "Surface type is invalid" );
-
- surfaceId = AnyCast<unsigned int>( surface );
- }
- return surfaceId;
-}
-
-RenderSurface::Type EcoreWlRenderSurface::GetSurfaceType()
-{
- return RenderSurface::ECORE_RENDER_SURFACE;
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <ecore-wl-render-surface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace ECore
-{
-
-DALI_EXPORT_API RenderSurface* CreatePixmapSurface(
- PositionSize positionSize,
- Any surface,
- Any display,
- const std::string& name,
- bool isTransparent )
-{
- return NULL;
-}
-
-} // namespace ECore
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-
-
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_ECORE_WL_RENDER_SURFACE_FACTORY_H__
-#define __DALI_INTERNAL_ADAPTOR_ECORE_WL_RENDER_SURFACE_FACTORY_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/math/rect.h>
-#include <dali/public-api/common/dali-common.h>
-
-// INTERNAL INCLUDES
-#include <native-buffer-pool.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace ECore
-{
-
-class RenderSurface;
-
-/**
- * Surface factory function for pixmap
- * A pixmap surface is created.
- *
- * @param [in] type the type of surface to create
- * @param [in] positionSize the position and size of the surface to create
- * @param [in] display Wayland Pixmap to use, or null for default.
- * @param [in] display Wayland Display to use, or null for default.
- * @param [in] name Name of surface passed in
- * @param [in] isTransparent Whether the surface has an alpha channel
- */
-RenderSurface* CreatePixmapSurface(
- PositionSize positionSize,
- Any surface,
- Any display,
- const std::string& name,
- bool isTransparent );
-
-} // namespace ECore
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_ECORE_X_RENDER_SURFACE_FACTORY_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include "system-settings.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-int GetElmAccessActionOver()
-{
- return 0;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "virtual-keyboard-impl.h"
-
-// EXTERNAL INCLUDES
-#include <Ecore.h>
-#include <Ecore_Wayland.h>
-#include <algorithm>
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor.h>
-#include <locale-utils.h>
-#include <imf-manager-impl.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace VirtualKeyboard
-{
-
-Dali::InputMethod::ActionButton gActionButtonFunction = Dali::InputMethod::ACTION_DEFAULT;
-
-Ecore_IMF_Input_Panel_Return_Key_Type actionButtonMapping(Dali::InputMethod::ActionButton actionButton )
-{
- switch( actionButton )
- {
- case InputMethod::ACTION_DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE;
- case InputMethod::ACTION_GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO;
- case InputMethod::ACTION_JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN;
- case InputMethod::ACTION_LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN;
- case InputMethod::ACTION_NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT;
- case InputMethod::ACTION_PREVIOUS: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH;
- case InputMethod::ACTION_SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND;
- case InputMethod::ACTION_SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_UNSPECIFIED: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_NONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- }
-}
-
-void RotateTo(int angle)
-{
-}
-
-void SetReturnKeyType( const InputMethod::ActionButton type )
-{
- Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when setting values
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if( imfContext )
- {
- gActionButtonFunction = type;
- ecore_imf_context_input_panel_return_key_type_set( imfContext, actionButtonMapping( type ) );
- }
-}
-
-Dali::InputMethod::ActionButton GetReturnKeyType()
-{
- return gActionButtonFunction;
-}
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <window-impl.h>
-
-// EXTERNAL HEADERS
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Ecore_Wayland.h>
-#include <tizen-extension-client-protocol.h>
-
-#include <dali/integration-api/core.h>
-#include <dali/integration-api/system-overlay.h>
-#include <dali/public-api/render-tasks/render-task.h>
-#include <dali/public-api/render-tasks/render-task-list.h>
-#include <orientation.h>
-
-// INTERNAL HEADERS
-#include <window-render-surface.h>
-#include <drag-and-drop-detector-impl.h>
-#include <ecore-indicator-impl.h>
-#include <window-visibility-observer.h>
-#include <orientation-impl.h>
-
-namespace
-{
-
-const float INDICATOR_ANIMATION_DURATION( 0.18f ); // 180 milli seconds
-const float INDICATOR_SHOW_Y_POSITION( 0.0f );
-const float INDICATOR_HIDE_Y_POSITION( -52.0f );
-
-const uint32_t MAX_TIZEN_CLIENT_VERSION = 7;
-
-}
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW");
-#endif
-
-/**
- * TODO: Abstract Window class out and move this into a window implementation for Ecore
- */
-struct Window::EventHandler
-{
- /**
- * Constructor
- * @param[in] window A pointer to the window class.
- */
- EventHandler( Window* window )
- : mWindow( window ),
- mEcoreEventHandler(),
- mEcoreWindow( 0 ),
- mDisplay( NULL ),
- mEventQueue( NULL ),
- mTizenPolicy( NULL ),
- mTizenDisplayPolicy( NULL ),
- mNotificationLevel( -1 ),
- mNotificationChangeState( 0 ),
- mNotificationLevelChangeDone( true ),
- mScreenOffMode( 0 ),
- mScreenOffModeChangeState( 0 ),
- mScreenOffModeChangeDone( true ),
- mBrightness( 0 ),
- mBrightnessChangeState( 0 ),
- mBrightnessChangeDone( true )
- {
- // store ecore window handle
- ECore::WindowRenderSurface* wlWindow( dynamic_cast< ECore::WindowRenderSurface * >( mWindow->mSurface ) );
- if( wlWindow )
- {
- mEcoreWindow = wlWindow->GetWlWindow();
- }
- DALI_ASSERT_ALWAYS( mEcoreWindow != 0 && "There is no ecore Wl window");
-
- if( mWindow->mEcoreEventHander )
- {
- mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this ) );
- mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this ) );
- mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this ) );
- mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this) );
- mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this) );
- }
-
- mDisplay = ecore_wl_display_get();
-
- if( mDisplay )
- {
- wl_display* displayWrapper = static_cast< wl_display* >( wl_proxy_create_wrapper( mDisplay ) );
- if( displayWrapper )
- {
- mEventQueue = wl_display_create_queue( mDisplay );
- if( mEventQueue )
- {
- wl_proxy_set_queue( reinterpret_cast< wl_proxy* >( displayWrapper ), mEventQueue );
-
- wl_registry* registry = wl_display_get_registry( displayWrapper );
- wl_registry_add_listener( registry, &mRegistryListener, this );
- }
-
- wl_proxy_wrapper_destroy( displayWrapper );
- }
- }
- }
-
- /**
- * Destructor
- */
- ~EventHandler()
- {
- for( Dali::Vector< Ecore_Event_Handler* >::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter )
- {
- ecore_event_handler_del( *iter );
- }
- mEcoreEventHandler.Clear();
-
- if( mEventQueue )
- {
- wl_event_queue_destroy( mEventQueue );
- }
- }
-
- // Static methods
-
- /// Called when the window iconify state is changed.
- static Eina_Bool EcoreEventWindowIconifyStateChanged( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Window_Iconify_State_Change* iconifyChangedEvent( static_cast< Ecore_Wl_Event_Window_Iconify_State_Change* >( event ) );
- EventHandler* handler( static_cast< EventHandler* >( data ) );
- Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
-
- if ( handler && handler->mWindow )
- {
- WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
- if ( observer && ( iconifyChangedEvent->win == static_cast< unsigned int> ( ecore_wl_window_id_get( handler->mEcoreWindow ) ) ) )
- {
- if( iconifyChangedEvent->iconified == EINA_TRUE )
- {
- handler->mWindow->mIconified = true;
- if( handler->mWindow->mVisible )
- {
- observer->OnWindowHidden();
- }
- DALI_LOG_RELEASE_INFO( "Window (%p) Iconified\n", handler->mEcoreWindow);
- }
- else
- {
- handler->mWindow->mIconified = false;
- if( handler->mWindow->mVisible )
- {
- observer->OnWindowShown();
- }
- DALI_LOG_RELEASE_INFO( "Window (%p) Deiconified\n", handler->mEcoreWindow );
- }
- handled = ECORE_CALLBACK_DONE;
- }
- }
-
- return handled;
- }
-
- /// Called when the window gains focus
- static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Focus_In* focusInEvent( static_cast< Ecore_Wl_Event_Focus_In* >( event ) );
- EventHandler* handler( static_cast< EventHandler* >( data ) );
-
- if ( handler && handler->mWindow && focusInEvent->win == static_cast< unsigned int >( ecore_wl_window_id_get( handler->mEcoreWindow ) ) )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n" );
-
- handler->mWindow->mFocusChangedSignal.Emit( true );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /// Called when the window loses focus
- static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Focus_Out* focusOutEvent( static_cast< Ecore_Wl_Event_Focus_Out* >( event ) );
- EventHandler* handler( static_cast< EventHandler* >( data ) );
-
- if ( handler && handler->mWindow && focusOutEvent->win == static_cast< unsigned int >(ecore_wl_window_id_get( handler->mEcoreWindow ) ) )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n" );
-
- handler->mWindow->mFocusChangedSignal.Emit( false );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /// Called when the output is transformed
- static Eina_Bool EcoreEventOutputTransform( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Output_Transform* transformEvent( static_cast< Ecore_Wl_Event_Output_Transform* >( event ) );
- EventHandler* handler( static_cast< EventHandler* >( data ) );
-
- if ( handler && handler->mWindow && transformEvent->output == ecore_wl_window_output_find( handler->mEcoreWindow ) )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", handler->mEcoreWindow );
-
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
- if( wlSurface )
- {
- wlSurface->OutputTransformed();
-
- PositionSize positionSize = wlSurface->GetPositionSize();
- handler->mWindow->mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- handler->mWindow->mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /// Called when the output transform should be ignored
- static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* event )
- {
- Ecore_Wl_Event_Ignore_Output_Transform* ignoreTransformEvent( static_cast< Ecore_Wl_Event_Ignore_Output_Transform* >( event ) );
- EventHandler* handler( static_cast< EventHandler* >( data ) );
-
- if ( handler && handler->mWindow && ignoreTransformEvent->win == handler->mEcoreWindow )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", handler->mEcoreWindow );
-
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
- if( wlSurface )
- {
- wlSurface->OutputTransformed();
-
- PositionSize positionSize = wlSurface->GetPositionSize();
- handler->mWindow->mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- handler->mWindow->mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- static void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version )
- {
- Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
-
- if( strcmp( interface, tizen_policy_interface.name ) == 0 )
- {
- uint32_t clientVersion = std::min( version, MAX_TIZEN_CLIENT_VERSION );
-
- eventHandler->mTizenPolicy = static_cast< tizen_policy* >( wl_registry_bind( registry, name, &tizen_policy_interface, clientVersion ) );
- if( !eventHandler->mTizenPolicy )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n" );
- return;
- }
-
- tizen_policy_add_listener( eventHandler->mTizenPolicy, &eventHandler->mTizenPolicyListener, data );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: tizen_policy_add_listener is called.\n" );
- }
- else if( strcmp( interface, tizen_display_policy_interface.name ) == 0 )
- {
- eventHandler->mTizenDisplayPolicy = static_cast< tizen_display_policy* >( wl_registry_bind( registry, name, &tizen_display_policy_interface, version ) );
- if( !eventHandler->mTizenDisplayPolicy )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n" );
- return;
- }
-
- tizen_display_policy_add_listener( eventHandler->mTizenDisplayPolicy, &eventHandler->mTizenDisplayPolicyListener, data );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n" );
- }
- }
-
- static void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id )
- {
- Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
- eventHandler->mTizenPolicy = NULL;
- eventHandler->mTizenDisplayPolicy = NULL;
- }
-
- static void TizenPolicyConformant( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant )
- {
- }
-
- static void TizenPolicyConformantArea( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h )
- {
- }
-
- static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state )
- {
- Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
-
- eventHandler->mNotificationLevel = level;
- eventHandler->mNotificationChangeState = state;
- eventHandler->mNotificationLevelChangeDone = true;
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state );
- }
-
- static void TizenPolicyTransientForDone( void* data, struct tizen_policy* tizenPolicy, uint32_t childId )
- {
- }
-
- static void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state )
- {
- Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
-
- eventHandler->mScreenOffMode = mode;
- eventHandler->mScreenOffModeChangeState = state;
- eventHandler->mScreenOffModeChangeDone = true;
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state );
- }
-
- static void TizenPolicyIconifyStateChanged( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force )
- {
- }
-
- static void TizenPolicySupportedAuxiliaryHints( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints )
- {
- }
-
- static void TizenPolicyAllowedAuxiliaryHint( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id )
- {
- }
-
- static void TizenPolicyAuxiliaryMessage( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options )
- {
- }
-
- static void TizenPolicyConformantRegion( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial )
- {
- }
-
- static void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state )
- {
- Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
-
- eventHandler->mBrightness = brightness;
- eventHandler->mBrightnessChangeState = state;
- eventHandler->mBrightnessChangeDone = true;
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state );
- }
-
- const struct wl_registry_listener mRegistryListener =
- {
- RegistryGlobalCallback,
- RegistryGlobalCallbackRemove
- };
-
- const struct tizen_policy_listener mTizenPolicyListener =
- {
- TizenPolicyConformant,
- TizenPolicyConformantArea,
- TizenPolicyNotificationChangeDone,
- TizenPolicyTransientForDone,
- TizenPolicyScreenModeChangeDone,
- TizenPolicyIconifyStateChanged,
- TizenPolicySupportedAuxiliaryHints,
- TizenPolicyAllowedAuxiliaryHint,
- TizenPolicyAuxiliaryMessage,
- TizenPolicyConformantRegion
- };
-
- const struct tizen_display_policy_listener mTizenDisplayPolicyListener =
- {
- DisplayPolicyBrightnessChangeDone
- };
-
- // Data
- Window* mWindow;
- Dali::Vector< Ecore_Event_Handler* > mEcoreEventHandler;
- Ecore_Wl_Window* mEcoreWindow;
-
- wl_display* mDisplay;
- wl_event_queue* mEventQueue;
- tizen_policy* mTizenPolicy;
- tizen_display_policy* mTizenDisplayPolicy;
-
- int mNotificationLevel;
- uint32_t mNotificationChangeState;
- bool mNotificationLevelChangeDone;
-
- int mScreenOffMode;
- uint32_t mScreenOffModeChangeState;
- bool mScreenOffModeChangeDone;
-
- int mBrightness;
- uint32_t mBrightnessChangeState;
- bool mBrightnessChangeDone;
-};
-
-Window* Window::New( const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent )
-{
- Window* window = new Window();
- window->mIsTransparent = isTransparent;
- window->Initialize( positionSize, name, className );
- return window;
-}
-
-void Window::SetAdaptor(Dali::Adaptor& adaptor)
-{
- DALI_ASSERT_ALWAYS( !mStarted && "Adaptor already started" );
- mStarted = true;
-
- // Only create one overlay per window
- Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor);
- Integration::Core& core = adaptorImpl.GetCore();
- mOverlay = &core.GetSystemOverlay();
-
- Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
- taskList.CreateTask();
-
- mAdaptor = &adaptorImpl;
- mAdaptor->AddObserver( *this );
-
- // Can only create the detector when we know the Core has been instantiated.
- mDragAndDropDetector = DragAndDropDetector::New();
- mAdaptor->SetDragAndDropDetector( &GetImplementation( mDragAndDropDetector ) );
-
- if( mOrientation )
- {
- mOrientation->SetAdaptor(adaptor);
- }
-
- if( mIndicator != NULL )
- {
- mIndicator->SetAdaptor(mAdaptor);
- }
-}
-
-RenderSurface* Window::GetSurface()
-{
- return mSurface;
-}
-
-void Window::ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode )
-{
- DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "visible : %d\n", visibleMode );
- DALI_ASSERT_DEBUG(mOverlay);
-
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
- DALI_ASSERT_DEBUG(wlSurface);
-
- if( wlSurface )
- {
- Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
-
- mIndicatorVisible = visibleMode;
-
- if ( mIndicatorVisible == Dali::Window::VISIBLE )
- {
- // when the indicator is visible, set proper mode for indicator server according to bg mode
- if ( mIndicatorOpacityMode == Dali::Window::OPAQUE )
- {
- ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_OPAQUE);
- }
- else if ( mIndicatorOpacityMode == Dali::Window::TRANSLUCENT )
- {
- ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_TRANSLUCENT);
- }
- else if ( mIndicatorOpacityMode == Dali::Window::TRANSPARENT )
- {
- ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_OPAQUE);
- }
- }
- else
- {
- // when the indicator is not visible, set TRANSPARENT mode for indicator server
- ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_TRANSPARENT); // it means hidden indicator
- }
- }
-
- DoShowIndicator( mIndicatorOrientation );
-}
-
-void Window::RotateIndicator( Dali::Window::WindowOrientation orientation )
-{
- DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "Orientation: %d\n", orientation );
-
- DoRotateIndicator( orientation );
-}
-
-void Window::SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacityMode )
-{
- mIndicatorOpacityMode = opacityMode;
-
- if( mIndicator != NULL )
- {
- mIndicator->SetOpacityMode( opacityMode );
- }
-}
-
-void Window::SetClass(std::string name, std::string klass)
-{
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
-
- if( wlSurface )
- {
- Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
- ecore_wl_window_title_set( wlWindow, name.c_str() );
- ecore_wl_window_class_name_set( wlWindow, klass.c_str() );
- }
- else
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window has no surface\n" );
- }
-}
-
-Window::Window()
-: mSurface( NULL ),
- mIndicatorVisible( Dali::Window::VISIBLE ),
- mIndicatorIsShown( false ),
- mShowRotatedIndicatorOnClose( false ),
- mStarted( false ),
- mIsTransparent( false ),
- mWMRotationAppSet( false ),
- mEcoreEventHander( true ),
- mIsFocusAcceptable( true ),
- mVisible( true ),
- mIconified( false ),
- mOpaqueState( false ),
- mResizeEnabled( false ),
- mIndicator( NULL ),
- mIndicatorOrientation( Dali::Window::PORTRAIT ),
- mNextIndicatorOrientation( Dali::Window::PORTRAIT ),
- mIndicatorOpacityMode( Dali::Window::OPAQUE ),
- mOverlay( NULL ),
- mAdaptor( NULL ),
- mType( Dali::Window::NORMAL ),
- mEventHandler( NULL ),
- mPreferredOrientation( Dali::Window::PORTRAIT ),
- mSupportedAuxiliaryHints(),
- mAuxiliaryHints(),
- mIndicatorVisibilityChangedSignal(),
- mFocusChangedSignal(),
- mResizedSignal(),
- mDeleteRequestSignal()
-{
-}
-
-Window::~Window()
-{
- delete mEventHandler;
-
- if( mIndicator )
- {
- mIndicator->Close();
- delete mIndicator;
- }
-
- if ( mAdaptor )
- {
- mAdaptor->RemoveObserver( *this );
- mAdaptor->SetDragAndDropDetector( NULL );
- mAdaptor = NULL;
- }
-
- delete mSurface;
-
- mSupportedAuxiliaryHints.clear();
- mAuxiliaryHints.clear();
-}
-
-void Window::Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className)
-{
- // create an Wayland window by default
- Any surface;
- ECore::WindowRenderSurface* windowSurface = new ECore::WindowRenderSurface( positionSize, surface, name, mIsTransparent );
-
- mSurface = windowSurface;
-
- // create event handler for Wayland window
- mEventHandler = new EventHandler( this );
-
- // get auxiliary hint
- Eina_List* hints = ecore_wl_window_aux_hints_supported_get( mEventHandler->mEcoreWindow );
- if( hints )
- {
- Eina_List* l = NULL;
- char* hint = NULL;
-
- for( l = hints, ( hint = static_cast< char* >( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( hint = static_cast< char* >( eina_list_data_get(l) ) ) )
- {
- mSupportedAuxiliaryHints.push_back( hint );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::Initialize: %s\n", hint );
- }
- }
-
- if( !positionSize.IsEmpty() )
- {
- AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
- mResizeEnabled = true;
- }
-
- SetClass( name, className );
- windowSurface->Map();
-
- mOrientation = Orientation::New(this);
-}
-
-void Window::DoShowIndicator( Dali::Window::WindowOrientation lastOrientation )
-{
- if( mIndicator == NULL )
- {
- if( mIndicatorVisible != Dali::Window::INVISIBLE )
- {
- mIndicator = new Indicator( mAdaptor, mIndicatorOrientation, this );
- mIndicator->SetOpacityMode( mIndicatorOpacityMode );
- Dali::Actor actor = mIndicator->GetActor();
- SetIndicatorActorRotation();
- mOverlay->Add(actor);
- }
- // else don't create a hidden indicator
- }
- else // Already have indicator
- {
- if( mIndicatorVisible == Dali::Window::VISIBLE )
- {
- // If we are resuming, and rotation has changed,
- if( mIndicatorIsShown == false && mIndicatorOrientation != mNextIndicatorOrientation )
- {
- // then close current indicator and open new one
- mShowRotatedIndicatorOnClose = true;
- mIndicator->Close(); // May synchronously call IndicatorClosed() callback & 1 level of recursion
- // Don't show actor - will contain indicator for old orientation.
- }
- }
- }
-
- // set indicator visible mode
- if( mIndicator != NULL )
- {
- mIndicator->SetVisible( mIndicatorVisible );
- }
-
- bool show = (mIndicatorVisible != Dali::Window::INVISIBLE );
- SetIndicatorProperties( show, lastOrientation );
- mIndicatorIsShown = show;
-}
-
-void Window::DoRotateIndicator( Dali::Window::WindowOrientation orientation )
-{
- if( mIndicatorIsShown )
- {
- mShowRotatedIndicatorOnClose = true;
- mNextIndicatorOrientation = orientation;
- mIndicator->Close(); // May synchronously call IndicatorClosed() callback
- }
- else
- {
- // Save orientation for when the indicator is next shown
- mShowRotatedIndicatorOnClose = false;
- mNextIndicatorOrientation = orientation;
- }
-}
-
-void Window::SetIndicatorProperties( bool isShow, Dali::Window::WindowOrientation lastOrientation )
-{
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
-
- if( wlSurface )
- {
- Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
- if ( isShow )
- {
- ecore_wl_window_indicator_state_set(wlWindow, ECORE_WL_INDICATOR_STATE_ON);
- }
- else
- {
- ecore_wl_window_indicator_state_set(wlWindow, ECORE_WL_INDICATOR_STATE_OFF);
- }
- }
-}
-
-void Window::IndicatorTypeChanged(Indicator::Type type)
-{
-#if defined(DALI_PROFILE_MOBILE)
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
-
- if( wlSurface )
- {
- Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
- switch(type)
- {
- case Indicator::INDICATOR_TYPE_1:
- ecore_wl_indicator_visible_type_set(wlWindow, ECORE_WL_INDICATOR_VISIBLE_TYPE_SHOWN);
- break;
-
- case Indicator::INDICATOR_TYPE_2:
- ecore_wl_indicator_visible_type_set(wlWindow, ECORE_WL_INDICATOR_VISIBLE_TYPE_HIDDEN);
- break;
-
- case Indicator::INDICATOR_TYPE_UNKNOWN:
- default:
- break;
- }
- }
-#endif //MOBILE
-}
-
-void Window::IndicatorClosed( IndicatorInterface* indicator )
-{
- DALI_LOG_TRACE_METHOD( gWindowLogFilter );
-
- if( mShowRotatedIndicatorOnClose )
- {
- Dali::Window::WindowOrientation currentOrientation = mIndicatorOrientation;
- mIndicator->Open(mNextIndicatorOrientation);
- mIndicatorOrientation = mNextIndicatorOrientation;
- SetIndicatorActorRotation();
- DoShowIndicator(currentOrientation);
- }
-}
-
-void Window::IndicatorVisibilityChanged(bool isVisible)
-{
- mIndicatorVisibilityChangedSignal.Emit(isVisible);
-}
-
-void Window::SetIndicatorActorRotation()
-{
- DALI_LOG_TRACE_METHOD( gWindowLogFilter );
- DALI_ASSERT_DEBUG( mIndicator != NULL );
-
- Dali::Actor actor = mIndicator->GetActor();
- switch( mIndicatorOrientation )
- {
- case Dali::Window::PORTRAIT:
- actor.SetParentOrigin( ParentOrigin::TOP_CENTER );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(0), Vector3::ZAXIS );
- break;
- case Dali::Window::PORTRAIT_INVERSE:
- actor.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(180), Vector3::ZAXIS );
- break;
- case Dali::Window::LANDSCAPE:
- actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(270), Vector3::ZAXIS );
- break;
- case Dali::Window::LANDSCAPE_INVERSE:
- actor.SetParentOrigin( ParentOrigin::CENTER_RIGHT );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(90), Vector3::ZAXIS );
- break;
- }
-}
-
-void Window::Raise()
-{
- // Use ecore_wl_window_activate to prevent the window shown without rendering
- ecore_wl_window_activate( mEventHandler->mEcoreWindow );
-}
-
-void Window::Lower()
-{
- ecore_wl_window_lower( mEventHandler->mEcoreWindow );
-}
-
-void Window::Activate()
-{
- ecore_wl_window_activate( mEventHandler->mEcoreWindow );
-}
-
-Dali::DragAndDropDetector Window::GetDragAndDropDetector() const
-{
- return mDragAndDropDetector;
-}
-
-Dali::Any Window::GetNativeHandle() const
-{
- if(mEventHandler)
- {
- return mEventHandler->mEcoreWindow;
- }
- else
- {
- return Dali::Any();
- }
-}
-
-void Window::OnStart()
-{
- DoShowIndicator( mIndicatorOrientation );
-}
-
-void Window::OnPause()
-{
-}
-
-void Window::OnResume()
-{
- // resume indicator status
- if( mIndicator != NULL )
- {
- // Restore own indicator opacity
- // Send opacity mode to indicator service when app resumed
- mIndicator->SetOpacityMode( mIndicatorOpacityMode );
- }
-}
-
-void Window::OnStop()
-{
- if( mIndicator )
- {
- mIndicator->Close();
- }
-
- delete mIndicator;
- mIndicator = NULL;
-}
-
-void Window::OnDestroy()
-{
- mAdaptor = NULL;
-}
-
-void Window::AddAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- bool found = false;
-
- if ( orientation <= Dali::Window::LANDSCAPE_INVERSE )
- {
- for( std::size_t i = 0; i < mAvailableOrientations.size(); i++ )
- {
- if( mAvailableOrientations[i] == orientation )
- {
- found = true;
- break;
- }
- }
-
- if( ! found )
- {
- mAvailableOrientations.push_back(orientation);
- SetAvailableOrientations( mAvailableOrientations );
- }
- }
-}
-
-void Window::RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- for( std::vector<Dali::Window::WindowOrientation>::iterator iter = mAvailableOrientations.begin();
- iter != mAvailableOrientations.end(); ++iter )
- {
- if( *iter == orientation )
- {
- mAvailableOrientations.erase( iter );
- break;
- }
- }
- SetAvailableOrientations( mAvailableOrientations );
-}
-
-void Window::SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations)
-{
- int rotations[4];
- for( std::size_t i = 0; i < mAvailableOrientations.size(); ++i )
- {
- rotations[i] = static_cast< int >( mAvailableOrientations[i] );
- }
- ecore_wl_window_rotation_available_rotations_set( mEventHandler->mEcoreWindow, rotations, mAvailableOrientations.size() );
-}
-
-const std::vector<Dali::Window::WindowOrientation>& Window::GetAvailableOrientations()
-{
- return mAvailableOrientations;
-}
-
-void Window::SetPreferredOrientation(Dali::Window::WindowOrientation orientation)
-{
- mPreferredOrientation = orientation;
-
- ecore_wl_window_rotation_preferred_rotation_set( mEventHandler->mEcoreWindow, orientation );
-}
-
-Dali::Window::WindowOrientation Window::GetPreferredOrientation()
-{
- return mPreferredOrientation;
-}
-
-void Window::SetAcceptFocus( bool accept )
-{
- mIsFocusAcceptable = accept;
-
- ecore_wl_window_focus_skip_set( mEventHandler->mEcoreWindow, !accept );
-}
-
-bool Window::IsFocusAcceptable() const
-{
- return mIsFocusAcceptable;
-}
-
-void Window::Show()
-{
- mVisible = true;
- ecore_wl_window_show( mEventHandler->mEcoreWindow );
-
- if( !mIconified )
- {
- if( mAdaptor )
- {
- WindowVisibilityObserver* observer( mAdaptor );
- observer->OnWindowShown();
- DALI_LOG_RELEASE_INFO( "Window (%p) ::Show() \n", mEventHandler->mEcoreWindow);
- }
- }
-}
-
-void Window::Hide()
-{
- mVisible = false;
- ecore_wl_window_hide( mEventHandler->mEcoreWindow );
-
- if( !mIconified )
- {
- if( mAdaptor )
- {
- WindowVisibilityObserver* observer( mAdaptor );
- observer->OnWindowHidden();
- DALI_LOG_RELEASE_INFO( "Window (%p) ::Hide() \n", mEventHandler->mEcoreWindow);
- }
- }
-}
-
-bool Window::IsVisible() const
-{
- return mVisible;
-}
-
-void Window::RotationDone( int orientation, int width, int height )
-{
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
- if( wlSurface )
- {
- wlSurface->RequestRotation( orientation, width, height );
- }
-
- mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( width, height ) );
-
- // Emit signal
- mResizedSignal.Emit( Dali::Window::WindowSize( width, height ) );
-
- mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( width, height ) );
-}
-
-void Window::SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode )
-{
- mIndicatorVisible = mode;
-}
-
-unsigned int Window::GetSupportedAuxiliaryHintCount() const
-{
- return mSupportedAuxiliaryHints.size();
-}
-
-std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
-{
- if( index >= GetSupportedAuxiliaryHintCount() )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index );
- }
-
- return mSupportedAuxiliaryHints[index];
-}
-
-unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
-{
- bool supported = false;
-
- // Check if the hint is suppported
- for( std::vector< std::string >::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter )
- {
- if( *iter == hint )
- {
- supported = true;
- break;
- }
- }
-
- if( !supported )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str() );
- return 0;
- }
-
- // Check if the hint is already added
- for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ )
- {
- if( mAuxiliaryHints[i].first == hint )
- {
- // Just change the value
- mAuxiliaryHints[i].second = value;
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1 );
-
- return i + 1; // id is index + 1
- }
- }
-
- // Add the hint
- mAuxiliaryHints.push_back( std::pair< std::string, std::string >( hint, value ) );
-
- unsigned int id = mAuxiliaryHints.size();
-
- ecore_wl_window_aux_hint_add( mEventHandler->mEcoreWindow, static_cast< int >( id ), hint.c_str(), value.c_str() );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id );
-
- return id;
-}
-
-bool Window::RemoveAuxiliaryHint( unsigned int id )
-{
- if( id == 0 || id > mAuxiliaryHints.size() )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::RemoveAuxiliaryHint: Invalid id [%d]\n", id );
- return false;
- }
-
- mAuxiliaryHints[id - 1].second = std::string();
-
- ecore_wl_window_aux_hint_del( mEventHandler->mEcoreWindow, static_cast< int >( id ) );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str() );
-
- return true;
-}
-
-bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
-{
- if( id == 0 || id > mAuxiliaryHints.size() )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::SetAuxiliaryHintValue: Invalid id [%d]\n", id );
- return false;
- }
-
- mAuxiliaryHints[id - 1].second = value;
-
- ecore_wl_window_aux_hint_change( mEventHandler->mEcoreWindow, static_cast< int >( id ), value.c_str() );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() );
-
- return true;
-}
-
-std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
-{
- if( id == 0 || id > mAuxiliaryHints.size() )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::GetAuxiliaryHintValue: Invalid id [%d]\n", id );
- return std::string();
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() );
-
- return mAuxiliaryHints[id - 1].second;
-}
-
-unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
-{
- for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ )
- {
- if( mAuxiliaryHints[i].first == hint )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1 );
- return i + 1;
- }
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str() );
-
- return 0;
-}
-
-void Window::SetInputRegion( const Rect< int >& inputRegion )
-{
- ecore_wl_window_input_region_set( mEventHandler->mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height );
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetInputRegion: x = %d, y = %d, w = %d, h = %d\n", inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height );
-}
-
-void Window::SetType( Dali::Window::Type type )
-{
- Ecore_Wl_Window_Type windowType;
-
- if( type != mType )
- {
- switch( type )
- {
- case Dali::Window::NORMAL:
- {
- windowType = ECORE_WL_WINDOW_TYPE_TOPLEVEL;
- break;
- }
- case Dali::Window::NOTIFICATION:
- {
- windowType = ECORE_WL_WINDOW_TYPE_NOTIFICATION;
- break;
- }
- case Dali::Window::UTILITY:
- {
- windowType = ECORE_WL_WINDOW_TYPE_UTILITY;
- break;
- }
- case Dali::Window::DIALOG:
- {
- windowType = ECORE_WL_WINDOW_TYPE_DIALOG;
- break;
- }
- default:
- {
- windowType = ECORE_WL_WINDOW_TYPE_TOPLEVEL;
- break;
- }
- }
-
- ecore_wl_window_type_set( mEventHandler->mEcoreWindow, windowType );
- }
-
- mType = type;
-}
-
-Dali::Window::Type Window::GetType() const
-{
- return mType;
-}
-
-bool Window::SetNotificationLevel( Dali::Window::NotificationLevel::Type level )
-{
- if( mType != Dali::Window::NOTIFICATION )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Not supported window type [%d]\n", mType );
- return false;
- }
-
- while( !mEventHandler->mTizenPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- int notificationLevel;
-
- switch( level )
- {
- case Dali::Window::NotificationLevel::NONE:
- {
- notificationLevel = TIZEN_POLICY_LEVEL_NONE;
- break;
- }
- case Dali::Window::NotificationLevel::BASE:
- {
- notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT;
- break;
- }
- case Dali::Window::NotificationLevel::MEDIUM:
- {
- notificationLevel = TIZEN_POLICY_LEVEL_MEDIUM;
- break;
- }
- case Dali::Window::NotificationLevel::HIGH:
- {
- notificationLevel = TIZEN_POLICY_LEVEL_HIGH;
- break;
- }
- case Dali::Window::NotificationLevel::TOP:
- {
- notificationLevel = TIZEN_POLICY_LEVEL_TOP;
- break;
- }
- default:
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: invalid level [%d]\n", level );
- notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT;
- break;
- }
- }
-
- mEventHandler->mNotificationLevelChangeDone = false;
- mEventHandler->mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
-
- tizen_policy_set_notification_level( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), notificationLevel );
-
- int count = 0;
-
- while( !mEventHandler->mNotificationLevelChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mNotificationLevelChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mEventHandler->mNotificationChangeState );
- return false;
- }
- else if( mEventHandler->mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Permission denied! [%d]\n", level );
- return false;
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Level is changed [%d]\n", mEventHandler->mNotificationLevel );
-
- return true;
-}
-
-Dali::Window::NotificationLevel::Type Window::GetNotificationLevel() const
-{
- if( mType != Dali::Window::NOTIFICATION )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Not supported window type [%d]\n", mType );
- return Dali::Window::NotificationLevel::NONE;
- }
-
- while( !mEventHandler->mTizenPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- int count = 0;
-
- while( !mEventHandler->mNotificationLevelChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mNotificationLevelChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Error! [%d]\n", mEventHandler->mNotificationChangeState );
- return Dali::Window::NotificationLevel::NONE;
- }
-
- Dali::Window::NotificationLevel::Type level;
-
- switch( mEventHandler->mNotificationLevel )
- {
- case TIZEN_POLICY_LEVEL_NONE:
- {
- level = Dali::Window::NotificationLevel::NONE;
- break;
- }
- case TIZEN_POLICY_LEVEL_DEFAULT:
- {
- level = Dali::Window::NotificationLevel::BASE;
- break;
- }
- case TIZEN_POLICY_LEVEL_MEDIUM:
- {
- level = Dali::Window::NotificationLevel::MEDIUM;
- break;
- }
- case TIZEN_POLICY_LEVEL_HIGH:
- {
- level = Dali::Window::NotificationLevel::HIGH;
- break;
- }
- case TIZEN_POLICY_LEVEL_TOP:
- {
- level = Dali::Window::NotificationLevel::TOP;
- break;
- }
- default:
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: invalid level [%d]\n", mEventHandler->mNotificationLevel );
- level = Dali::Window::NotificationLevel::NONE;
- break;
- }
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: level [%d]\n", mEventHandler->mNotificationLevel );
-
- return level;
-}
-
-void Window::SetOpaqueState( bool opaque )
-{
- while( !mEventHandler->mTizenPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- tizen_policy_set_opaque_state( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), ( opaque ? 1 : 0 ) );
-
- mOpaqueState = opaque;
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetOpaqueState: opaque = %d\n", opaque );
-}
-
-bool Window::IsOpaqueState() const
-{
- return mOpaqueState;
-}
-
-bool Window::SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode)
-{
- while( !mEventHandler->mTizenPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- mEventHandler->mScreenOffModeChangeDone = false;
- mEventHandler->mScreenOffModeChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
-
- unsigned int mode = 0;
-
- switch( screenOffMode )
- {
- case Dali::Window::ScreenOffMode::TIMEOUT:
- {
- mode = 0;
- break;
- }
- case Dali::Window::ScreenOffMode::NEVER:
- {
- mode = 1;
- break;
- }
- }
-
- tizen_policy_set_window_screen_mode( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), mode );
-
- int count = 0;
-
- while( !mEventHandler->mScreenOffModeChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mScreenOffModeChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mEventHandler->mScreenOffModeChangeState );
- return false;
- }
- else if( mEventHandler->mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode );
- return false;
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Screen mode is changed [%d]\n", mEventHandler->mScreenOffMode );
-
- return true;
-}
-
-Dali::Window::ScreenOffMode::Type Window::GetScreenOffMode() const
-{
- while( !mEventHandler->mTizenPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- int count = 0;
-
- while( !mEventHandler->mScreenOffModeChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mScreenOffModeChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetScreenOffMode: Error! [%d]\n", mEventHandler->mScreenOffModeChangeState );
- return Dali::Window::ScreenOffMode::TIMEOUT;
- }
-
- Dali::Window::ScreenOffMode::Type screenMode = Dali::Window::ScreenOffMode::TIMEOUT;
-
- switch( mEventHandler->mScreenOffMode )
- {
- case 0:
- {
- screenMode = Dali::Window::ScreenOffMode::TIMEOUT;
- break;
- }
- case 1:
- {
- screenMode = Dali::Window::ScreenOffMode::NEVER;
- break;
- }
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetScreenOffMode: screen mode [%d]\n", mEventHandler->mScreenOffMode );
-
- return screenMode;
-}
-
-bool Window::SetBrightness( int brightness )
-{
- if( brightness < 0 || brightness > 100 )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Invalid brightness value [%d]\n", brightness );
- return false;
- }
-
- while( !mEventHandler->mTizenDisplayPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- mEventHandler->mBrightnessChangeDone = false;
- mEventHandler->mBrightnessChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
-
- tizen_display_policy_set_window_brightness( mEventHandler->mTizenDisplayPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), brightness );
-
- int count = 0;
-
- while( !mEventHandler->mBrightnessChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mBrightnessChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mEventHandler->mBrightnessChangeState );
- return false;
- }
- else if( mEventHandler->mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Permission denied! [%d]\n", brightness );
- return false;
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Brightness is changed [%d]\n", mEventHandler->mBrightness );
-
- return true;
-}
-
-int Window::GetBrightness() const
-{
- while( !mEventHandler->mTizenDisplayPolicy )
- {
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- }
-
- int count = 0;
-
- while( !mEventHandler->mBrightnessChangeDone && count < 3 )
- {
- ecore_wl_flush();
- wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
- count++;
- }
-
- if( !mEventHandler->mBrightnessChangeDone )
- {
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetBrightness: Error! [%d]\n", mEventHandler->mBrightnessChangeState );
- return 0;
- }
-
- DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetBrightness: Brightness [%d]\n", mEventHandler->mBrightness );
-
- return mEventHandler->mBrightness;
-}
-
-void Window::SetSize( Dali::Window::WindowSize size )
-{
- if( !mResizeEnabled )
- {
- AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
- mResizeEnabled = true;
- }
-
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.width != size.GetWidth() || positionSize.height != size.GetHeight() )
- {
- positionSize.width = size.GetWidth();
- positionSize.height = size.GetHeight();
-
- mSurface->MoveResize( positionSize );
-
- mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
-
- // Emit signal
- mResizedSignal.Emit( Dali::Window::WindowSize( positionSize.width, positionSize.height ) );
-
- mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- }
-}
-
-Dali::Window::WindowSize Window::GetSize() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowSize( positionSize.width, positionSize.height );
-}
-
-void Window::SetPosition( Dali::Window::WindowPosition position )
-{
- if( !mResizeEnabled )
- {
- AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
- mResizeEnabled = true;
- }
-
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.x != position.GetX() || positionSize.y != position.GetY() )
- {
- positionSize.x = position.GetX();
- positionSize.y = position.GetY();
-
- mSurface->MoveResize( positionSize );
- }
-}
-
-Dali::Window::WindowPosition Window::GetPosition() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowPosition( positionSize.x, positionSize.y );
-}
-
-void Window::SetTransparency( bool transparent )
-{
- ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
- if( wlSurface )
- {
- wlSurface->SetTransparency( transparent );
- }
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <window-render-surface.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-#include <gl/egl-implementation.h>
-#include <adaptors/common/adaptor-impl.h>
-#include <integration-api/trigger-event-factory-interface.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gRenderSurfaceLogFilter;
-#endif
-
-namespace ECore
-{
-
-namespace
-{
-
-const int MINIMUM_DIMENSION_CHANGE( 1 ); ///< Minimum change for window to be considered to have moved
-
-} // unnamed namespace
-
-WindowRenderSurface::WindowRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: EcoreWlRenderSurface( positionSize, surface, name, isTransparent ),
- mWlWindow( NULL ),
- mWlSurface( NULL ),
- mEglWindow( NULL ),
- mThreadSynchronization( NULL ),
- mRotationTrigger( NULL ),
- mRotationAngle( 0 ),
- mScreenRotationAngle( 0 ),
- mRotationSupported( false ),
- mRotationFinished( true ),
- mScreenRotationFinished( true ),
- mResizeFinished( true )
-{
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n" );
- Init( surface );
-}
-
-WindowRenderSurface::~WindowRenderSurface()
-{
- if( mEglWindow != NULL )
- {
- wl_egl_window_destroy(mEglWindow);
- mEglWindow = NULL;
- }
-
- if( mOwnSurface )
- {
- ecore_wl_window_free( mWlWindow );
- }
-
- if( mRotationTrigger )
- {
- delete mRotationTrigger;
- }
-
-}
-
-Ecore_Wl_Window* WindowRenderSurface::GetDrawable()
-{
- // already an e-core type
- return mWlWindow;
-}
-
-Any WindowRenderSurface::GetSurface()
-{
- // already an e-core type
- return Any( mWlWindow );
-}
-
-Ecore_Wl_Window* WindowRenderSurface::GetWlWindow()
-{
- return mWlWindow;
-}
-
-void WindowRenderSurface::RequestRotation( int angle, int width, int height )
-{
- if( !mRotationSupported )
- {
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::Rotate: Rotation is not supported!\n" );
- return;
- }
-
- if( !mRotationTrigger )
- {
- TriggerEventFactoryInterface& triggerFactory = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetTriggerEventFactoryInterface();
- mRotationTrigger = triggerFactory.CreateTriggerEvent( MakeCallback( this, &WindowRenderSurface::ProcessRotationRequest ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
- }
-
- mPositionSize.width = width;
- mPositionSize.height = height;
-
- mRotationAngle = angle;
- mRotationFinished = false;
-
- ecore_wl_window_rotation_set( mWlWindow, mRotationAngle );
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::Rotate: angle = %d screen rotation = %d\n", mRotationAngle, mScreenRotationAngle );
-}
-
-void WindowRenderSurface::OutputTransformed()
-{
- int transform;
-
- if( ecore_wl_window_ignore_output_transform_get( mWlWindow ) )
- {
- transform = 0;
- }
- else
- {
- transform = ecore_wl_output_transform_get( ecore_wl_window_output_find( mWlWindow ) );
- }
-
- mScreenRotationAngle = transform * 90;
- mScreenRotationFinished = false;
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::OutputTransformed: angle = %d screen rotation = %d\n", mRotationAngle, mScreenRotationAngle );
-}
-
-void WindowRenderSurface::SetTransparency( bool transparent )
-{
- ecore_wl_window_alpha_set( mWlWindow, transparent );
-}
-
-void WindowRenderSurface::InitializeEgl( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
-
- eglImpl.ChooseConfig(true, mColorDepth);
-}
-
-void WindowRenderSurface::CreateEglSurface( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
-
- // create the EGL window
- if( mScreenRotationAngle == 0 || mScreenRotationAngle == 180 )
- {
- mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.width, mPositionSize.height );
- }
- else
- {
- mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.height, mPositionSize.width );
- }
-
- EGLNativeWindowType windowType( mEglWindow );
- eglImpl.CreateSurfaceWindow( windowType, mColorDepth );
-
- // Check capability
- wl_egl_window_capability capability = static_cast< wl_egl_window_capability >( wl_egl_window_get_capabilities( mEglWindow ) );
- if( capability == WL_EGL_WINDOW_CAPABILITY_ROTATION_SUPPORTED )
- {
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::CreateEglSurface: capability = %d\n", capability );
- mRotationSupported = true;
- }
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::CreateEglSurface: w = %d h = %d angle = %d screen rotation = %d\n", mPositionSize.width, mPositionSize.height, mRotationAngle, mScreenRotationAngle );
-}
-
-void WindowRenderSurface::DestroyEglSurface( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
- eglImpl.DestroySurface();
-
- if( mEglWindow != NULL )
- {
- wl_egl_window_destroy(mEglWindow);
- mEglWindow = NULL;
- }
-}
-
-bool WindowRenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- if( mEglWindow != NULL )
- {
- wl_egl_window_destroy(mEglWindow);
- mEglWindow = NULL;
- }
-
- if( mScreenRotationAngle == 0 || mScreenRotationAngle == 180 )
- {
- mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.width, mPositionSize.height );
- }
- else
- {
- mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.height, mPositionSize.width );
- }
-
- // Set screen rotation
- mScreenRotationFinished = false;
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- EGLNativeWindowType windowType( mEglWindow );
- return eglImpl.ReplaceSurfaceWindow( windowType );
-}
-
-void WindowRenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
- bool needToMove = false;
- bool needToResize = false;
-
- // check moving
- if( (fabs(positionSize.x - mPositionSize.x) > MINIMUM_DIMENSION_CHANGE) ||
- (fabs(positionSize.y - mPositionSize.y) > MINIMUM_DIMENSION_CHANGE) )
- {
- needToMove = true;
- }
-
- // check resizing
- if( (fabs(positionSize.width - mPositionSize.width) > MINIMUM_DIMENSION_CHANGE) ||
- (fabs(positionSize.height - mPositionSize.height) > MINIMUM_DIMENSION_CHANGE) )
- {
- needToResize = true;
- }
-
- if( needToMove )
- {
- ecore_wl_window_position_set( mWlWindow, positionSize.x, positionSize.y );
- }
- if( needToResize )
- {
- ecore_wl_window_update_size( mWlWindow, positionSize.width, positionSize.height );
- mResizeFinished = false;
- }
-
- mPositionSize = positionSize;
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::MoveResize: %d, %d, %d, %d\n", mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height );
-}
-
-void WindowRenderSurface::Map()
-{
- ecore_wl_window_show(mWlWindow);
-}
-
-void WindowRenderSurface::StartRender()
-{
-}
-
-bool WindowRenderSurface::PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface )
-{
- if( resizingSurface )
- {
-#ifdef OVER_TIZEN_VERSION_4
- // Window rotate or screen rotate
- if( !mRotationFinished || !mScreenRotationFinished )
- {
- wl_egl_window_rotation rotation;
- wl_output_transform bufferTransform;
- int totalAngle = (mRotationAngle + mScreenRotationAngle) % 360;
-
- switch( totalAngle )
- {
- case 0:
- {
- rotation = ROTATION_0;
- bufferTransform = WL_OUTPUT_TRANSFORM_NORMAL;
- break;
- }
- case 90:
- {
- rotation = ROTATION_270;
- bufferTransform = WL_OUTPUT_TRANSFORM_90;
- break;
- }
- case 180:
- {
- rotation = ROTATION_180;
- bufferTransform = WL_OUTPUT_TRANSFORM_180;
- break;
- }
- case 270:
- {
- rotation = ROTATION_90;
- bufferTransform = WL_OUTPUT_TRANSFORM_270;
- break;
- }
- default:
- {
- rotation = ROTATION_0;
- bufferTransform = WL_OUTPUT_TRANSFORM_NORMAL;
- break;
- }
- }
-
- wl_egl_window_set_rotation( mEglWindow, rotation );
-
- wl_egl_window_set_buffer_transform( mEglWindow, bufferTransform );
-
- // Reset only screen rotation flag
- mScreenRotationFinished = true;
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PreRender: Set rotation [%d] [%d]\n", mRotationAngle, mScreenRotationAngle );
- }
-
- // Only window rotate
- if( !mRotationFinished )
- {
- wl_output_transform windowTransform;
-
- switch( mRotationAngle )
- {
- case 0:
- {
- windowTransform = WL_OUTPUT_TRANSFORM_NORMAL;
- break;
- }
- case 90:
- {
- windowTransform = WL_OUTPUT_TRANSFORM_90;
- break;
- }
- case 180:
- {
- windowTransform = WL_OUTPUT_TRANSFORM_180;
- break;
- }
- case 270:
- {
- windowTransform = WL_OUTPUT_TRANSFORM_270;
- break;
- }
- default:
- {
- windowTransform = WL_OUTPUT_TRANSFORM_NORMAL;
- break;
- }
- }
-
- wl_egl_window_set_window_transform( mEglWindow, windowTransform );
- }
-#endif
-
- // Resize case
- if( !mResizeFinished )
- {
- wl_egl_window_resize( mEglWindow, mPositionSize.width, mPositionSize.height, mPositionSize.x, mPositionSize.y );
- mResizeFinished = true;
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PreRender: Set resize\n" );
- }
- }
-
- return true;
-}
-
-void WindowRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- if( resizingSurface )
- {
- if( !mRotationFinished )
- {
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PostRender: Trigger rotation event\n" );
-
- mRotationTrigger->Trigger();
-
- if( mThreadSynchronization )
- {
- // Wait until the event-thread complete the rotation event processing
- mThreadSynchronization->PostRenderWaitForCompletion();
- }
- }
- }
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.SwapBuffers();
-
- if( mRenderNotification )
- {
- mRenderNotification->Trigger();
- }
-}
-
-void WindowRenderSurface::StopRender()
-{
-}
-
-void WindowRenderSurface::SetViewMode( ViewMode viewMode )
-{
- //FIXME
-}
-
-void WindowRenderSurface::CreateWlRenderable()
-{
- // if width or height are zero, go full screen.
- if ( (mPositionSize.width == 0) || (mPositionSize.height == 0) )
- {
- // Default window size == screen size
- mPositionSize.x = 0;
- mPositionSize.y = 0;
-
- ecore_wl_screen_size_get( &mPositionSize.width, &mPositionSize.height );
- }
-
- mWlWindow = ecore_wl_window_new( 0, mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height, ECORE_WL_WINDOW_BUFFER_TYPE_EGL_WINDOW );
-
- if ( mWlWindow == 0 )
- {
- DALI_ASSERT_ALWAYS(0 && "Failed to create Wayland window");
- }
-
- mWlSurface = ecore_wl_window_surface_create( mWlWindow );
-
- if( mColorDepth == COLOR_DEPTH_32 )
- {
- ecore_wl_window_alpha_set( mWlWindow, true );
- }
- else
- {
- ecore_wl_window_alpha_set( mWlWindow, false );
- }
-
- // Get output transform
- if( !ecore_wl_window_ignore_output_transform_get( mWlWindow ) )
- {
- Ecore_Wl_Output* output = ecore_wl_window_output_find( mWlWindow );
-
- int transform = ecore_wl_output_transform_get( output );
-
- mScreenRotationAngle = transform * 90;
- mScreenRotationFinished = false;
- }
-}
-
-void WindowRenderSurface::UseExistingRenderable( unsigned int surfaceId )
-{
- mWlWindow = AnyCast< Ecore_Wl_Window* >( surfaceId );
-}
-
-void WindowRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
-{
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::SetThreadSynchronization: called\n" );
-
- mThreadSynchronization = &threadSynchronization;
-}
-
-void WindowRenderSurface::ReleaseLock()
-{
- // Nothing to do.
-}
-
-void WindowRenderSurface::ProcessRotationRequest()
-{
- mRotationFinished = true;
-
- ecore_wl_window_rotation_change_done_send( mWlWindow );
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::ProcessRotationRequest: Rotation Done\n" );
-
- if( mThreadSynchronization )
- {
- mThreadSynchronization->PostRenderComplete();
- }
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
-#define __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wayland-egl.h>
-
-// INTERNAL INCLUDES
-#include <ecore-wl-render-surface.h>
-#include <integration-api/thread-synchronization-interface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-/**
- * @copydoc Dali::ECore::EcoreWlRenderSurface.
- * Window specialization.
- */
-class WindowRenderSurface : public EcoreWlRenderSurface
-{
-public:
-
- /**
- * Uses an Wayland surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a Wayland-window or Wayland-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- WindowRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false );
-
- /**
- * @copydoc Dali::ECore::EcoreWlRenderSurface::~EcoreWlRenderSurface
- */
- virtual ~WindowRenderSurface();
-
-public: // API
-
- /**
- * @copydoc Dali::RenderSurface::GetDrawable()
- */
- virtual Ecore_Wl_Window* GetDrawable();
-
- /**
- * Map window
- */
- virtual void Map();
-
- /**
- * @copydoc Dali::ECore::EcoreWlRenderSurface::GetSurface()
- */
- virtual Any GetSurface();
-
- /**
- * @copydoc Dali::ECore::EcoreWlRenderSurface::GetWlWindow()
- */
- virtual Ecore_Wl_Window* GetWlWindow();
-
- /**
- * Request surface rotation
- * @param[in] angle A new angle of the surface
- * @param[in] width A new width of the surface
- * @param[in] height A new height of the surface
- */
- void RequestRotation( int angle, int width, int height );
-
- /**
- * Notify output is transformed.
- */
- void OutputTransformed();
-
- /**
- * @brief Sets whether the surface is transparent or not.
- *
- * @param[in] transparent Whether the surface is transparent
- */
- void SetTransparency( bool transparent );
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender()
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
- /**
- * @copydoc Dali::RenderSurface::ReleaseLock()
- */
- virtual void ReleaseLock();
-
-protected:
-
- /**
- * Create WlWindow
- */
- virtual void CreateWlRenderable();
-
- /**
- * @copydoc Dali::Internal::Adaptor::ECore::EcoreWlRenderSurface::UseExistingRenderable
- */
- virtual void UseExistingRenderable( unsigned int surfaceId );
-
-private:
-
- /**
- * Used as the callback for the rotation-trigger.
- */
- void ProcessRotationRequest();
-
-private: // Data
-
- Ecore_Wl_Window* mWlWindow; ///< Wayland-Window
- wl_surface* mWlSurface;
- wl_egl_window* mEglWindow;
- ThreadSynchronizationInterface* mThreadSynchronization;
- TriggerEventInterface* mRotationTrigger;
- int mRotationAngle;
- int mScreenRotationAngle;
- bool mRotationSupported;
- bool mRotationFinished;
- bool mScreenRotationFinished;
- bool mResizeFinished;
-
-}; // class WindowRenderSurface
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
+++ /dev/null
-#ifndef __DALI_INTEGRATION_ADAPTOR_H__
-#define __DALI_INTEGRATION_ADAPTOR_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/signals/callback.h>
-#include <dali/public-api/signals/dali-signal.h>
-#include <dali/public-api/math/rect.h>
-#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/common/view-mode.h>
-
-// INTERNAL INCLUDES
-
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-// @todo Make dali-adaptor code folder structure mirror the folder structure installed to dali-env
-#include <window.h>
-#include <application-configuration.h>
-#else
-#include <dali/public-api/adaptor-framework/window.h>
-#include <dali/public-api/adaptor-framework/application-configuration.h>
-#endif
-
-
-namespace Dali
-{
-
-class RenderSurface;
-
-namespace Internal
-{
-namespace Adaptor
-{
-class Adaptor;
-}
-}
-
-/**
- * @brief An Adaptor object is used to initialize and control how Dali runs.
- *
- * It provides a lifecycle interface that allows the application
- * writer to provide their own main loop and other platform related
- * features.
- *
- * The Adaptor class provides a means for initialising the resources required by the Dali::Core.
- *
- * When dealing with platform events, the application writer MUST ensure that Dali is called in a
- * thread-safe manner.
- *
- * As soon as the Adaptor class is created and started, the application writer can initialise their
- * Dali::Actor objects straight away or as required by the main loop they intend to use (there is no
- * need to wait for an initialise signal as per the Dali::Application class).
- *
- * The Adaptor does emit a Resize signal which informs the user when the surface is resized.
- * Tizen and Linux Adaptors should follow the example below:
- *
- * @code
- * void CreateProgram(DaliAdaptor& adaptor)
- * {
- * // Create Dali components...
- * // Can instantiate adaptor here instead, if required
- * }
- *
- * int main ()
- * {
- * // Initialise platform
- * MyPlatform.Init();
- *
- * // Create an 800 by 1280 window positioned at (0,0).
- * Dali::PositionSize positionSize(0, 0, 800, 1280);
- * Dali::Window window = Dali::Window::New( positionSize, "My Application" );
- *
- * // Create an adaptor which uses that window for rendering
- * Dali::Adaptor adaptor = Dali::Adaptor::New( window );
- * adaptor.Start();
- *
- * CreateProgram(adaptor);
- * // Or use this as a callback function depending on the platform initialisation sequence.
- *
- * // Start Main Loop of your platform
- * MyPlatform.StartMainLoop();
- *
- * return 0;
- * }
- * @endcode
- *
- * If required, you can also connect class member functions to a signal:
- *
- * @code
- * MyApplication application;
- * adaptor.ResizedSignal().Connect(&application, &MyApplication::Resize);
- * @endcode
- *
- * @see RenderSurface
- */
-class DALI_IMPORT_API Adaptor
-{
-public:
-
- typedef Signal< void (Adaptor&) > AdaptorSignalType; ///< Generic Type for adaptor signals
-
-public:
- /**
- * @brief Create a new adaptor using the window.
- *
- * @param[in] window The window to draw onto
- * @return a reference to the adaptor handle
- */
- static Adaptor& New( Window window );
-
- /**
- * @brief Create a new adaptor using the window.
- *
- * @param[in] window The window to draw onto
- * @param[in] configuration The context loss configuration.
- * @return a reference to the adaptor handle
- */
- static Adaptor& New( Window window, Configuration::ContextLoss configuration );
-
- /**
- * @brief Create a new adaptor using render surface.
- *
- * @param[in] nativeWindow native window handle
- * @param[in] surface The surface to draw onto
- * @return a reference to the adaptor handle
- */
- static Adaptor& New( Any nativeWindow, const Dali::RenderSurface& surface );
-
- /**
- * @brief Create a new adaptor using render surface.
- *
- * @param[in] nativeWindow native window handle
- * @param[in] surface The surface to draw onto
- * @param[in] configuration The context loss configuration.
- * @return a reference to the adaptor handle
- */
- static Adaptor& New( Any nativeWindow, const Dali::RenderSurface& surface, Configuration::ContextLoss configuration = Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS);
-
- /**
- * @brief Virtual Destructor.
- */
- virtual ~Adaptor();
-
-public:
-
- /**
- * @brief Starts the Adaptor.
- */
- void Start();
-
- /**
- * @brief Pauses the Adaptor.
- */
- void Pause();
-
- /**
- * @brief Resumes the Adaptor, if previously paused.
- *
- * @note If the adaptor is not paused, this does not do anything.
- */
- void Resume();
-
- /**
- * @brief Stops the Adaptor.
- */
- void Stop();
-
- /**
- * @brief Ensures that the function passed in is called from the main loop when it is idle.
- * @note Function must be called from the main event thread only.
- *
- * A callback of the following type may be used:
- * @code
- * void MyFunction();
- * @endcode
- *
- * @param[in] callback The function to call.
- * @return true if added successfully, false otherwise
- *
- * @note Ownership of the callback is passed onto this class.
- */
- bool AddIdle( CallbackBase* callback );
-
- /**
- * @brief Removes a previously added @p callback.
- * @note Function must be called from the main event thread only.
- *
- * Does nothing if the @p callback doesn't exist.
- *
- * @param[in] callback The callback to be removed.
- */
- void RemoveIdle( CallbackBase* callback );
-
- /**
- * @brief Replaces the rendering surface
- *
- * @param[in] nativeWindow native window handle
- * @param[in] surface to use
- */
- void ReplaceSurface( Any nativeWindow, Dali::RenderSurface& surface );
-
- /**
- * @brief Get the render surface the adaptor is using to render to.
- *
- * @return reference to current render surface
- */
- RenderSurface& GetSurface();
-
- /**
- * @brief Gets native window handle
- *
- * @return Native window handle
- */
- Any GetNativeWindowHandle();
-
- /**
- * @brief Release any locks the surface may hold.
- *
- * For example, after compositing an offscreen surface, use this method to allow
- * rendering to continue.
- */
- void ReleaseSurfaceLock();
-
- /**
- * @brief Set the number of frames per render.
- *
- * This enables an application to deliberately render with a reduced FPS.
- * @param[in] numberOfVSyncsPerRender The number of vsyncs between successive renders.
- * Suggest this is a power of two:
- * 1 - render each vsync frame
- * 2 - render every other vsync frame
- * 4 - render every fourth vsync frame
- * 8 - render every eighth vsync frame
- */
- void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender );
-
- /**
- * @brief Set whether the frame count per render is managed using the hardware VSync or
- * manually timed.
- *
- * @param[in] useHardware True if the hardware VSync should be used
- */
- void SetUseHardwareVSync(bool useHardware);
-
- /**
- * @brief Returns a reference to the instance of the adaptor used by the current thread.
- *
- * @return A reference to the adaptor.
- * @pre The adaptor has been initialised.
- * @note This is only valid in the main thread.
- */
- static Adaptor& Get();
-
- /**
- * @brief Checks whether the adaptor is available.
- *
- * @return true, if it is available, false otherwise.
- */
- static bool IsAvailable();
-
- /**
- * @brief Call this method to notify Dali when scene is created and initialized.
- *
- * Notify Adaptor that the scene has been created.
- */
- void NotifySceneCreated();
-
- /**
- * @brief Call this method to notify Dali when the system language changes.
- *
- * Use this only when NOT using Dali::Application, As Application created using
- * Dali::Application will automatically receive notification of language change.
- * When Dali::Application is not used, the application developer should
- * use app-core to receive language change notifications and should update Dali
- * by calling this method.
- */
- void NotifyLanguageChanged();
-
- /**
- * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
- * trigger a pinch gesture
- *
- * @param[in] distance The minimum pinch distance in pixels
- */
- void SetMinimumPinchDistance(float distance);
-
- /**
- * @brief Feed a touch point to the adaptor.
- *
- * @param[in] point touch point
- * @param[in] timeStamp time value of event
- */
- void FeedTouchPoint( TouchPoint& point, int timeStamp );
-
- /**
- * @brief Feed a wheel event to the adaptor.
- *
- * @param[in] wheelEvent wheel event
- */
- void FeedWheelEvent( WheelEvent& wheelEvent );
-
- /**
- * @brief Feed a key event to the adaptor.
- *
- * @param[in] keyEvent The key event holding the key information.
- */
- void FeedKeyEvent( KeyEvent& keyEvent );
-
- /**
- * @copydoc Dali::Core::SceneCreated();
- */
- void SceneCreated();
-
- /**
- * @copydoc Dali::Application::SetViewMode();
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::Application::SetStereoBase();
- */
- void SetStereoBase( float stereoBase );
-
- /**
- * @brief Renders once more even if we're paused
- * @note Will not work if the window is hidden.
- */
- void RenderOnce();
-
-public: // Signals
-
- /**
- * @brief The user should connect to this signal if they need to perform any
- * special activities when the surface Dali is being rendered on is resized.
- *
- * @return The signal to connect to
- */
- AdaptorSignalType& ResizedSignal();
-
- /**
- * @brief This signal is emitted when the language is changed on the device.
- *
- * @return The signal to connect to
- */
- AdaptorSignalType& LanguageChangedSignal();
-
-private:
-
- // Undefined
- Adaptor(const Adaptor&);
- Adaptor& operator=(Adaptor&);
-
-private:
-
- /**
- * @brief Create an uninitialized Adaptor.
- */
- Adaptor();
-
- Internal::Adaptor::Adaptor* mImpl; ///< Implementation object
- friend class Internal::Adaptor::Adaptor;
-};
-
-} // namespace Dali
-
-#endif // __DALI_INTEGRATION_ADAPTOR_H__
+++ /dev/null
-adaptor_integration_api_header_files = \
- $(adaptor_integration_api_dir)/adaptor.h \
- $(adaptor_integration_api_dir)/egl-interface.h \
- $(adaptor_integration_api_dir)/thread-synchronization-interface.h \
- $(adaptor_integration_api_dir)/trigger-event-interface.h \
- $(adaptor_integration_api_dir)/trigger-event-factory-interface.h \
- $(adaptor_integration_api_dir)/trigger-event-factory.h
-
-adaptor_integration_wayland_api_header_files = \
- $(adaptor_integration_api_dir)/wayland/wl-types.h \
- $(adaptor_integration_api_dir)/wayland/ecore-wl-render-surface.h \
- $(adaptor_integration_api_dir)/wayland/native-render-surface.h \
- $(adaptor_integration_api_dir)/native-render-surface-factory.h
-
-adaptor_integration_ecore_wayland_api_header_files = \
- $(adaptor_integration_api_dir)/../ecore/wayland/imf-manager-impl.h
-
-adaptor_integration_x11_api_header_files = \
- $(adaptor_integration_api_dir)/x11/ecore-x-types.h \
- $(adaptor_integration_api_dir)/x11/ecore-x-render-surface.h \
- $(adaptor_integration_api_dir)/x11/pixmap-render-surface.h \
- $(adaptor_integration_api_dir)/x11/imf-manager-impl.h \
- $(adaptor_integration_api_dir)/pixmap-render-surface-factory.h
+++ /dev/null
-#ifndef __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
-#define __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/signals/callback.h>
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION
-#include <trigger-event-interface.h>
-#else
-#include <dali/integration-api/adaptors/trigger-event-interface.h>
-#endif
-
-namespace Dali
-{
-
-/**
- * @brief Trigger interface factory class for creating a TriggerEvents
- *
- */
-class TriggerEventFactoryInterface
-{
-public:
-
-
- /**
- * @brief Create a new concrete implementation of the event trigger interface.
- * @param callback called when interface->Trigger() is called
- * @param options TriggerEventInterface option
- * @return pointer to a new trigger event
- * @note Ownership of callback should be taken over by deriving classes
- */
- virtual TriggerEventInterface* CreateTriggerEvent( CallbackBase* callback,
- TriggerEventInterface::Options options ) = 0;
- /**
- * @brief destroy a trigger event
- * @param triggerEventInterface event to destroy
- */
- virtual void DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface ) = 0;
-
-protected:
-
- /**
- * @brief Constructor
- */
- TriggerEventFactoryInterface()
- {
- }
-
- /**
- * @brief Virtual Destructor
- */
- virtual ~TriggerEventFactoryInterface()
- {
- }
-
-private:
-
-
- // Undefined copy constructor.
- TriggerEventFactoryInterface( const TriggerEventFactoryInterface& );
-
- // Undefined assignment operator.
- TriggerEventFactoryInterface& operator=( const TriggerEventFactoryInterface& );
-
-};
-
-} // namespace Dali
-
-#endif // __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
+++ /dev/null
-#ifndef __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
-#define __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#ifdef DALI_ADAPTOR_COMPILATION
-#include <trigger-event-factory-interface.h>
-#else
-#include <dali/integration-api/adaptors/trigger-event-factory-interface.h>
-#endif
-
-namespace Dali
-{
-
-/**
- * @brief Trigger interface factory class
- *
- */
-class DALI_IMPORT_API TriggerEventFactory : public TriggerEventFactoryInterface
-{
-
-public:
-
- /**
- * @brief Constructor
- */
- TriggerEventFactory()
- {
- }
-
- /**
- * @brief Destructor
- */
- virtual ~TriggerEventFactory()
- {
- }
-
- /**
- * @copydoc TriggerEventFactoryInterface::CreateTriggerEvent
- */
- virtual TriggerEventInterface* CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options );
-
-
- /**
- * @copydoc TriggerEventFactoryInterface::DestroyTriggerEvent
- */
- virtual void DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface );
-
-};
-
-} // namespace Dali
-
-#endif // __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
+++ /dev/null
-#ifndef __DALI_ECORE_WL_RENDER_SURFACE_H__
-#define __DALI_ECORE_WL_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_Wayland.h>
-#include <dali/public-api/common/dali-common.h>
-
-// INTERNAL INCLUDES
-#include <render-surface.h>
-#include <egl-interface.h>
-
-namespace Dali
-{
-
-class TriggerEventInterface;
-
-namespace ECore
-{
-
-/**
- * Ecore Wayland implementation of render surface.
- * @todo change namespace to ECore_Wayland as the class
- * is no longer pure Wayland.
- */
-class DALI_IMPORT_API EcoreWlRenderSurface : public Dali::RenderSurface
-{
-public:
- /**
- * Uses an Wayland surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- EcoreWlRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false);
-
- /**
- * Destructor.
- * Will delete the display, if it has ownership.
- * Will delete the window/pixmap if it has owner ship
- */
- virtual ~EcoreWlRenderSurface();
-
-protected:
- /**
- * Second stage construction
- * Creates the surface (window, pixmap or native buffer)
- */
- void Init( Any surface );
-
-public: // API
-
- /**
- * @brief Sets the render notification trigger to call when render thread is completed a frame
- *
- * @param renderNotification to use
- */
- void SetRenderNotification(TriggerEventInterface* renderNotification);
-
- /**
- * @brief Get window handle
- *
- * @return the Ecore X window handle
- */
- virtual Ecore_Wl_Window* GetWlWindow();
-
- /**
- * Get the surface as an Ecore_Wl_Window
- */
- virtual Ecore_Wl_Window* GetDrawable();
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::GetPositionSize()
- */
- virtual PositionSize GetPositionSize() const;
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender() = 0;
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::ReleaseLock()
- */
- virtual void ReleaseLock() = 0;
-
- /**
- * @copydoc Dali::RenderSurface::GetSurfaceType()
- */
- virtual RenderSurface::Type GetSurfaceType();
-
-private:
-
- /**
- * Get the surface id if the surface parameter is not empty
- * @param surface Any containing a surface id, or can be empty
- * @return surface id, or zero if surface is empty
- */
- unsigned int GetSurfaceId( Any surface ) const;
-
-protected:
-
- /**
- * Create XRenderable
- */
- virtual void CreateWlRenderable() = 0;
-
- /**
- * Use an existing render surface
- * @param surfaceId the id of the surface
- */
- virtual void UseExistingRenderable( unsigned int surfaceId ) = 0;
-
-protected: // Data
-
- PositionSize mPositionSize; ///< Position
- std::string mTitle; ///< Title of window which shows from "xinfo -topvwins" command
- TriggerEventInterface* mRenderNotification; ///< Render notification trigger
- ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit)
- bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it)
-};
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_ECORE_WL_RENDER_SURFACE_H__
+++ /dev/null
-#ifndef __DALI_NATIVE_RENDER_SURFACE_H__
-#define __DALI_NATIVE_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <tbm_surface.h>
-#include <dali/public-api/common/dali-common.h>
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION
-#include <render-surface.h>
-#include <egl-interface.h>
-#else
-#include <dali/devel-api/adaptor-framework/render-surface.h>
-#include <dali/integration-api/adaptors/egl-interface.h>
-#endif
-
-namespace Dali
-{
-
-class TriggerEventInterface;
-
-/**
- * Ecore X11 implementation of render surface.
- */
-class DALI_IMPORT_API NativeRenderSurface : public Dali::RenderSurface
-{
-public:
-
- /**
- * Uses an Wayland surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- NativeRenderSurface( Dali::PositionSize positionSize,
- const std::string& name,
- bool isTransparent = false );
-
- /**
- * @copydoc Dali::RenderSurface::~RenderSurface
- */
- virtual ~NativeRenderSurface();
-
-public: // API
-
- /**
- * @brief Sets the render notification trigger to call when render thread is completed a frame
- *
- * @param renderNotification to use
- */
- void SetRenderNotification( TriggerEventInterface* renderNotification );
-
- /**
- * @brief Gets the tbm surface for offscreen rendering
- */
- virtual tbm_surface_h GetDrawable();
-
- /**
- * @brief Gets the surface
- *
- * @return TBM surface
- */
- virtual Any GetSurface();
-
- /**
- * @brief Waits until surface is replaced
- * After tbm surface is acquired in PostRender, this function is finished.
- */
- void WaitUntilSurfaceReplaced();
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::GetPositionSize()
- */
- virtual PositionSize GetPositionSize() const;
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender()
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
- /**
- * @copydoc Dali::RenderSurface::GetSurfaceType()
- */
- virtual RenderSurface::Type GetSurfaceType();
-
-private:
-
- /**
- * Release any locks.
- */
- void ReleaseLock();
-
- /**
- * Create tbm surface
- */
- virtual void CreateNativeRenderable();
-
- /**
- * Release tbm surface
- */
- void ReleaseDrawable();
-
-private: // Data
-
- struct Impl;
-
- Impl* mImpl;
-
-};
-
-} // namespace Dali
-
-#endif // __DALI_NATIVE_RENDER_SURFACE_H__
+++ /dev/null
-#ifndef __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
-#define __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <ecore-wl-render-surface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-/**
- * Ecore X11 implementation of render surface.
- */
-class PixmapRenderSurface : public EcoreWlRenderSurface
-{
-public:
-
- /**
- * Uses an Wayland surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a Wayland-window (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- PixmapRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false);
-
- /**
- * @copydoc Dali::RenderSurface::~RenderSurface
- */
- virtual ~PixmapRenderSurface();
-
-public: // API
-
- /**
- * @copydoc Dali::ECore::EcoreWlRenderSurface::GetDrawable()
- */
- virtual Ecore_Wl_Window* GetDrawable();
-
- /**
- * @brief GetSurface
- *
- * @return pixmap
- */
- virtual Any GetSurface();
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender()
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
-private:
- enum SyncMode
- {
- SYNC_MODE_NONE,
- SYNC_MODE_WAIT
- };
-
- /**
- * Set the sync mode.
- * @param[in] syncMode The sync mode
- */
- void SetSyncMode( SyncMode syncMode );
-
- /**
- * If sync mode is WAIT, then acquire a lock. This prevents render thread from
- * continuing until the pixmap has been drawn by the compositor.
- * It must be released for rendering to continue.
- */
- void AcquireLock();
-
- /**
- * Release any locks.
- */
- void ReleaseLock();
-
- /**
- * Create XPixmap
- */
- virtual void CreateWlRenderable();
-
- /**
- * @copydoc Dali::Internal::Adaptor::ECore::RenderSurface::UseExistingRenderable
- */
- virtual void UseExistingRenderable( unsigned int surfaceId );
-
-private: // Data
-
-};
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+++ /dev/null
-#ifndef __DALI_ECORE_X_RENDER_SURFACE_H__
-#define __DALI_ECORE_X_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-#include <dali/public-api/common/dali-common.h>
-
-// INTERNAL INCLUDES
-#include <render-surface.h>
-#include <ecore-x-types.h>
-#include <egl-interface.h>
-
-namespace Dali
-{
-
-class TriggerEventInterface;
-
-namespace ECore
-{
-
-/**
- * Ecore X11 implementation of render surface.
- * @todo change namespace to ECore_X11 as the class
- * is no longer pure X11.
- */
-class DALI_IMPORT_API EcoreXRenderSurface : public Dali::RenderSurface
-{
-public:
- /**
- * Uses an X11 surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- EcoreXRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false);
-
- /**
- * Destructor.
- * Will delete the display, if it has ownership.
- * Will delete the window/pixmap if it has owner ship
- */
- virtual ~EcoreXRenderSurface();
-
-protected:
- /**
- * Second stage construction
- * Creates the surface (window, pixmap or native buffer)
- */
- void Init( Any surface );
-
-public: // API
-
- /**
- * @brief Sets the render notification trigger to call when render thread is completed a frame
- *
- * @param renderNotification to use
- */
- void SetRenderNotification(TriggerEventInterface* renderNotification);
-
- /**
- * @brief Get window handle
- *
- * @return the Ecore X window handle
- */
- Ecore_X_Window GetXWindow();
-
- /**
- * Get the surface as an Ecore_X_drawable
- */
- virtual Ecore_X_Drawable GetDrawable();
-
- /**
- * @brief Get the render surface the adaptor is using to render to.
- *
- * @return reference to current render surface (eg, pixmap / window)
- */
- virtual Any GetSurface() = 0;
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::GetPositionSize()
- */
- virtual PositionSize GetPositionSize() const;
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender() = 0;
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface ) = 0;
-
- /**
- * @copydoc Dali::RenderSurface::ReleaseLock()
- */
- virtual void ReleaseLock() = 0;
-
- /**
- * @copydoc Dali::RenderSurface::GetSurfaceType()
- */
- virtual RenderSurface::Type GetSurfaceType();
-
-private:
-
- /**
- * Get the surface id if the surface parameter is not empty
- * @param surface Any containing a surface id, or can be empty
- * @return surface id, or zero if surface is empty
- */
- unsigned int GetSurfaceId( Any surface ) const;
-
-protected:
-
- /**
- * Create XRenderable
- */
- virtual void CreateXRenderable() = 0;
-
- /**
- * Use an existing render surface
- * @param surfaceId the id of the surface
- */
- virtual void UseExistingRenderable( unsigned int surfaceId ) = 0;
-
-protected: // Data
-
- PositionSize mPosition; ///< Position
- std::string mTitle; ///< Title of window which shows from "xinfo -topvwins" command
- TriggerEventInterface* mRenderNotification; ///< Render notification trigger
- ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit)
- bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it)
-};
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_ECORE_X_RENDER_SURFACE_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_IMF_MANAGER_H
-#define __DALI_INTERNAL_IMF_MANAGER_H
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_IMF.h>
-#include <Ecore_X.h>
-
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <imf-manager.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class DALI_IMPORT_API ImfManager : public Dali::BaseObject
-{
-public:
- typedef Dali::ImfManager::ImfManagerSignalType ImfManagerSignalType;
- typedef Dali::ImfManager::ImfEventSignalType ImfEventSignalType;
- typedef Dali::ImfManager::StatusSignalType ImfStatusSignalType;
- typedef Dali::ImfManager::VoidSignalType ImfVoidSignalType;
- typedef Dali::ImfManager::KeyboardTypeSignalType ImfKeyboardTypeSignalType;
- typedef Dali::ImfManager::KeyboardResizedSignalType KeyboardResizedSignalType;
- typedef Dali::ImfManager::LanguageChangedSignalType LanguageChangedSignalType;
-
-public:
-
- /**
- * Check whether the ImfManager is available.
- * @return true if available, false otherwise
- */
- static bool IsAvailable();
-
- /**
- * Get the IMF manager instance, it creates the instance if it has not already been created.
- * Internally, a check should be made using IsAvailable() before this is called as we do not want
- * to create an instance if not needed by applications.
- * @see IsAvailable()
- */
- static Dali::ImfManager Get();
-
- /**
- * Constructor
- * @param[in] ecoreXwin, The window is created by application.
- */
- ImfManager( Ecore_X_Window ecoreXwin );
-
- /**
- * Connect Callbacks required for IMF.
- * If you don't connect imf callbacks, you can't get the key events.
- * The events are PreeditChanged, Commit and DeleteSurrounding.
- */
- void ConnectCallbacks();
-
- /**
- * Disconnect Callbacks attached to imf context.
- */
- void DisconnectCallbacks();
-
- /**
- * @copydoc Dali::ImfManager::Activate()
- */
- void Activate();
-
- /**
- * @copydoc Dali::ImfManager::Deactivate()
- */
- void Deactivate();
-
- /**
- * @copydoc Dali::ImfManager::Reset()
- */
- void Reset();
-
- /**
- * @copydoc Dali::ImfManager::GetContext()
- */
- Ecore_IMF_Context* GetContext();
-
- /**
- * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
- */
- bool RestoreAfterFocusLost() const;
-
- /**
- * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
- */
- void SetRestoreAfterFocusLost( bool toggle );
-
- /**
- * @copydoc Dali::ImfManager::PreEditChanged()
- */
- void PreEditChanged( void* data, Ecore_IMF_Context* imfContext, void* event_info );
-
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- void CommitReceived( void* data, Ecore_IMF_Context* imfContext, void* event_info );
-
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- Eina_Bool RetrieveSurrounding( void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition );
-
- /**
- * @copydoc Dali::ImfManager::DeleteSurrounding()
- */
- void DeleteSurrounding( void* data, Ecore_IMF_Context* imfContext, void* event_info );
-
- // Cursor related
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- void NotifyCursorPosition();
-
- /**
- * @copydoc Dali::ImfManager::SetCursorPosition()
- */
- void SetCursorPosition( unsigned int cursorPosition );
-
- /**
- * @copydoc Dali::ImfManager::GetCursorPosition()
- */
- unsigned int GetCursorPosition() const;
-
- /**
- * @copydoc Dali::ImfManager::SetSurroundingText()
- */
- void SetSurroundingText( const std::string& text );
-
- /**
- * @copydoc Dali::ImfManager::GetSurroundingText()
- */
- const std::string& GetSurroundingText() const;
-
- /**
- * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
- */
- void NotifyTextInputMultiLine( bool multiLine );
-
- /**
- * @copydoc Dali::ImfManager::GetTextDirection()
- */
- Dali::ImfManager::TextDirection GetTextDirection();
-
- /**
- * @copydoc Dali::ImfManager::GetInputMethodArea()
- */
- Dali::Rect<int> GetInputMethodArea();
-
- /**
- * @copydoc Dali::ImfManager::ApplyOptions()
- */
- void ApplyOptions( const InputMethodOptions& options );
-
- /**
- * @copydoc Dali::ImfManager::SetInputPanelData()
- */
- void SetInputPanelData( const std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelData()
- */
- void GetInputPanelData( std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelState()
- */
- Dali::ImfManager::State GetInputPanelState();
-
- /**
- * @copydoc Dali::ImfManager::SetReturnKeyState()
- */
- void SetReturnKeyState( bool visible );
-
- /**
- * @copydoc Dali::ImfManager::AutoEnableInputPanel()
- */
- void AutoEnableInputPanel( bool enabled );
-
- /**
- * @copydoc Dali::ImfManager::ShowInputPanel()
- */
- void ShowInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::HideInputPanel()
- */
- void HideInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::GetKeyboardType()
- */
- Dali::ImfManager::KeyboardType GetKeyboardType();
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelLocale()
- */
- std::string GetInputPanelLocale();
-
-public: // Signals
-
- /**
- * @copydoc Dali::ImfManager::ActivatedSignal()
- */
- ImfManagerSignalType& ActivatedSignal() { return mActivatedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::EventReceivedSignal()
- */
- ImfEventSignalType& EventReceivedSignal() { return mEventSignal; }
-
- /**
- * @copydoc Dali::ImfManager::StatusChangedSignal()
- */
- ImfStatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; }
-
- /**
- * @copydoc Dali::ImfManager::ResizedSignal()
- */
- KeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; }
-
- /**
- * @copydoc Dali::ImfManager::LanguageChangedSignal()
- */
- LanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::KeyboardTypeChangedSignal()
- */
- ImfKeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; }
-protected:
-
- /**
- * Destructor.
- */
- virtual ~ImfManager();
-
-private:
- /**
- * Context created the first time and kept until deleted.
- * @param[in] ecoreXwin, The window is created by application.
- */
- void CreateContext( Ecore_X_Window ecoreXwin );
-
- /**
- * @copydoc Dali::ImfManager::DeleteContext()
- */
- void DeleteContext();
-
-private:
- // Undefined
- ImfManager( const ImfManager& );
- ImfManager& operator=( ImfManager& );
-
-private:
- Ecore_IMF_Context* mIMFContext;
- int mIMFCursorPosition;
- std::string mSurroundingText;
-
- bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
- bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected.
- InputMethodOptions mOptions;
-
- ImfManagerSignalType mActivatedSignal;
- ImfEventSignalType mEventSignal;
- ImfStatusSignalType mKeyboardStatusSignal;
- KeyboardResizedSignalType mKeyboardResizeSignal;
- LanguageChangedSignalType mKeyboardLanguageChangedSignal;
- ImfKeyboardTypeSignalType mKeyboardTypeChangedSignal;
-
-public:
-
-DALI_IMPORT_API inline static Internal::Adaptor::ImfManager& GetImplementation(Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<Internal::Adaptor::ImfManager&>(handle);
-}
-
-DALI_IMPORT_API inline static const Internal::Adaptor::ImfManager& GetImplementation(const Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- const BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::ImfManager&>(handle);
-}
-
-};
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_IMF_MANAGER_H
+++ /dev/null
-#ifndef __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
-#define __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <ecore-x-render-surface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-/**
- * Ecore X11 implementation of render surface.
- */
-class PixmapRenderSurface : public EcoreXRenderSurface
-{
-public:
-
- /**
- * Uses an X11 surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- PixmapRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false);
-
- /**
- * @copydoc Dali::RenderSurface::~RenderSurface
- */
- virtual ~PixmapRenderSurface();
-
-public: // API
-
- /**
- * @copydoc Dali::ECore::EcoreXRenderSurface::GetDrawable()
- */
- virtual Ecore_X_Drawable GetDrawable();
-
- /**
- * @brief GetSurface
- *
- * @return pixmap
- */
- virtual Any GetSurface();
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender()
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
- virtual RenderSurface::Type GetSurfaceType();
-
-private:
-
- /**
- * Release any locks.
- */
- void ReleaseLock();
-
- /**
- * Create XPixmap
- */
- virtual void CreateXRenderable();
-
- /**
- * @copydoc Dali::Internal::Adaptor::ECore::RenderSurface::UseExistingRenderable
- */
- virtual void UseExistingRenderable( unsigned int surfaceId );
-
-private: // Data
-
- struct Impl;
- Impl* mImpl;
-};
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "accessibility-adaptor-impl-mobile.h"
-
-// EXTERNAL INCLUDES
-#include <vconf.h>
-
-#ifndef WAYLAND
-#include <Ecore_X.h>
-#include <Elementary.h>
-#endif
-
-#include <vconf.h>
-
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/events/gesture-requests.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-#include "system-settings.h"
-
-#ifndef WAYLAND
-#define MSG_DOMAIN_CONTROL_ACCESS static_cast< int >( ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL )
-#endif
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
-#endif
-
-const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
-
-bool GetEnabledVConf()
-{
- int isEnabled = 0;
- vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
-
- if( isEnabled == 0 )
- {
- vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
- }
-
- return bool( isEnabled );
-}
-
-
-void AccessibilityOnOffNotification(keynode_t* node, void* data)
-{
- AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
-
- bool isEnabled = GetEnabledVConf();
-
- DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
-
- if( isEnabled )
- {
- adaptor->EnableAccessibility();
- }
- else
- {
- adaptor->DisableAccessibility();
- }
-}
-
-} // unnamed namespace
-
-Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
-{
- Dali::AccessibilityAdaptor adaptor;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
- if(handle)
- {
- // If so, downcast the handle
- adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptorMobile() );
- AccessibilityAdaptorMobile& adaptorImpl = AccessibilityAdaptorMobile::GetImplementation( adaptor );
-
- bool isEnabled = GetEnabledVConf();
-
- if( isEnabled )
- {
- adaptorImpl.EnableAccessibility();
- }
- DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
-
- vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
- vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
-
- service.Register( typeid( adaptor ), adaptor );
- }
- }
-
- return adaptor;
-}
-
-void AccessibilityAdaptor::OnDestroy()
-{
- vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
- vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
-}
-
-AccessibilityAdaptorMobile::AccessibilityAdaptorMobile()
-{
-}
-
-bool AccessibilityAdaptorMobile::HandleActionNextEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionPreviousEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionActivateEvent()
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_ACTIVATE;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionActivate();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
-{
- bool ret = false;
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
-
- mReadPosition.x = x;
- mReadPosition.y = y;
-
- Dali::AccessibilityAdaptor handle( this );
-
- bool indicatorFocused = false;
-
- // Check whether the Indicator is focused
- if( mIndicator && mIndicator->IsConnected() )
- {
- // Check the position and size of Indicator actor
- Dali::Actor indicatorActor = mIndicator->GetActor();
- Vector3 position = Vector3(0.0f, 0.0f, 0.0f);
- Vector3 size = indicatorActor.GetCurrentSize();
-
- if(mReadPosition.x >= position.x &&
- mReadPosition.x <= position.x + size.width &&
- mReadPosition.y >= position.y &&
- mReadPosition.y <= position.y + size.height)
- {
- indicatorFocused = true;
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Indicator area!!!!\n", __FUNCTION__, __LINE__);
- }
- }
-
- if( mIndicator )
- {
- if( !mIndicatorFocused && indicatorFocused )
- {
- // If Indicator is focused, the focus should be cleared in Dali focus chain.
- if( mActionHandler )
- {
- mActionHandler->ClearAccessibilityFocus();
- }
- }
- else if( mIndicatorFocused && !indicatorFocused )
- {
-#ifndef WAYLAND
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_UNHIGHLIGHT;
-
- // Indicator should be unhighlighted
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send unhighlight message to indicator!!!!\n", __FUNCTION__, __LINE__);
-#endif
- }
-
- mIndicatorFocused = indicatorFocused;
-
- // Send accessibility READ action information to Indicator
- if( mIndicatorFocused )
- {
-#ifndef WAYLAND
- Elm_Access_Action_Info actionInfo;
- actionInfo.x = mReadPosition.x;
- actionInfo.y = mReadPosition.y;
-
- if(allowReadAgain)
- {
- actionInfo.action_type = ELM_ACCESS_ACTION_READ;
- }
- else
- {
- actionInfo.action_type = static_cast<Elm_Access_Action_Type>( GetElmAccessActionOver() );
- }
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send READ message to indicator!!!!\n", __FUNCTION__, __LINE__);
-#endif
- }
- }
-
- if( mActionHandler && !mIndicatorFocused)
- {
- // If Indicator is not focused, the accessibility actions should be handled by the registered
- // accessibility action handler (e.g. focus manager)
- ret = mActionHandler->AccessibilityActionRead(allowReadAgain);
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
- }
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionReadNextEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionReadPreviousEvent(bool allowEndFeedback)
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionUpEvent()
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_UP;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionUp();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-bool AccessibilityAdaptorMobile::HandleActionDownEvent()
-{
- bool ret = false;
-
-#ifndef WAYLAND
- if( mIndicator && mIndicatorFocused )
- {
- Elm_Access_Action_Info actionInfo;
- actionInfo.action_type = ELM_ACCESS_ACTION_DOWN;
-
- ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
- }
- else if( mActionHandler )
-#else
- if( mActionHandler )
-#endif
- {
- ret = mActionHandler->AccessibilityActionDown();
- }
-
- DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
-
- return ret;
-}
-
-AccessibilityAdaptorMobile::~AccessibilityAdaptorMobile()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
-#define __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <accessibility-adaptor.h>
-#include <accessibility-action-handler.h>
-#include <accessibility-gesture-handler.h>
-#include <indicator-interface.h>
-#include <accessibility-gesture-detector.h>
-#include <accessibility-adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * This mobile version is different since it forwards events to the indicator.
- */
-class AccessibilityAdaptorMobile : public AccessibilityAdaptor
-{
-public:
-
- /**
- * Constructor.
- */
- AccessibilityAdaptorMobile();
-
- // From AccessibilityAdaptor base class
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionNextEvent()
- */
- virtual bool HandleActionNextEvent( bool allowEndFeedback );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionPreviousEvent()
- */
- virtual bool HandleActionPreviousEvent( bool allowEndFeedback );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionActivateEvent()
- */
- virtual bool HandleActionActivateEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadEvent()
- */
- virtual bool HandleActionReadEvent( unsigned int x, unsigned int y, bool allowReadAgain );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadNextEvent()
- */
- virtual bool HandleActionReadNextEvent( bool allowEndFeedback );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPreviousEvent()
- */
- virtual bool HandleActionReadPreviousEvent( bool allowEndFeedback );
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionUpEvent()
- */
- virtual bool HandleActionUpEvent();
-
- /**
- * @copydoc Dali::AccessibilityAdaptor::HandleActionDownEvent()
- */
- virtual bool HandleActionDownEvent();
-
-private:
-
- /**
- * Destructor.
- */
- virtual ~AccessibilityAdaptorMobile();
-
- // Undefined
- AccessibilityAdaptorMobile( const AccessibilityAdaptorMobile& );
- AccessibilityAdaptorMobile& operator=( AccessibilityAdaptorMobile& );
-
-public:
-
- // Helpers for public-api forwarding methods
-
- inline static Internal::Adaptor::AccessibilityAdaptorMobile& GetImplementation(Dali::AccessibilityAdaptor& adaptor)
- {
- DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptorMobile handle is empty" );
-
- BaseObject& handle = adaptor.GetBaseObject();
-
- return static_cast<Internal::Adaptor::AccessibilityAdaptorMobile&>(handle);
- }
-
- inline static const Internal::Adaptor::AccessibilityAdaptorMobile& GetImplementation(const Dali::AccessibilityAdaptor& adaptor)
- {
- DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptorMobile handle is empty" );
-
- const BaseObject& handle = adaptor.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::AccessibilityAdaptorMobile&>(handle);
- }
-
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
+++ /dev/null
-# mobile profile internal files
-adaptor_common_internal_mobile_profile_src_files = \
- $(adaptor_mobile_dir)/accessibility-adaptor-impl-mobile.cpp \
- $(adaptor_mobile_dir)/mobile-system-settings.cpp \
- $(adaptor_mobile_dir)/mobile-color-controller-impl.cpp
-
-adaptor_common_internal_wayland_mobile_profile_src_files = \
- $(adaptor_mobile_dir)/native-render-surface-factory.cpp
-
-adaptor_common_internal_x_mobile_profile_src_files = \
- $(adaptor_mobile_dir)/pixmap-render-surface-factory.cpp
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <common/color-controller-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::ColorController ColorController::Get()
-{
- Dali::ColorController colorController;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ColorController ) );
- if(handle)
- {
- // If so, downcast the handle
- colorController = Dali::ColorController( dynamic_cast< ColorController* >( handle.GetObjectPtr() ) );
- }
- else
- {
- colorController = Dali::ColorController( new ColorController( ) );
- service.Register( typeid( colorController ), colorController );
- }
- }
-
- return colorController;
-
-}
-
-ColorController::ColorController()
-{
-}
-
-ColorController::~ColorController()
-{
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
-{
- return false;
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
-{
- return false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <system_settings.h>
-
-// INTERNAL INCLUDES
-#include <system-settings.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-int GetLongPressTime( int defaultTime )
-{
- return defaultTime;
-}
-
-int GetElmAccessActionOver()
-{
- return 0;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <native-render-surface.h>
-
-namespace Dali
-{
-
-DALI_EXPORT_API NativeRenderSurface* CreateNativeSurface(
- PositionSize positionSize,
- const std::string& name,
- bool isTransparent)
-{
- return new NativeRenderSurface( positionSize, name, isTransparent );
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <pixmap-render-surface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-DALI_EXPORT_API PixmapRenderSurface* CreatePixmapSurface(
- PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-{
- return new PixmapRenderSurface(positionSize, surface, name, isTransparent);
-}
-
-} // namespace ECoreX
-
-} // namespace Dali
-
-
-
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "application.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <application-impl.h>
-
-namespace Dali
-{
-
-Application Application::New()
-{
- return New( NULL, NULL );
-}
-
-Application Application::New( int* argc, char **argv[] )
-{
- Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
- if( internal )
- {
- if( argc && ( *argc > 0 ) )
- {
- internal->GetWindow().SetClass( (*argv)[0], "" );
- }
-
- return Application( internal.Get() );
- }
- else
- {
- internal = Internal::Adaptor::Application::New( argc, argv, "", OPAQUE, PositionSize(),
- Internal::Adaptor::Framework::NORMAL);
- return Application(internal.Get());
- }
-}
-
-Application Application::New( int* argc, char **argv[], const std::string& stylesheet )
-{
- Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
- if( internal )
- {
- if( argc && ( *argc > 0 ) )
- {
- internal->GetWindow().SetClass( (*argv)[0], "" );
- }
- internal->SetStyleSheet( stylesheet );
-
- return Application( internal.Get() );
- }
- else
- {
- internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, OPAQUE, PositionSize(),
- Internal::Adaptor::Framework::NORMAL);
- return Application(internal.Get());
- }
-}
-
-Application Application::New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode )
-{
- Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
- if( internal )
- {
- if( argc && ( *argc > 0 ) )
- {
- internal->GetWindow().SetClass( (*argv)[0], "" );
- }
- internal->SetStyleSheet( stylesheet );
-
- internal->GetWindow().SetTransparency( ( windowMode == Application::OPAQUE ? false : true ) );
-
- return Application( internal.Get() );
- }
- else
- {
- internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, windowMode, PositionSize(),
- Internal::Adaptor::Framework::NORMAL);
- return Application(internal.Get());
- }
-}
-
-Application Application::New( int* argc, char **argv[], const std::string& stylesheet, Application::WINDOW_MODE windowMode, PositionSize positionSize )
-{
- Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
- if( internal )
- {
- if( argc && ( *argc > 0 ) )
- {
- internal->GetWindow().SetClass( (*argv)[0], "" );
- }
- internal->SetStyleSheet( stylesheet );
-
- internal->GetWindow().SetTransparency( ( windowMode == Application::OPAQUE ? false : true ) );
- internal->GetWindow().SetSize( Window::WindowSize( positionSize.width, positionSize.height ) );
- internal->GetWindow().SetPosition( Window::WindowPosition( positionSize.x, positionSize.y ) );
-
- return Application( internal.Get() );
- }
- else
- {
- internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, windowMode, positionSize, Internal::Adaptor::Framework::NORMAL );
- return Application( internal.Get() );
- }
-}
-
-Application::~Application()
-{
-}
-
-Application::Application()
-{
-}
-
-Application::Application(const Application& application)
-: BaseHandle(application)
-{
-}
-
-Application& Application::operator=(const Application& application)
-{
- if( *this != application )
- {
- BaseHandle::operator=( application );
- }
- return *this;
-}
-
-void Application::MainLoop()
-{
- Internal::Adaptor::GetImplementation(*this).MainLoop(Configuration::APPLICATION_HANDLES_CONTEXT_LOSS);
-}
-
-void Application::MainLoop(Configuration::ContextLoss configuration)
-{
- Internal::Adaptor::GetImplementation(*this).MainLoop(configuration);
-}
-
-void Application::Lower()
-{
- Internal::Adaptor::GetImplementation(*this).Lower();
-}
-
-void Application::Quit()
-{
- Internal::Adaptor::GetImplementation(*this).Quit();
-}
-
-bool Application::AddIdle( CallbackBase* callback )
-{
- return Internal::Adaptor::GetImplementation(*this).AddIdle( callback );
-}
-
-Window Application::GetWindow()
-{
- return Internal::Adaptor::GetImplementation(*this).GetWindow();
-}
-
-void Application::ReplaceWindow(PositionSize windowPosition, const std::string& name)
-{
- Internal::Adaptor::GetImplementation(*this).ReplaceWindow(windowPosition, name);
-}
-
-std::string Application::GetResourcePath()
-{
- return Internal::Adaptor::Application::GetResourcePath();
-}
-
-std::string Application::GetRegion() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetRegion();
-}
-
-std::string Application::GetLanguage() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetLanguage();
-}
-
-void Application::SetViewMode( ViewMode viewMode )
-{
- Internal::Adaptor::GetImplementation(*this).SetViewMode( viewMode );
-}
-
-ViewMode Application::GetViewMode() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetViewMode();
-}
-
-void Application::SetStereoBase( float stereoBase )
-{
- Internal::Adaptor::GetImplementation(*this).SetStereoBase( stereoBase );
-}
-
-float Application::GetStereoBase() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetStereoBase();
-}
-
-Application::AppSignalType& Application::InitSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).InitSignal();
-}
-
-Application::AppSignalType& Application::TerminateSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).TerminateSignal();
-}
-
-Application::AppSignalType& Application::PauseSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).PauseSignal();
-}
-
-Application::AppSignalType& Application::ResumeSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).ResumeSignal();
-}
-
-Application::AppSignalType& Application::ResetSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).ResetSignal();
-}
-
-Application::AppSignalType& Application::ResizeSignal()
-{
- DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: ResizeSignal() is deprecated and will be removed from next release. Use Window::ResizedSignal() instead.\n" );
-
- return Internal::Adaptor::GetImplementation(*this).ResizeSignal();
-}
-
-Application::AppControlSignalType & Application::AppControlSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).AppControlSignal();
-}
-
-Application::AppSignalType& Application::LanguageChangedSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).LanguageChangedSignal();
-}
-
-Application::AppSignalType& Application::RegionChangedSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).RegionChangedSignal();
-}
-
-Application::AppSignalType& Application::BatteryLowSignal()
-{
- DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: BatteryLowSignal() is deprecated and will be removed from next release. Use Application::LowBatterySignal() instead.\n" );
- return Internal::Adaptor::GetImplementation(*this).BatteryLowSignal();
-}
-
-Application::AppSignalType& Application::MemoryLowSignal()
-{
- DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: MemoryLowSignal() is deprecated and will be removed from next release. Use Application::LowMemorySignal() instead.\n" );
- return Internal::Adaptor::GetImplementation(*this).MemoryLowSignal();
-}
-
-Application::LowBatterySignalType& Application::LowBatterySignal()
-{
- return Internal::Adaptor::GetImplementation(*this).LowBatterySignal();
-}
-
-Application::LowMemorySignalType& Application::LowMemorySignal()
-{
- return Internal::Adaptor::GetImplementation(*this).LowMemorySignal();
-}
-
-Application::Application(Internal::Adaptor::Application* application)
-: BaseHandle(application)
-{
-}
-
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_APPLICATION_H__
-#define __DALI_APPLICATION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/common/view-mode.h>
-#include <dali/public-api/object/base-handle.h>
-#include <dali/public-api/signals/callback.h>
-
-// INTERNAL INCLUDES
-#include "application-configuration.h"
-#include "device-status.h"
-#include "window.h"
-
-namespace Dali
-{
-/**
- * @addtogroup dali_adaptor_framework
- * @{
- */
-
-namespace Internal DALI_INTERNAL
-{
-namespace Adaptor
-{
-class Application;
-}
-}
-/**
- * @brief An Application class object should be created by every application
- * that wishes to use Dali.
- *
- * It provides a means for initializing the
- * resources required by the Dali::Core.
- *
- * The Application class emits several signals which the user can
- * connect to. The user should not create any Dali objects in the main
- * function and instead should connect to the Init signal of the
- * Application and create the Dali objects in the connected callback.
- *
- * Applications should follow the example below:
- *
- * @code
- * class ExampleController: public ConnectionTracker
- * {
- * public:
- * ExampleController( Application& application )
- * : mApplication( application )
- * {
- * mApplication.InitSignal().Connect( this, &ExampleController::Create );
- * }
- *
- * void Create( Application& application )
- * {
- * // Create Dali components...
- * }
- * ...
- * private:
- * Application& mApplication;
- * };
- *
- * int main (int argc, char **argv)
- * {
- * Application app = Application::New(&argc, &argv);
- * ExampleController example( app );
- * app.MainLoop();
- * }
- * @endcode
- *
- * If required, you can also connect class member functions to a signal:
- *
- * @code
- * MyApplication app;
- * app.ResumeSignal().Connect(&app, &MyApplication::Resume);
- * @endcode
- *
- * This class accepts command line arguments as well. The following options are supported:
- *
- * @code
- * --no-vsync Disable VSync on Render
- * -w|--width Stage Width
- * -h|--height Stage Height
- * -d|--dpi Emulated DPI
- * --help Help
- * @endcode
- *
- * When the above options are found, they are stripped from argv, and argc is updated appropriately.
- * @SINCE_1_0.0
- */
-class DALI_IMPORT_API Application : public BaseHandle
-{
-public:
-
- typedef Signal< void (DeviceStatus::Battery::Status) > LowBatterySignalType; ///< Application device signal type @SINCE_1_2.62
- typedef Signal< void (DeviceStatus::Memory::Status) > LowMemorySignalType; ///< Application device signal type @SINCE_1_2.62
- typedef Signal< void (Application&) > AppSignalType; ///< Application lifecycle signal and system signal callback type @SINCE_1_0.0
- typedef Signal< void (Application&, void *) > AppControlSignalType; ///< Application control signal callback type @SINCE_1_0.0
-
- /**
- * @brief Enumeration for deciding whether a Dali application window is opaque or transparent.
- * @SINCE_1_0.0
- */
- enum WINDOW_MODE
- {
- OPAQUE = 0, ///< The window will be opaque @SINCE_1_0.0
- TRANSPARENT = 1 ///< The window transparency will match the alpha value set in Dali::Stage::SetBackgroundcolor() @SINCE_1_0.0
- };
-
-public:
-
- /**
- * @brief This is the constructor for applications without an argument list.
- * @SINCE_1_0.0
- * @PRIVLEVEL_PUBLIC
- * @PRIVILEGE_DISPLAY
- * @return A handle to the Application
- */
- static Application New();
-
- /**
- * @brief This is the constructor for applications.
- *
- * @SINCE_1_0.0
- * @PRIVLEVEL_PUBLIC
- * @PRIVILEGE_DISPLAY
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- * @return A handle to the Application
- */
- static Application New( int* argc, char **argv[] );
-
- /**
- * @brief This is the constructor for applications with a name.
- *
- * @SINCE_1_0.0
- * @PRIVLEVEL_PUBLIC
- * @PRIVILEGE_DISPLAY
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @return A handle to the Application
- * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
- */
- static Application New( int* argc, char **argv[], const std::string& stylesheet );
-
- /**
- * @brief This is the constructor for applications with a name.
- *
- * @SINCE_1_0.0
- * @PRIVLEVEL_PUBLIC
- * @PRIVILEGE_DISPLAY
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of WINDOW_MODE
- * @return A handle to the Application
- * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
- */
- static Application New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
-
- /**
- * @brief This is the constructor for applications.
- *
- * @SINCE_1_2.60
- * @PRIVLEVEL_PUBLIC
- * @PRIVILEGE_DISPLAY
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of WINDOW_MODE
- * @param[in] positionSize A position and a size of the window
- * @return A handle to the Application
- * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
- */
- static Application New( int* argc, char **argv[], const std::string& stylesheet, Application::WINDOW_MODE windowMode, PositionSize positionSize );
-
- /**
- * @brief Constructs an empty handle.
- * @SINCE_1_0.0
- */
- Application();
-
- /**
- * @brief Copy Constructor.
- * @SINCE_1_0.0
- * @param[in] application Handle to an object
- */
- Application( const Application& application );
-
- /**
- * @brief Assignment operator.
- * @SINCE_1_0.0
- * @param[in] application Handle to an object
- * @return A reference to this
- */
- Application& operator=( const Application& application );
-
- /**
- * @brief Destructor.
- *
- * This is non-virtual since derived Handle types must not contain data or virtual methods.
- * @SINCE_1_0.0
- */
- ~Application();
-
-public:
- /**
- * @brief This starts the application.
- *
- * Choosing this form of main loop indicates that the default
- * application configuration of APPLICATION_HANDLES_CONTEXT_LOSS is used. On platforms where
- * context loss can occur, the application is responsible for tearing down and re-loading UI.
- * The application should listen to Stage::ContextLostSignal and Stage::ContextRegainedSignal.
- * @SINCE_1_0.0
- */
- void MainLoop();
-
- /**
- * @brief This starts the application, and allows the app to choose a different configuration.
- *
- * If the application plans on using the ReplaceSurface or ReplaceWindow API, then this will
- * trigger context loss & regain.
- * The application should listen to Stage::ContextLostSignal and Stage::ContextRegainedSignal.
- * @SINCE_1_0.0
- * @param[in] configuration The context loss configuration
- */
- void MainLoop(Configuration::ContextLoss configuration);
-
- /**
- * @brief This lowers the application to bottom without actually quitting it.
- * @SINCE_1_0.0
- */
- void Lower();
-
- /**
- * @brief This quits the application. Tizen applications should use Lower to improve re-start performance unless they need to Quit completely.
- * @SINCE_1_0.0
- */
- void Quit();
-
- /**
- * @brief Ensures that the function passed in is called from the main loop when it is idle.
- * @SINCE_1_0.0
- * @param[in] callback The function to call
- * @return @c true if added successfully, @c false otherwise
- *
- * @note Function must be called from main event thread only
- *
- * A callback of the following type may be used:
- * @code
- * void MyFunction();
- * @endcode
- *
- * @note Ownership of the callback is passed onto this class.
- */
- bool AddIdle( CallbackBase* callback );
-
- /**
- * @brief Retrieves the window used by the Application class.
- *
- * The application writer can use the window to change indicator and orientation
- * properties.
- * @SINCE_1_0.0
- * @return A handle to the window
- */
- Window GetWindow();
-
- /**
- * @brief Replaces the current window.
- *
- * This will force context loss.
- * If you plan on using this API in your application, then you should configure
- * it to prevent discard behavior when handling the Init signal.
- * @SINCE_1_0.0
- * @param[in] windowPosition The position and size parameters of the new window
- * @param[in] name The name of the new window
- */
- void ReplaceWindow(PositionSize windowPosition, const std::string& name);
-
- /**
- * @brief Get path application resources are stored at
- *
- * @SINCE_1_2.2
- * @return the full path of the resources
- */
- static std::string GetResourcePath();
-
- /**
- * @brief This is used to get region information from device.
- *
- * @SINCE_1_2.62
- * @return Region information
- */
- std::string GetRegion() const;
-
- /**
- * @brief This is used to get language information from device.
- *
- * @SINCE_1_2.62
- * @return Language information
- */
- std::string GetLanguage() const;
-
-public: // Stereoscopy
-
- /**
- * @brief Sets the viewing mode for the application.
- * @SINCE_1_0.0
- * @param[in] viewMode The new viewing mode
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @brief Gets the current viewing mode.
- * @SINCE_1_0.0
- * @return The current viewing mode
- */
- ViewMode GetViewMode() const;
-
- /**
- * @brief Sets the stereo base (eye separation) for Stereoscopic 3D.
- *
- * The stereo base is the distance in millimetres between the eyes. Typical values are
- * between 50mm and 70mm. The default value is 65mm.
- * @SINCE_1_0.0
- * @param[in] stereoBase The stereo base (eye separation) for Stereoscopic 3D
- */
- void SetStereoBase( float stereoBase );
-
- /**
- * @brief Gets the stereo base (eye separation) for Stereoscopic 3D.
- *
- * @SINCE_1_0.0
- * @return The stereo base (eye separation) for Stereoscopic 3D
- */
- float GetStereoBase() const;
-
-public: // Signals
-
- /**
- * @brief The user should connect to this signal to determine when they should initialize
- * their application.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& InitSignal();
-
- /**
- * @brief The user should connect to this signal to determine when they should terminate
- * their application.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& TerminateSignal();
-
- /**
- * @brief The user should connect to this signal if they need to perform any special
- * activities when the application is about to be paused.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& PauseSignal();
-
- /**
- * @brief The user should connect to this signal if they need to perform any special
- * activities when the application has resumed.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& ResumeSignal();
-
- /**
- * @brief This signal is sent when the system requires the user to reinitialize itself.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& ResetSignal();
-
- /**
- * @DEPRECATED_1_1.43 Use Window::ResizedSignal() instead.
- * @brief This signal is emitted when the window application rendering on is resized.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& ResizeSignal() DALI_DEPRECATED_API;
-
- /**
- * @brief This signal is emitted when another application sends a launch request to the application.
- *
- * When the application is launched, this signal is emitted after the main loop of the application starts up.
- * The passed parameter describes the launch request and contains the information about why the application is launched.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppControlSignalType& AppControlSignal();
-
- /**
- * @brief This signal is emitted when the language is changed on the device.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& LanguageChangedSignal();
-
- /**
- * @brief This signal is emitted when the region of the device is changed.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& RegionChangedSignal();
-
- /**
- * @DEPRECATED_1_2.62 Use LowBatterySignal() instead.
- * @brief This signal is emitted when the battery level of the device is low.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& BatteryLowSignal() DALI_DEPRECATED_API;
-
- /**
- * @DEPRECATED_1_2.62 Use LowMemorySignal() instead.
- * @brief This signal is emitted when the memory level of the device is low.
- * @SINCE_1_0.0
- * @return The signal to connect to
- */
- AppSignalType& MemoryLowSignal() DALI_DEPRECATED_API;
-
- /**
- * @brief This signal is emitted when the battery level of the device is low.
- * @SINCE_1_2.62
- * @return The signal to connect to
- */
- LowBatterySignalType& LowBatterySignal();
-
- /**
- * @brief This signal is emitted when the memory level of the device is low.
- * @SINCE_1_2.62
- * @return The signal to connect to
- */
- LowMemorySignalType& LowMemorySignal();
-
-public: // Not intended for application developers
- /// @cond internal
- /**
- * @brief Internal constructor.
- * @SINCE_1_0.0
- */
- explicit DALI_INTERNAL Application(Internal::Adaptor::Application* application);
- /// @endcond
-};
-
-/**
- * @}
- */
-} // namespace Dali
-
-#endif // __DALI_APPLICATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <key.h>
-
-// INTERNAL INCLUDES
-#include <key-impl.h>
-
-namespace Dali
-{
-
-bool IsKey( const KeyEvent& keyEvent, KEY daliKey)
-{
- return Internal::Adaptor::KeyLookup::IsKey( keyEvent, daliKey );
-}
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <native-image-source.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/any.h>
-
-// INTERNAL INCLUDES
-#include <native-image-source-impl.h>
-
-namespace Dali
-{
-
-NativeImageSourcePtr NativeImageSource::New( unsigned int width, unsigned int height, ColorDepth depth )
-{
- Any empty;
- NativeImageSourcePtr image = new NativeImageSource( width, height, depth, empty );
- return image;
-}
-
-Any NativeImageSource::GetNativeImageSource()
-{
- return mImpl->GetNativeImageSource();
-}
-
-NativeImageSourcePtr NativeImageSource::New( Any nativeImageSource )
-{
- NativeImageSourcePtr image = new NativeImageSource(0, 0, COLOR_DEPTH_DEFAULT, nativeImageSource);
- return image;
-}
-
-bool NativeImageSource::GetPixels( std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const
-{
- return mImpl->GetPixels( pixbuf, width, height, pixelFormat );
-}
-
-bool NativeImageSource::EncodeToFile(const std::string& filename) const
-{
- return mImpl->EncodeToFile(filename);
-}
-
-void NativeImageSource::SetSource( Any source )
-{
- mImpl->SetSource( source );
-}
-
-bool NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
-{
- return mImpl->IsColorDepthSupported( colorDepth );
-}
-
-bool NativeImageSource::GlExtensionCreate()
-{
- return mImpl->GlExtensionCreate();
-}
-
-void NativeImageSource::GlExtensionDestroy()
-{
- mImpl->GlExtensionDestroy();
-}
-
-unsigned int NativeImageSource::TargetTexture()
-{
- return mImpl->TargetTexture();
-}
-
-void NativeImageSource::PrepareTexture()
-{
- mImpl->PrepareTexture();
-}
-
-unsigned int NativeImageSource::GetWidth() const
-{
- return mImpl->GetWidth();
-}
-
-unsigned int NativeImageSource::GetHeight() const
-{
- return mImpl->GetHeight();
-}
-
-bool NativeImageSource::RequiresBlending() const
-{
- return mImpl->RequiresBlending();
-}
-
-NativeImageInterface::Extension* NativeImageSource::GetExtension()
-{
- return mImpl->GetNativeImageInterfaceExtension();
-}
-
-NativeImageSource::NativeImageSource( unsigned int width, unsigned int height, ColorDepth depth, Any nativeImageSource )
-{
- mImpl = Internal::Adaptor::NativeImageSource::New( width, height, depth, nativeImageSource );
-}
-
-NativeImageSource::~NativeImageSource()
-{
- delete mImpl;
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <timer.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-
-// INTERNAL INCLUDES
-#include <timer-impl.h>
-
-namespace Dali
-{
-
-Timer::Timer()
-{
-}
-
-Timer Timer::New( unsigned int milliSec )
-{
- Internal::Adaptor::TimerPtr internal = Internal::Adaptor::Timer::New( milliSec );
- return Timer(internal.Get());
-}
-
-Timer::Timer( const Timer& timer )
-: BaseHandle(timer)
-{
-}
-
-Timer& Timer::operator=( const Timer& timer )
-{
- // check self assignment
- if( *this != timer )
- {
- BaseHandle::operator=(timer);
- }
- return *this;
-}
-
-Timer::~Timer()
-{
-}
-
-Timer Timer::DownCast( BaseHandle handle )
-{
- return Timer( dynamic_cast<Internal::Adaptor::Timer*>( handle.GetObjectPtr() ) );
-}
-
-void Timer::Start()
-{
- Internal::Adaptor::GetImplementation(*this).Start();
-}
-
-void Timer::Stop()
-{
- Internal::Adaptor::GetImplementation(*this).Stop();
-}
-
-void Timer::SetInterval( unsigned int interval )
-{
- Internal::Adaptor::GetImplementation(*this).SetInterval( interval );
-}
-
-unsigned int Timer::GetInterval() const
-{
- return Internal::Adaptor::GetImplementation(*this).GetInterval();
-}
-
-bool Timer::IsRunning() const
-{
- return Internal::Adaptor::GetImplementation(*this).IsRunning();
-}
-
-Timer::TimerSignalType& Timer::TickSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).TickSignal();
-}
-
-Timer::Timer(Internal::Adaptor::Timer* timer)
-: BaseHandle(timer)
-{
-}
-
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <tts-player.h>
-
-// INTERNAL INCLUDES
-#include <tts-player-impl.h>
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-TtsPlayer::TtsPlayer()
-{
-}
-
-TtsPlayer TtsPlayer::Get(Dali::TtsPlayer::Mode mode)
-{
- TtsPlayer ttsPlayer;
-
- if ( Adaptor::IsAvailable() )
- {
- ttsPlayer = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetTtsPlayer(mode);
- }
-
- return ttsPlayer;
-}
-
-TtsPlayer::~TtsPlayer()
-{
-}
-
-TtsPlayer::TtsPlayer(const TtsPlayer& handle)
-: BaseHandle(handle)
-{
-}
-
-TtsPlayer& TtsPlayer::operator=(const TtsPlayer& rhs)
-{
- BaseHandle::operator=(rhs);
- return *this;
-}
-
-void TtsPlayer::Play(const std::string& text)
-{
- GetImplementation(*this).Play(text);
-}
-
-void TtsPlayer::Stop()
-{
- GetImplementation(*this).Stop();
-}
-
-void TtsPlayer::Pause()
-{
- GetImplementation(*this).Pause();
-}
-
-void TtsPlayer::Resume()
-{
- GetImplementation(*this).Resume();
-}
-
-TtsPlayer::State TtsPlayer::GetState()
-{
- return GetImplementation(*this).GetState();
-}
-
-TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal()
-{
- return GetImplementation(*this).StateChangedSignal();
-}
-
-TtsPlayer::TtsPlayer( Internal::Adaptor::TtsPlayer* player )
-: BaseHandle( player )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-application.h"
-
-// INTERNAL INCLUDES
-#include <widget-application-impl.h>
-
-namespace Dali
-{
-
-WidgetApplication WidgetApplication::New( int* argc, char **argv[], const std::string& stylesheet )
-{
- Internal::Adaptor::WidgetApplicationPtr internal = Internal::Adaptor::WidgetApplication::New( argc, argv, stylesheet);
- return WidgetApplication(internal.Get());
-}
-
-WidgetApplication::~WidgetApplication()
-{
-}
-
-WidgetApplication::WidgetApplication()
-{
-}
-
-WidgetApplication::WidgetApplication(const WidgetApplication& widgetApplication)
-: Application(widgetApplication)
-{
-}
-
-WidgetApplication& WidgetApplication::operator=(const WidgetApplication& widgetApplication)
-{
- if( *this != widgetApplication )
- {
- BaseHandle::operator=( widgetApplication );
- }
- return *this;
-}
-
-void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, CreateWidgetFunction createFunction )
-{
- Internal::Adaptor::GetImplementation(*this).RegisterWidgetCreatingFunction( widgetName, createFunction );
-}
-
-WidgetApplication::WidgetApplication(Internal::Adaptor::WidgetApplication* widgetApplication)
-: Application(widgetApplication)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_WIDGET_APPLICATION_H
-#define DALI_WIDGET_APPLICATION_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#ifdef DALI_ADAPTOR_COMPILATION // full path doesn't exist until adaptor is installed so we have to use relative
-#include <application.h>
-#else
-#include <dali/public-api/adaptor-framework/application.h>
-#endif
-namespace Dali
-{
-
-namespace Internal DALI_INTERNAL
-{
-
-namespace Adaptor
-{
-class WidgetApplication;
-}
-
-}
-
-class Widget;
-
-/**
- * @brief An WidgetApplication class object should be created by every widget application
- * that wishes to use Dali.
- *
- * It provides a means for initializing the
- * resources required by the Dali::Core.
- *
- * The WidgetApplication class emits several signals which the user can
- * connect to. The user should not create any Dali objects in the main
- * function and instead should connect to the Init signal of the
- * WidgetApplication and create the Dali Widget object in the connected callback.
- *
- * WidgetApplications should follow the example below:
- *
- * @code
- *
- * //Widget header which
- * #include <my-widget.h>
- *
- * class ExampleController: public ConnectionTracker
- * {
- * public:
- * ExampleController( Application& application )
- * : mWidgetApplication( application )
- * {
- * mApplication.InitSignal().Connect( this, &ExampleController::Create );
- * }
- *
- * static Widget CreateWidgetFunction(const std::string& widgetName)
- * {
- * MyWidget widget = MyWidget::New();
- * return widget;
- * }
- *
- * void Create( Application& application )
- * {
- * mApplication.RegisterWidgetCreatingFunction( "myWidget", &ExampleController::CreateWidgetFunction );
- * }
- *
- * private:
- * WidgetApplication& mWidgetApplication;
- * };
- *
- * int main (int argc, char **argv)
- * {
- * WidgetApplication app = WidgetApplication::New(&argc, &argv);
- * ExampleController example( app );
- * app.MainLoop();
- * }
- * @endcode
- *
- * If required, you can also connect class member functions to a signal:
- *
- * @code
- * MyWidgetApplication app;
- * app.ResumeSignal().Connect(&app, &MyWidgetApplication::Resume);
- * @endcode
- *
- * @SINCE_1_3_5
- */
-class DALI_IMPORT_API WidgetApplication : public Application
-{
-public:
-
- /**
- * @brief This is the typedef for Widget creator.
- * @SINCE_1_3_5
- */
- typedef Widget(*CreateWidgetFunction)(const std::string&);
-
-public:
-
- /**
- * @brief This is the constructor for WidgetApplications with a name.
- *
- * @SINCE_1_3_5
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @return A handle to the WidgetApplication
- * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
- */
- static WidgetApplication New( int* argc, char **argv[], const std::string& stylesheet );
-
- /**
- * @brief The default constructor.
- * @SINCE_1_3_5
- */
- WidgetApplication();
-
- /**
- * @brief Copy Constructor.
- *
- * @SINCE_1_3_5
- * @param[in] widgetApplication Handle to an object
- */
- WidgetApplication( const WidgetApplication& widgetApplication );
-
- /**
- * @brief Assignment operator.
- *
- * @SINCE_1_3_5
- * @param[in] widgetApplication Handle to an object
- * @return A reference to this
- */
- WidgetApplication& operator=( const WidgetApplication& widgetApplication );
-
- /**
- * @brief Destructor
- * @SINCE_1_3_5
- */
- ~WidgetApplication();
-
- /**
- * @brief Register create function for widget.
- *
- * @SINCE_1_3_5
- * @param[in] widgetName Name of widget
- * @param[in] createFunction Function pointer for widget creation.
- */
- void RegisterWidgetCreatingFunction( const std::string& widgetName, CreateWidgetFunction createFunction );
-
-public: // Not intended for application developers
- /// @cond internal
- /**
- * @brief Internal constructor.
- */
- explicit DALI_INTERNAL WidgetApplication(Internal::Adaptor::WidgetApplication* widgetApplication);
- /// @endcond
-};
-
-} // namespace Dali
-
-#endif // DALI_WIDGET_APPLICATION_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-impl.h"
-
-// INTERNAL INCLUDES
-#include <window.h>
-#include <widget-controller.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-WidgetPtr Widget::New()
-{
- return new Widget();
-}
-
-Widget::Widget()
-: mImpl( nullptr )
-{
-}
-
-Widget::~Widget()
-{
- if( mImpl != nullptr )
- {
- delete mImpl;
- }
-}
-
-void Widget::OnCreate( const std::string& contentInfo, Dali::Window window )
-{
-}
-
-void Widget::OnTerminate( const std::string& contentInfo, Dali::Widget::Termination type )
-{
-}
-
-void Widget::OnPause()
-{
-}
-
-void Widget::OnResume()
-{
-}
-
-void Widget::OnResize( Dali::Window window )
-{
-}
-
-void Widget::OnUpdate( const std::string& contentInfo, int force )
-{
-}
-
-void Widget::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
-{
- mImpl->SignalConnected( slotObserver, callback );
-}
-
-void Widget::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
-{
- mImpl->SignalDisconnected( slotObserver, callback );
-}
-
-void Widget::SetContentInfo( const std::string& contentInfo )
-{
- if( mImpl != nullptr )
- {
- mImpl->SetContentInfo( contentInfo );
- }
-}
-
-void Widget::SetImpl( Impl* impl )
-{
- mImpl = impl;
-}
-
-Internal::Adaptor::Widget& GetImplementation(Dali::Widget& widget)
-{
- DALI_ASSERT_ALWAYS(widget && "widget handle is empty");
-
- BaseObject& handle = widget.GetBaseObject();
-
- return static_cast<Internal::Adaptor::Widget&>(handle);
-}
-
-const Internal::Adaptor::Widget& GetImplementation(const Dali::Widget& widget)
-{
- const BaseObject& handle = widget.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::Widget&>(handle);
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_WIDGET_H
-#define DALI_INTERNAL_WIDGET_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
-#include <dali/public-api/signals/connection-tracker-interface.h>
-
-// INTERNAL INCLUDES
-#include "widget.h"
-
-namespace Dali
-{
-class Window;
-
-/**
- * @addtogroup dali_adaptor_framework
- * @{
- */
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class Widget;
-typedef IntrusivePtr<Widget> WidgetPtr;
-
-/**
- * @brief This is the internal base class of custom widget.
- *
- * It will provides several widget instance lifecycle virtual functions
- * which the user can override.
- *
- * User should override OnCreate function and create scene for custom widget.
- *
- * Plus, Implements ConnectionTrackerInterface so that signals (typically connected to member functions) will
- * be disconnected automatically when the control is destroyed.
- *
- * @SINCE_1_3_5
- */
-class DALI_IMPORT_API Widget : public BaseObject, public ConnectionTrackerInterface
-{
-public:
-
- /**
- * @brief Creates a new WidgetImpl instance.
- *
- * @SINCE_1_3_5
- * @return A handle to the WidgetImpl instance
- */
- static WidgetPtr New();
-
- /**
- * @brief The user should override this function to determine when they create widget.
- *
- * @SINCE_1_3_5
- * @param[in] contentInfo Information from WidgetView for creating. It contains previous status of widget which is sent by SetContentInfo before.
- * @param[in] window Window handle for widget
- */
- virtual void OnCreate( const std::string& contentInfo, Dali::Window window );
-
- /**
- * @brief The user should override this function to determine when they terminate widget.
- *
- * @SINCE_1_3_5
- * @param[in] contentInfo Data from WidgetView for deleting
- * @param[in] type Termination type. When user delete widget view, termination type is PERMANENT.
- */
- virtual void OnTerminate( const std::string& contentInfo, Dali::Widget::Termination type );
-
- /**
- * @brief The user should override this function to determine when they pause widget.
- * @SINCE_1_3_5
- */
- virtual void OnPause();
-
- /**
- * @brief The user should override this function to determine when they resume widget.
- * @SINCE_1_3_5
- */
- virtual void OnResume();
-
- /**
- * @brief The user should override this function to determine when they resize widget.
- *
- * @SINCE_1_3_5
- * @param[in] window Window handle for widget
- */
- virtual void OnResize( Dali::Window window );
-
- /**
- * @brief The user should override this function to determine when they update widget.
- *
- * @SINCE_1_3_5
- * @param[in] contentInfo Data from WidgetView for updating
- * @param[in] force Although the widget is paused, if it is true, the widget can be updated
- */
- virtual void OnUpdate( const std::string& contentInfo, int force );
-
- // From ConnectionTrackerInterface
-
- /**
- * @copydoc ConnectionTrackerInterface::SignalConnected
- */
- virtual void SignalConnected( SlotObserver* slotObserver, CallbackBase* callback );
-
- /**
- * @copydoc ConnectionTrackerInterface::SignalDisconnected
- */
- virtual void SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback );
-
- /**
- * @brief Set content info to WidgetView.
- *
- * @SINCE_1_3_5
- * @param[in] contentInfo Content info is kind of context information which contains current status of widget.
- */
- void SetContentInfo( const std::string& contentInfo );
-
-protected:
-
- /**
- * @brief WidgetImpl constructor
- */
- Widget();
-
- /**
- * @brief Virtual destructor
- */
- virtual ~Widget();
-
- /// @cond internal
-public:
- class Impl; // Class declaration is public so we can internally add devel API's to the WidgetImpl
-
- /*
- * Set pointer of WidgetImpl Internal.
- * @SINCE_1_3_5
- */
- void SetImpl( Widget::Impl* impl );
-
-private:
- Impl* mImpl;
-
- // Undefined
- DALI_INTERNAL Widget(const Widget&);
- DALI_INTERNAL Widget& operator=(Widget&);
- /// @endcond
-
-};
-
-/**
- * @brief Gets implementation from the handle.
- *
- * @SINCE_1_3_5
- * @param handle
- * @return Implementation
- * @pre handle is initialized and points to a widget
- */
-DALI_IMPORT_API Internal::Adaptor::Widget& GetImplementation( Dali::Widget& widget );
-
-/**
- * @brief Gets implementation from the handle.
- *
- * @SINCE_1_3_5
- * @param handle
- * @return Implementation
- * @pre Handle is initialized and points to a widget.
- */
-DALI_IMPORT_API const Internal::Adaptor::Widget& GetImplementation( const Dali::Widget& widget );
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-/**
- * @}
- */
-
-} // namespace Dali
-#endif // DALI_INTERNAL_WIDGET_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget.h"
-
-// INTERNAL INCLUDES
-#include <widget-impl.h>
-
-namespace Dali
-{
-
-Widget Widget::New()
-{
- Internal::Adaptor::WidgetPtr internal = Internal::Adaptor::Widget::New();
- return Widget(internal.Get());
-}
-
-Widget::~Widget()
-{
-}
-
-Widget::Widget()
-{
-}
-
-Widget::Widget(const Widget& widget)
-: BaseHandle(widget)
-{
-}
-
-Widget& Widget::operator=(const Widget& widget)
-{
- if( *this != widget )
- {
- BaseHandle::operator=( widget );
- }
- return *this;
-}
-
-Widget::Widget(Internal::Adaptor::Widget* widget)
-: BaseHandle(widget)
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <window.h>
-
-// INTERNAL INCLUDES
-#include <window-impl.h>
-#include <orientation-impl.h>
-
-namespace Dali
-{
-
-Window Window::New(PositionSize posSize, const std::string& name, bool isTransparent)
-{
- Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, "", isTransparent);
- return Window(window);
-}
-
-Window Window::New(PositionSize posSize, const std::string& name, const std::string& className, bool isTransparent)
-{
- Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, className, isTransparent);
- return Window(window);
-}
-
-Window::Window()
-{
-}
-
-Window::~Window()
-{
-}
-
-Window::Window(const Window& handle)
-: BaseHandle(handle)
-{
-}
-
-Window& Window::operator=(const Window& rhs)
-{
- BaseHandle::operator=(rhs);
- return *this;
-}
-
-void Window::ShowIndicator( IndicatorVisibleMode visibleMode )
-{
- GetImplementation(*this).ShowIndicator( visibleMode );
-}
-
-Window::IndicatorSignalType& Window::IndicatorVisibilityChangedSignal()
-{
- return GetImplementation(*this).IndicatorVisibilityChangedSignal();
-}
-
-void Window::SetIndicatorBgOpacity( IndicatorBgOpacity opacity )
-{
- GetImplementation(*this).SetIndicatorBgOpacity( opacity );
-}
-
-void Window::RotateIndicator( WindowOrientation orientation )
-{
- GetImplementation(*this).RotateIndicator( orientation );
-}
-
-void Window::SetClass( std::string name, std::string klass )
-{
- GetImplementation(*this).SetClass( name, klass );
-}
-
-void Window::Raise()
-{
- GetImplementation(*this).Raise();
-}
-
-void Window::Lower()
-{
- GetImplementation(*this).Lower();
-}
-
-void Window::Activate()
-{
- GetImplementation(*this).Activate();
-}
-
-void Window::AddAvailableOrientation( WindowOrientation orientation )
-{
- GetImplementation(*this).AddAvailableOrientation( orientation );
-}
-
-void Window::RemoveAvailableOrientation( WindowOrientation orientation )
-{
- GetImplementation(*this).RemoveAvailableOrientation( orientation );
-}
-
-void Window::SetPreferredOrientation( Dali::Window::WindowOrientation orientation )
-{
- GetImplementation(*this).SetPreferredOrientation( orientation );
-}
-
-Dali::Window::WindowOrientation Window::GetPreferredOrientation()
-{
- return GetImplementation(*this).GetPreferredOrientation();
-}
-
-DragAndDropDetector Window::GetDragAndDropDetector() const
-{
- return GetImplementation(*this).GetDragAndDropDetector();
-}
-
-Any Window::GetNativeHandle() const
-{
- return GetImplementation(*this).GetNativeHandle();
-}
-
-Window::FocusSignalType& Window::FocusChangedSignal()
-{
- return GetImplementation(*this).FocusChangedSignal();
-}
-
-void Window::SetAcceptFocus( bool accept )
-{
- GetImplementation(*this).SetAcceptFocus( accept );
-}
-
-bool Window::IsFocusAcceptable() const
-{
- return GetImplementation(*this).IsFocusAcceptable();
-}
-
-void Window::Show()
-{
- GetImplementation(*this).Show();
-}
-
-void Window::Hide()
-{
- GetImplementation(*this).Hide();
-}
-
-bool Window::IsVisible() const
-{
- return GetImplementation(*this).IsVisible();
-}
-
-unsigned int Window::GetSupportedAuxiliaryHintCount() const
-{
- return GetImplementation(*this).GetSupportedAuxiliaryHintCount();
-}
-
-std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
-{
- return GetImplementation(*this).GetSupportedAuxiliaryHint( index );
-}
-
-unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
-{
- return GetImplementation(*this).AddAuxiliaryHint( hint, value );
-}
-
-bool Window::RemoveAuxiliaryHint( unsigned int id )
-{
- return GetImplementation(*this).RemoveAuxiliaryHint( id );
-}
-
-bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
-{
- return GetImplementation(*this).SetAuxiliaryHintValue( id, value );
-}
-
-std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
-{
- return GetImplementation(*this).GetAuxiliaryHintValue( id );
-}
-
-unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
-{
- return GetImplementation(*this).GetAuxiliaryHintId( hint );
-}
-
-void Window::SetInputRegion( const Rect< int >& inputRegion )
-{
- return GetImplementation(*this).SetInputRegion( inputRegion );
-}
-
-void Window::SetType( Window::Type type )
-{
- GetImplementation(*this).SetType( type );
-}
-
-Window::Type Window::GetType() const
-{
- return GetImplementation(*this).GetType();
-}
-
-bool Window::SetNotificationLevel( Window::NotificationLevel::Type level )
-{
- return GetImplementation(*this).SetNotificationLevel( level );
-}
-
-Window::NotificationLevel::Type Window::GetNotificationLevel() const
-{
- return GetImplementation(*this).GetNotificationLevel();
-}
-
-void Window::SetOpaqueState( bool opaque )
-{
- GetImplementation(*this).SetOpaqueState( opaque );
-}
-
-bool Window::IsOpaqueState() const
-{
- return GetImplementation(*this).IsOpaqueState();
-}
-
-bool Window::SetScreenOffMode(Window::ScreenOffMode::Type screenMode)
-{
- return GetImplementation(*this).SetScreenOffMode(screenMode);
-}
-
-Window::ScreenOffMode::Type Window::GetScreenOffMode() const
-{
- return GetImplementation(*this).GetScreenOffMode();
-}
-
-bool Window::SetBrightness( int brightness )
-{
- return GetImplementation(*this).SetBrightness( brightness );
-}
-
-int Window::GetBrightness() const
-{
- return GetImplementation(*this).GetBrightness();
-}
-
-Window::ResizedSignalType& Window::ResizedSignal()
-{
- return GetImplementation(*this).ResizedSignal();
-}
-
-void Window::SetSize( Window::WindowSize size )
-{
- GetImplementation(*this).SetSize( size );
-}
-
-Window::WindowSize Window::GetSize() const
-{
- return GetImplementation(*this).GetSize();
-}
-
-void Window::SetPosition( Window::WindowPosition position )
-{
- GetImplementation(*this).SetPosition( position );
-}
-
-Window::WindowPosition Window::GetPosition() const
-{
- return GetImplementation(*this).GetPosition();
-}
-
-void Window::SetTransparency( bool transparent )
-{
- GetImplementation(*this).SetTransparency( transparent );
-}
-
-Window::Window( Internal::Adaptor::Window* window )
-: BaseHandle( window )
-{
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// HEADER
-#include <dali-adaptor-version.h>
-
-// EXTERNAL INCLUDES
-#ifdef DEBUG_ENABLED
-#include <iostream>
-#endif
-
-namespace Dali
-{
-
-const unsigned int ADAPTOR_MAJOR_VERSION = 1;
-const unsigned int ADAPTOR_MINOR_VERSION = 3;
-const unsigned int ADAPTOR_MICRO_VERSION = 7;
-const char * const ADAPTOR_BUILD_DATE = __DATE__ " " __TIME__;
-
-#ifdef DEBUG_ENABLED
-namespace
-{
-/// Allows the printing of the version number ONLY when debug is enabled
-struct PrintVersion
-{
- PrintVersion()
- {
- std::cerr << "DALi Adaptor: " << ADAPTOR_MAJOR_VERSION << "." << ADAPTOR_MINOR_VERSION << "." << ADAPTOR_MICRO_VERSION << " (" << ADAPTOR_BUILD_DATE << ")" << std::endl;
- }
-};
-PrintVersion ADAPTOR_VERSION;
-} // unnamed namespace
-#endif
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_H__
-#define __DALI_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <dali/public-api/dali-core.h>
-
-// Application / UI Framework adaption
-#include <dali/public-api/adaptor-framework/application.h>
-#include <dali/public-api/adaptor-framework/device-status.h>
-#include <dali/public-api/adaptor-framework/input-method.h>
-#include <dali/public-api/adaptor-framework/key.h>
-#include <dali/public-api/adaptor-framework/timer.h>
-#include <dali/public-api/adaptor-framework/tts-player.h>
-#include <dali/public-api/adaptor-framework/native-image-source.h>
-#include <dali/public-api/adaptor-framework/widget-application.h>
-#include <dali/public-api/adaptor-framework/widget.h>
-#include <dali/public-api/adaptor-framework/widget-impl.h>
-#include <dali/public-api/dali-adaptor-version.h>
-
-#endif //__DALI_H__
+++ /dev/null
-public_api_src_files = \
- $(adaptor_public_api_dir)/adaptor-framework/application.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/key.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/window.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/timer.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/tts-player.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/native-image-source.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/widget.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/widget-impl.cpp \
- $(adaptor_public_api_dir)/adaptor-framework/widget-application.cpp \
- $(adaptor_public_api_dir)/dali-adaptor-version.cpp
-
-
-public_api_header_files = \
- $(adaptor_public_api_dir)/dali-adaptor-version.h
-
-
-public_api_adaptor_framework_header_files = \
- $(adaptor_public_api_dir)/adaptor-framework/application.h \
- $(adaptor_public_api_dir)/adaptor-framework/application-configuration.h \
- $(adaptor_public_api_dir)/adaptor-framework/device-status.h \
- $(adaptor_public_api_dir)/adaptor-framework/input-method.h \
- $(adaptor_public_api_dir)/adaptor-framework/key.h \
- $(adaptor_public_api_dir)/adaptor-framework/style-change.h \
- $(adaptor_public_api_dir)/adaptor-framework/timer.h \
- $(adaptor_public_api_dir)/adaptor-framework/tts-player.h \
- $(adaptor_public_api_dir)/adaptor-framework/native-image-source.h \
- $(adaptor_public_api_dir)/adaptor-framework/window.h \
- $(adaptor_public_api_dir)/adaptor-framework/widget.h \
- $(adaptor_public_api_dir)/adaptor-framework/widget-impl.h \
- $(adaptor_public_api_dir)/adaptor-framework/widget-application.h
-
-adaptor_dali_header_file = \
- $(adaptor_public_api_dir)/dali.h
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "accessibility-adaptor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <vconf.h>
-
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-#include <system-settings.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
-
-// Disabled Accessibility temporarily in Tizen platform
-bool GetEnabledVConf()
-{
- int isEnabled = 0;
- //vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
-
- if( isEnabled == 0 )
- {
- //vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
- }
-
- return static_cast<bool>(isEnabled);
-}
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR" );
-#endif
-
-void AccessibilityOnOffNotification(keynode_t* node, void* data)
-{
- AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
-
- bool isEnabled = GetEnabledVConf();
-
- DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
-
- if( isEnabled )
- {
- adaptor->EnableAccessibility();
- }
- else
- {
- adaptor->DisableAccessibility();
- }
-}
-
-} // unnamed namespace
-
-Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
-{
- Dali::AccessibilityAdaptor adaptor;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
- if(handle)
- {
- // If so, downcast the handle
- adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptor() );
- AccessibilityAdaptor& adaptorImpl = AccessibilityAdaptor::GetImplementation( adaptor );
-
- bool isEnabled = GetEnabledVConf();
-
- if( isEnabled )
- {
- adaptorImpl.EnableAccessibility();
- }
- DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
-
- vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
- vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
-
- service.Register( typeid( adaptor ), adaptor );
- }
- }
-
- return adaptor;
-}
-
-void AccessibilityAdaptor::OnDestroy()
-{
- vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
- vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <adaptor-impl.h>
-
-// EXTERNAL INCLUDES
-#include <app_common.h>
-#ifdef APPCORE_WATCH_AVAILABLE
-#include <screen_connector_provider.h>
-#include <ecore-wl-render-surface.h>
-#endif
-
-#include <system_settings.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-static void OnSystemLanguageChanged( system_settings_key_e key, void* data )
-{
- char* locale = NULL;
- if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE ||
- locale == NULL )
- {
- DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " );
- return;
- }
-
- Adaptor* adaptor = static_cast< Adaptor* >( data );
- if( adaptor != NULL )
- {
- adaptor->SetRootLayoutDirection( locale );
- }
-
- free( locale );
-}
-
-} // namesapce
-
-void Adaptor::GetDataStoragePath( std::string& path)
-{
-#ifdef USE_APPFW
- char *pathInt = app_get_data_path();
- if ( pathInt )
- {
- path = pathInt;
- free( pathInt );
- }
- else
- {
- path = "";
- }
-#endif
-
-}
-
-void Adaptor::GetAppId( std::string& appId )
-{
-#ifdef USE_APPFW
- char *id;
- app_get_id(&id);
- if ( id )
- {
- appId = id;
- }
- else
- {
- appId = "";
- }
-#endif
-}
-
-void Adaptor::SurfaceInitialized()
-{
-#ifdef APPCORE_WATCH_AVAILABLE
- if ( !mUseRemoteSurface )
- {
- return;
- }
- char *appId;
- app_get_id(&appId);
-
- Ecore_Wl_Window* ecoreWlWindow = AnyCast<Ecore_Wl_Window*>( mNativeWindow );
- screen_connector_provider_remote_enable(appId, ecore_wl_window_surface_get(ecoreWlWindow));
-#endif
-}
-
-void Adaptor::SetupSystemInformation()
-{
- if( system_settings_set_changed_cb( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, OnSystemLanguageChanged, this ) != SYSTEM_SETTINGS_ERROR_NONE )
- {
- DALI_LOG_ERROR( "DALI system_settings_set_changed_cb failed.\n" );
- return;
- }
-
- char* locale = NULL;
- if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE ||
- locale == NULL )
- {
- DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " );
- return;
- }
-
- SetRootLayoutDirection( locale );
-
- free( locale );
-
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <display-connection-impl.h>
-
-// EXTERNAL_HEADERS
-#include <tbm_bufmgr.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL HEADERS
-#include <native-render-surface.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-EGLNativeDisplayType DisplayConnection::GetNativeDisplay()
-{
- return reinterpret_cast< EGLNativeDisplayType >( tbm_bufmgr_init( -1 ) );
-}
-
-void DisplayConnection::ReleaseNativeDisplay()
-{
- if( mDisplay )
- {
- tbm_bufmgr_deinit( reinterpret_cast< tbm_bufmgr >( mDisplay ) );
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-# tizen
-
-adaptor_tizen_internal_src_files = \
- $(adaptor_tizen_dir)/adaptor-impl-tizen.cpp \
- $(adaptor_tizen_dir)/vsync-monitor-tizen.cpp \
- $(adaptor_tizen_dir)/tilt-sensor-impl-tizen.cpp \
- $(adaptor_tizen_dir)/tts-player-impl-tizen.cpp \
- $(adaptor_tizen_dir)/widget-application-impl-tizen-3.cpp \
- $(adaptor_tizen_dir)/widget-controller-tizen-3.cpp
-
-# common to tizen platforms except not for mobile
-adaptor_tizen_internal_non_mobile_src_files = \
- $(adaptor_tizen_dir)/accessibility-adaptor-impl-tizen.cpp
-
-adaptor_tizen_framework_efl_src_files = $(adaptor_tizen_dir)/framework-tizen-3.cpp
-
-adaptor_tizen_internal_egl_extension_src_files = \
- $(adaptor_tizen_dir)/gl/egl-image-extensions-tizen.cpp
-
-adaptor_tizen_internal_native_image_src_files = \
- $(adaptor_tizen_dir)/display-connection-impl-tizen.cpp \
- $(adaptor_tizen_dir)/native-render-surface-tizen.cpp \
- $(adaptor_tizen_dir)/native-image-source-impl-tizen.cpp
-
-public_api_adaptor_tizen_header_files = \
- $(adaptor_tizen_dir)/key-grab.h
+++ /dev/null
-# tizen
-
-adaptor_tizen_internal_src_files = \
- $(adaptor_tizen_dir)/adaptor-impl-tizen.cpp \
- $(adaptor_tizen_dir)/vsync-monitor-tizen.cpp \
- $(adaptor_tizen_dir)/tilt-sensor-impl-tizen.cpp \
- $(adaptor_tizen_dir)/tts-player-impl-tizen.cpp \
- $(adaptor_tizen_dir)/widget-application-impl-tizen.cpp \
- $(adaptor_tizen_dir)/widget-controller-tizen.cpp
-
-# common to tizen platforms except not for mobile
-adaptor_tizen_internal_non_mobile_src_files = \
- $(adaptor_tizen_dir)/accessibility-adaptor-impl-tizen.cpp
-
-adaptor_tizen_framework_efl_src_files = $(adaptor_tizen_dir)/framework-tizen.cpp
-
-adaptor_tizen_internal_egl_extension_src_files = \
- $(adaptor_tizen_dir)/gl/egl-image-extensions-tizen.cpp
-
-adaptor_tizen_internal_native_image_src_files = \
- $(adaptor_tizen_dir)/display-connection-impl-tizen.cpp \
- $(adaptor_tizen_dir)/native-render-surface-tizen.cpp \
- $(adaptor_tizen_dir)/native-image-source-impl-tizen.cpp
-
-public_api_adaptor_tizen_header_files = \
- $(adaptor_tizen_dir)/key-grab.h
-
-adaptor_tizen_internal_capture_src_files = \
- $(adaptor_tizen_dir)/capture-impl-tizen.cpp
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "framework.h"
-
-// EXTERNAL INCLUDES
-#include <app.h>
-#include <bundle.h>
-#include <Ecore.h>
-
-#include <system_info.h>
-#include <system_settings.h>
-#include <app_control_internal.h>
-#include <bundle_internal.h>
-
-// CONDITIONAL INCLUDES
-#ifdef APPCORE_WATCH_AVAILABLE
-#include <appcore-watch/watch_app.h>
-#endif
-#ifdef DALI_ELDBUS_AVAILABLE
-#include <Eldbus.h>
-#endif // DALI_ELDBUS_AVAILABLE
-
-#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
-#include <tzplatform_config.h>
-#endif // TIZEN_PLATFORM_CONFIG_SUPPORTED
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <callback-manager.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-namespace
-{
-Integration::Log::Filter* gDBusLogging = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DBUS" );
-} // anonymous namespace
-#endif
-
-/**
- * Impl to hide EFL data members
- */
-struct Framework::Impl
-{
-// Constructor
- Impl(void* data, Type type )
- : mAbortCallBack( NULL ),
- mCallbackManager( NULL ),
- mEventCallback()
-#ifdef APPCORE_WATCH_AVAILABLE
- , mWatchCallback()
-#endif
- {
- mFramework = static_cast<Framework*>(data);
-
-#ifndef APPCORE_WATCH_AVAILABLE
- if ( type == WATCH )
- {
- throw Dali::DaliException( "", "Watch Application is not supported." );
- }
-#endif
- mApplicationType = type;
- mCallbackManager = CallbackManager::New();
-
- char* region;
- char* language;
- system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_COUNTRY, ®ion );
- system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &language );
- mRegion = std::string( region );
- mLanguage = std::string( language );
- }
-
- ~Impl()
- {
- delete mAbortCallBack;
-
- // we're quiting the main loop so
- // mCallbackManager->RemoveAllCallBacks() does not need to be called
- // to delete our abort handler
- delete mCallbackManager;
- }
-
- int AppMain()
- {
- int ret;
-
- if (mApplicationType == NORMAL)
- {
- ret = AppNormalMain();
- }
- else
- {
- ret = AppWatchMain();
- }
- return ret;
- }
-
- void AppExit()
- {
- if (mApplicationType == NORMAL)
- {
- AppNormalExit();
- }
- else
- {
- AppWatchExit();
- }
- }
-
- std::string GetLanguage() const
- {
- return mLanguage;
- }
-
- std::string GetRegion() const
- {
- return mRegion;
- }
-
- // Data
- Type mApplicationType;
- CallbackBase* mAbortCallBack;
- CallbackManager *mCallbackManager;
- std::string mLanguage;
- std::string mRegion;
-
- Framework* mFramework;
- app_event_handler_h handlers[5];
- ui_app_lifecycle_callback_s mEventCallback;
-#ifdef APPCORE_WATCH_AVAILABLE
- watch_app_lifecycle_callback_s mWatchCallback;
-#endif
-
- static bool AppCreate(void *data)
- {
- return static_cast<Framework*>(data)->Create();
- }
-
- static void AppTerminate(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnTerminate();
- }
-
- static void AppPause(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnPause();
- }
-
- static void AppResume(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnResume();
- }
-
- static void ProcessBundle(Framework* framework, bundle *bundleData)
- {
- if(bundleData == NULL)
- {
- return;
- }
-
- // get bundle name
- char* bundleName = const_cast<char*>(bundle_get_val(bundleData, "name"));
- if(bundleName != NULL)
- {
- framework->SetBundleName(bundleName);
- }
-
- // get bundle id
- char* bundleId = const_cast<char*>(bundle_get_val(bundleData, "id"));
- if(bundleId != NULL)
- {
- framework->SetBundleId(bundleId);
- }
- }
-
- /**
- * Called by AppCore when the application is launched from another module (e.g. homescreen).
- * @param[in] b the bundle data which the launcher module sent
- */
- static void AppControl(app_control_h app_control, void *data)
- {
- Framework* framework = static_cast<Framework*>(data);
- Observer *observer = &framework->mObserver;
- bundle *bundleData = NULL;
-
- app_control_to_bundle(app_control, &bundleData);
- ProcessBundle(framework, bundleData);
-
- observer->OnReset();
- observer->OnAppControl(app_control);
- }
-
- int AppNormalMain()
- {
- int ret;
-
- mEventCallback.create = AppCreate;
- mEventCallback.terminate = AppTerminate;
- mEventCallback.pause = AppPause;
- mEventCallback.resume = AppResume;
- mEventCallback.app_control = AppControl;
-
- ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY, AppBatteryLow, mFramework);
- ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY, AppMemoryLow, mFramework);
- ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED], APP_EVENT_DEVICE_ORIENTATION_CHANGED, AppDeviceRotated, mFramework);
- ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
- ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED], APP_EVENT_REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
-
- ret = ui_app_main(*mFramework->mArgc, *mFramework->mArgv, &mEventCallback, mFramework);
-
- return ret;
- }
-
- void AppNormalExit()
- {
- ui_app_exit();
- }
-
-#ifdef APPCORE_WATCH_AVAILABLE
- static bool AppCreateWatch(int width, int height, void *data)
- {
- return static_cast<Framework*>(data)->Create();
- }
-
- static void AppTimeTick(watch_time_h time, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- WatchTime curTime(time);
-
- observer->OnTimeTick(curTime);
- }
-
- static void AppAmbientTick(watch_time_h time, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- WatchTime curTime(time);
-
- observer->OnAmbientTick(curTime);
- }
-
- static void AppAmbientChanged(bool ambient, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnAmbientChanged(ambient);
- }
-#endif
-
- int AppWatchMain()
- {
- int ret = true;
-
-#ifdef APPCORE_WATCH_AVAILABLE
- mWatchCallback.create = AppCreateWatch;
- mWatchCallback.app_control = AppControl;
- mWatchCallback.terminate = AppTerminate;
- mWatchCallback.pause = AppPause;
- mWatchCallback.resume = AppResume;
- mWatchCallback.time_tick = AppTimeTick;
- mWatchCallback.ambient_tick = AppAmbientTick;
- mWatchCallback.ambient_changed = AppAmbientChanged;
-
- watch_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY, AppBatteryLow, mFramework);
- watch_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY, AppMemoryLow, mFramework);
- watch_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED], APP_EVENT_LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
- watch_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED], APP_EVENT_REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
-
- ret = watch_app_main(*mFramework->mArgc, *mFramework->mArgv, &mWatchCallback, mFramework);
-#endif
- return ret;
- }
-
- void AppWatchExit()
- {
-#ifdef APPCORE_WATCH_AVAILABLE
- watch_app_exit();
-#endif
- }
-
- static void AppLanguageChanged(app_event_info_h event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- observer->OnLanguageChanged();
- }
-
- static void AppDeviceRotated(app_event_info_h event_info, void *data)
- {
- }
-
- static void AppRegionChanged(app_event_info_h event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- observer->OnRegionChanged();
- }
-
- static void AppBatteryLow(app_event_info_h event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- observer->OnBatteryLow(Dali::DeviceStatus::Battery::NORMAL);
- }
-
- static void AppMemoryLow(app_event_info_h event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- observer->OnMemoryLow(Dali::DeviceStatus::Memory::NORMAL);
- }
-
-private:
- // Undefined
- Impl( const Impl& impl );
-
- // Undefined
- Impl& operator=( const Impl& impl );
-};
-
-Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
-: mObserver(observer),
- mInitialised(false),
- mRunning(false),
- mArgc(argc),
- mArgv(argv),
- mBundleName(""),
- mBundleId(""),
- mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
- mImpl(NULL)
-{
- bool featureFlag = true;
- system_info_get_platform_bool( "tizen.org/feature/opengles.version.2_0", &featureFlag );
-
- if( featureFlag == false )
- {
- set_last_result( TIZEN_ERROR_NOT_SUPPORTED );
- }
-#ifdef DALI_ELDBUS_AVAILABLE
- // Initialize ElDBus.
- DALI_LOG_INFO( gDBusLogging, Debug::General, "Starting DBus Initialization\n" );
- eldbus_init();
-#endif
- InitThreads();
-
- mImpl = new Impl(this, type);
-}
-
-Framework::~Framework()
-{
- if (mRunning)
- {
- Quit();
- }
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Shutdown ELDBus.
- DALI_LOG_INFO( gDBusLogging, Debug::General, "Shutting down DBus\n" );
- eldbus_shutdown();
-#endif
-
- delete mImpl;
-}
-
-bool Framework::Create()
-{
- mInitialised = true;
- mObserver.OnInit();
- return true;
-}
-
-void Framework::Run()
-{
- mRunning = true;
- int ret;
-
- ret = mImpl->AppMain();
- if (ret != APP_ERROR_NONE)
- {
- DALI_LOG_ERROR("Framework::Run(), ui_app_main() is failed. err = %d\n", ret);
- }
- mRunning = false;
-}
-
-void Framework::Quit()
-{
- mImpl->AppExit();
-}
-
-bool Framework::IsMainLoopRunning()
-{
- return mRunning;
-}
-
-void Framework::AddAbortCallback( CallbackBase* callback )
-{
- mImpl->mAbortCallBack = callback;
-}
-
-std::string Framework::GetBundleName() const
-{
- return mBundleName;
-}
-
-void Framework::SetBundleName(const std::string& name)
-{
- mBundleName = name;
-}
-
-std::string Framework::GetBundleId() const
-{
- return mBundleId;
-}
-
-std::string Framework::GetResourcePath()
-{
- std::string resourcePath = "";
-#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
- resourcePath = app_get_resource_path();
-#else // For backwards compatibility with older Tizen versions
-
- // "DALI_APPLICATION_PACKAGE" is used to get the already configured Application package path.
- const char* environmentVariable = "DALI_APPLICATION_PACKAGE";
- char* value = getenv( environmentVariable );
- if ( value != NULL )
- {
- resourcePath = value;
- }
-#endif //TIZEN_PLATFORM_CONFIG_SUPPORTED
-
- return resourcePath;
-}
-
-void Framework::SetBundleId(const std::string& id)
-{
- mBundleId = id;
-}
-
-void Framework::AbortCallback( )
-{
- // if an abort call back has been installed run it.
- if (mImpl->mAbortCallBack)
- {
- CallbackBase::Execute( *mImpl->mAbortCallBack );
- }
- else
- {
- Quit();
- }
-}
-
-std::string Framework::GetLanguage() const
-{
- return mImpl->GetLanguage();
-}
-
-std::string Framework::GetRegion() const
-{
- return mImpl->GetRegion();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "framework.h"
-
-// EXTERNAL INCLUDES
-#include <appcore_ui_base.h>
-#include <app_control_internal.h>
-#include <app_common.h>
-#include <bundle.h>
-#include <Ecore.h>
-
-#include <system_info.h>
-#include <system_settings.h>
-#include <bundle_internal.h>
-#include <widget_base.h>
-// CONDITIONAL INCLUDES
-#ifdef APPCORE_WATCH_AVAILABLE
-#include <appcore-watch/watch_app.h>
-#endif
-#ifdef DALI_ELDBUS_AVAILABLE
-#include <Eldbus.h>
-#endif // DALI_ELDBUS_AVAILABLE
-
-#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
-#include <tzplatform_config.h>
-#endif // TIZEN_PLATFORM_CONFIG_SUPPORTED
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <callback-manager.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Integration::Log::Filter* gDBusLogging = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DBUS" );
-#endif
-
-bool IsWidgetFeatureEnabled()
-{
- static bool feature = false;
- static bool retrieved = false;
- int ret;
-
- if(retrieved == true)
- {
- return feature;
- }
-
- ret = system_info_get_platform_bool("http://tizen.org/feature/shell.appwidget", &feature);
- if(ret != SYSTEM_INFO_ERROR_NONE)
- {
- DALI_LOG_ERROR("failed to get system info");
- return false;
- }
-
- retrieved = true;
- return feature;
-}
-
-} // anonymous namespace
-
-namespace AppCore
-{
-
-typedef enum
-{
- LOW_MEMORY, //< The low memory event
- LOW_BATTERY, //< The low battery event
- LANGUAGE_CHANGED, //< The system language changed event
- DEVICE_ORIENTATION_CHANGED, //< The device orientation changed event
- REGION_FORMAT_CHANGED, //< The region format changed event
- SUSPENDED_STATE_CHANGED, //< The suspended state changed event of the application
- UPDATE_REQUESTED, //< The update requested event. This event can occur when an app needs to be updated. It is dependent on target devices.
-} AppEventType;
-
-static int AppEventConverter[APPCORE_BASE_EVENT_MAX] =
-{
- [LOW_MEMORY] = APPCORE_BASE_EVENT_LOW_MEMORY,
- [LOW_BATTERY] = APPCORE_BASE_EVENT_LOW_BATTERY,
- [LANGUAGE_CHANGED] = APPCORE_BASE_EVENT_LANG_CHANGE,
- [DEVICE_ORIENTATION_CHANGED] = APPCORE_BASE_EVENT_DEVICE_ORIENTATION_CHANGED,
- [REGION_FORMAT_CHANGED] = APPCORE_BASE_EVENT_REGION_CHANGE,
- [SUSPENDED_STATE_CHANGED] = APPCORE_BASE_EVENT_SUSPENDED_STATE_CHANGE,
-};
-
-struct AppEventInfo
-{
- AppEventType type;
- void *value;
-};
-
-typedef struct AppEventInfo *AppEventInfoPtr;
-
-typedef void (*AppEventCallback)(AppEventInfoPtr eventInfo, void *userData);
-
-struct AppEventHandler
-{
- AppEventType type;
- AppEventCallback cb;
- void *data;
- void *raw;
-};
-
-typedef struct AppEventHandler *AppEventHandlerPtr;
-
-int EventCallback(void *event, void *data)
-{
- AppEventHandlerPtr handler = static_cast<AppEventHandlerPtr>(data);
-
- struct AppEventInfo appEvent;
-
- appEvent.type = handler->type;
- appEvent.value = event;
-
- if (handler->cb)
- handler->cb(&appEvent, handler->data);
-
- return 0;
-}
-
-int AppAddEventHandler(AppEventHandlerPtr *eventHandler, AppEventType eventType, AppEventCallback callback, void *userData)
-{
- AppEventHandlerPtr handler;
-
- handler = static_cast<AppEventHandlerPtr>( calloc(1, sizeof(struct AppEventHandler)) );
- if (!handler)
- {
- DALI_LOG_ERROR( "failed to create handler" );
- return TIZEN_ERROR_UNKNOWN;
- }
- else
- {
- handler->type = eventType;
- handler->cb = callback;
- handler->data = userData;
- handler->raw = appcore_base_add_event( static_cast<appcore_base_event>(AppEventConverter[static_cast<int>(eventType)]), EventCallback, handler);
-
- *eventHandler = handler;
-
- return TIZEN_ERROR_NONE;
- }
-}
-
-} // namespace Appcore
-
-/**
- * Impl to hide EFL data members
- */
-struct Framework::Impl
-{
-// Constructor
- Impl(void* data, Type type )
- : mAbortCallBack( NULL ),
- mCallbackManager( NULL )
-#ifdef APPCORE_WATCH_AVAILABLE
- , mWatchCallback()
-#endif
- {
- mFramework = static_cast<Framework*>(data);
-
-#ifndef APPCORE_WATCH_AVAILABLE
- if ( type == WATCH )
- {
- throw Dali::DaliException( "", "Watch Application is not supported." );
- }
-#endif
- mApplicationType = type;
- mCallbackManager = CallbackManager::New();
-
- char* region;
- char* language;
- system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_COUNTRY, ®ion );
- system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &language );
- mRegion = std::string( region );
- mLanguage = std::string( language );
- }
-
- ~Impl()
- {
- delete mAbortCallBack;
-
- // we're quiting the main loop so
- // mCallbackManager->RemoveAllCallBacks() does not need to be called
- // to delete our abort handler
- delete mCallbackManager;
- }
-
- int AppMain()
- {
- int ret;
-
- if (mApplicationType == NORMAL)
- {
- ret = AppNormalMain();
- }
- else if(mApplicationType == WIDGET)
- {
- ret = AppWidgetMain();
- }
- else
- {
- ret = AppWatchMain();
- }
- return ret;
- }
-
- void AppExit()
- {
- if (mApplicationType == NORMAL)
- {
- AppNormalExit();
- }
- else if(mApplicationType == WIDGET)
- {
- AppWidgetExit();
- }
- else
- {
- AppWatchExit();
- }
- }
-
- void SetLanguage( const std::string& language )
- {
- mLanguage = language;
- }
-
- void SetRegion( const std::string& region )
- {
- mRegion = region;
- }
-
- std::string GetLanguage() const
- {
- return mLanguage;
- }
-
- std::string GetRegion() const
- {
- return mRegion;
- }
-
- // Data
- Type mApplicationType;
- CallbackBase* mAbortCallBack;
- CallbackManager *mCallbackManager;
- std::string mLanguage;
- std::string mRegion;
-
- Framework* mFramework;
- AppCore::AppEventHandlerPtr handlers[5];
-#ifdef APPCORE_WATCH_AVAILABLE
- watch_app_lifecycle_callback_s mWatchCallback;
- app_event_handler_h watchHandlers[5];
-#endif
-
- static int AppCreate(void *data)
- {
- appcore_ui_base_on_create();
- return static_cast<int>( static_cast<Framework*>(data)->Create() );
- }
-
- static int AppTerminate(void *data)
- {
- appcore_ui_base_on_terminate();
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnTerminate();
-
- return 0;
- }
-
- static int AppPause(void *data)
- {
- appcore_ui_base_on_pause();
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnPause();
-
- return 0;
- }
-
- static int AppResume(void *data)
- {
- appcore_ui_base_on_resume();
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnResume();
-
- return 0;
- }
-
- static void ProcessBundle(Framework* framework, bundle *bundleData)
- {
- if(bundleData == NULL)
- {
- return;
- }
-
- // get bundle name
- char* bundleName = const_cast<char*>(bundle_get_val(bundleData, "name"));
- if(bundleName != NULL)
- {
- framework->SetBundleName(bundleName);
- }
-
- // get bundle? id
- char* bundleId = const_cast<char*>(bundle_get_val(bundleData, "id"));
- if(bundleId != NULL)
- {
- framework->SetBundleId(bundleId);
- }
- }
-
- /**
- * Called by AppCore when the application is launched from another module (e.g. homescreen).
- * @param[in] b the bundle data which the launcher module sent
- */
- static int AppControl(bundle* bundleData, void *data)
- {
- app_control_h appControl = NULL;
-
- appcore_ui_base_on_control(bundleData);
-
- if (bundleData)
- {
- if (app_control_create_event(bundleData, &appControl) != TIZEN_ERROR_NONE)
- {
- DALI_LOG_ERROR("Failed to create an app_control handle");
- }
- }
- else
- {
- if (app_control_create(&appControl) != TIZEN_ERROR_NONE)
- {
- DALI_LOG_ERROR("Failed to create an app_control handle");
- }
- }
-
- Framework* framework = static_cast<Framework*>(data);
- Observer *observer = &framework->mObserver;
-
- ProcessBundle(framework, bundleData);
-
- observer->OnReset();
- observer->OnAppControl(appControl);
-
- app_control_destroy(appControl);
-
- return 0;
- }
-
- static void AppInit(int argc, char **argv, void *data)
- {
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-
- ecore_init();
- ecore_app_args_set( argc, (const char **)argv );
-
-#pragma GCC diagnostic pop
- }
-
- static void AppFinish(void)
- {
- ecore_shutdown();
-
- if(getenv("AUL_LOADER_INIT"))
- {
- unsetenv("AUL_LOADER_INIT");
- ecore_shutdown();
- }
- }
-
- static void AppRun(void *data)
- {
- ecore_main_loop_begin();
- }
-
- static void AppExit(void *data)
- {
- ecore_main_loop_quit();
- }
-
- static void AppLanguageChanged(AppCore::AppEventInfoPtr event, void *data)
- {
- Framework* framework = static_cast<Framework*>(data);
- Observer *observer = &framework->mObserver;
-
- if( event && event->value )
- {
- framework->SetLanguage( std::string( static_cast<const char *>(event->value) ) );
- observer->OnLanguageChanged();
- }
- else
- {
- DALI_LOG_ERROR( "NULL pointer in Language changed event\n" );
- }
- }
-
- static void AppDeviceRotated(AppCore::AppEventInfoPtr event_info, void *data)
- {
- }
-
- static void AppRegionChanged(AppCore::AppEventInfoPtr event, void *data)
- {
- Framework* framework = static_cast<Framework*>(data);
- Observer *observer = &framework->mObserver;
-
- if( event && event->value )
- {
- framework->SetRegion( std::string( static_cast<const char *>(event->value) ) );
- observer->OnRegionChanged();
- }
- else
- {
- DALI_LOG_ERROR( "NULL pointer in Region changed event\n" );
- }
- }
-
- static void AppBatteryLow(AppCore::AppEventInfoPtr event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- int status = *static_cast<int *>(event->value);
- Dali::DeviceStatus::Battery::Status result = Dali::DeviceStatus::Battery::NORMAL;
-
- // convert to dali battery status
- switch( status )
- {
- case 1:
- {
- result = Dali::DeviceStatus::Battery::POWER_OFF;
- break;
- }
- case 2:
- {
- result = Dali::DeviceStatus::Battery::CRITICALLY_LOW;
- break;
- }
- default :
- break;
- }
- observer->OnBatteryLow(result);
- }
-
- static void AppMemoryLow(AppCore::AppEventInfoPtr event, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- int status = *static_cast<int *>(event->value);
- Dali::DeviceStatus::Memory::Status result = Dali::DeviceStatus::Memory::NORMAL;
-
- // convert to dali memmory status
- switch( status )
- {
- case 1:
- {
- result = Dali::DeviceStatus::Memory::NORMAL;
- break;
- }
- case 2:
- {
- result = Dali::DeviceStatus::Memory::LOW;
- break;
- }
- case 4:
- {
- result = Dali::DeviceStatus::Memory::CRITICALLY_LOW;
- break;
- }
- default :
- break;
- }
- observer->OnMemoryLow(result);
- }
-
-
- int AppNormalMain()
- {
- int ret;
-
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::DEVICE_ORIENTATION_CHANGED], AppCore::DEVICE_ORIENTATION_CHANGED, AppDeviceRotated, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
-
- appcore_ui_base_ops ops = appcore_ui_base_get_default_ops();
-
- /* override methods */
- ops.base.create = AppCreate;
- ops.base.control = AppControl;
- ops.base.terminate = AppTerminate;
- ops.pause = AppPause;
- ops.resume = AppResume;
- ops.base.init = AppInit;
- ops.base.finish = AppFinish;
- ops.base.run = AppRun;
- ops.base.exit = AppExit;
-
- ret = appcore_ui_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework, APPCORE_UI_BASE_HINT_WINDOW_GROUP_CONTROL |
- APPCORE_UI_BASE_HINT_WINDOW_STACK_CONTROL |
- APPCORE_UI_BASE_HINT_BG_LAUNCH_CONTROL |
- APPCORE_UI_BASE_HINT_HW_ACC_CONTROL |
- APPCORE_UI_BASE_HINT_WINDOW_AUTO_CONTROL );
-
- if (ret != TIZEN_ERROR_NONE)
- return ret;
-
- appcore_ui_base_fini();
-
- return TIZEN_ERROR_NONE;
- }
-
- void AppNormalExit()
- {
- appcore_ui_base_exit();
- }
-
- void AppWidgetExit()
- {
- widget_base_exit();
- }
-
- static int WidgetAppCreate( void *data )
- {
- widget_base_on_create();
- return static_cast<int>( static_cast<Framework*>(data)->Create() );
- }
-
- static int WidgetAppTerminate( void *data )
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- observer->OnTerminate();
-
- widget_base_on_terminate();
- return 0;
- }
-
- int AppWidgetMain()
- {
- if( !IsWidgetFeatureEnabled() )
- {
- DALI_LOG_ERROR("widget feature is not supported");
- return 0;
- }
-
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::DEVICE_ORIENTATION_CHANGED], AppCore::DEVICE_ORIENTATION_CHANGED, AppDeviceRotated, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
-
- widget_base_ops ops = widget_base_get_default_ops();
-
- /* override methods */
- ops.create = WidgetAppCreate;
- ops.terminate = WidgetAppTerminate;
- ops.init = AppInit;
- ops.finish = AppFinish;
- ops.run = AppRun;
- ops.exit = AppExit;
-
- int result = widget_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework);
-
- widget_base_fini();
-
- return result;
- }
-
-#ifdef APPCORE_WATCH_AVAILABLE
- static bool WatchAppCreate(int width, int height, void *data)
- {
- return static_cast<Framework*>(data)->Create();
- }
-
- static void WatchAppTimeTick(watch_time_h time, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- WatchTime curTime(time);
-
- observer->OnTimeTick(curTime);
- }
-
- static void WatchAppAmbientTick(watch_time_h time, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
- WatchTime curTime(time);
-
- observer->OnAmbientTick(curTime);
- }
-
- static void WatchAppAmbientChanged(bool ambient, void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnAmbientChanged(ambient);
- }
-
- static void WatchAppControl(app_control_h app_control, void *data)
- {
- Framework* framework = static_cast<Framework*>(data);
- Observer *observer = &framework->mObserver;
- bundle *bundleData = NULL;
-
- app_control_to_bundle(app_control, &bundleData);
- ProcessBundle(framework, bundleData);
-
- observer->OnReset();
- observer->OnAppControl(app_control);
- }
-
- static void WatchAppTerminate(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnTerminate();
- }
-
- static void WatchAppPause(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnPause();
- }
-
- static void WatchAppResume(void *data)
- {
- Observer *observer = &static_cast<Framework*>(data)->mObserver;
-
- observer->OnResume();
- }
-
-#endif
-
- int AppWatchMain()
- {
- int ret = true;
-
-#ifdef APPCORE_WATCH_AVAILABLE
- mWatchCallback.create = WatchAppCreate;
- mWatchCallback.app_control = WatchAppControl;
- mWatchCallback.terminate = WatchAppTerminate;
- mWatchCallback.pause = WatchAppPause;
- mWatchCallback.resume = WatchAppResume;
- mWatchCallback.time_tick = WatchAppTimeTick;
- mWatchCallback.ambient_tick = WatchAppAmbientTick;
- mWatchCallback.ambient_changed = WatchAppAmbientChanged;
-
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
- AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
-
- ret = watch_app_main(*mFramework->mArgc, *mFramework->mArgv, &mWatchCallback, mFramework);
-#endif
- return ret;
- }
-
- void AppWatchExit()
- {
-#ifdef APPCORE_WATCH_AVAILABLE
- watch_app_exit();
-#endif
- }
-
-private:
- // Undefined
- Impl( const Impl& impl );
-
- // Undefined
- Impl& operator=( const Impl& impl );
-};
-
-Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
-: mObserver(observer),
- mInitialised(false),
- mRunning(false),
- mArgc(argc),
- mArgv(argv),
- mBundleName(""),
- mBundleId(""),
- mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
- mImpl(NULL)
-{
- bool featureFlag = true;
- system_info_get_platform_bool( "tizen.org/feature/opengles.version.2_0", &featureFlag );
-
- if( featureFlag == false )
- {
- set_last_result( TIZEN_ERROR_NOT_SUPPORTED );
- }
-#ifdef DALI_ELDBUS_AVAILABLE
- // Initialize ElDBus.
- DALI_LOG_INFO( gDBusLogging, Debug::General, "Starting DBus Initialization\n" );
- eldbus_init();
-#endif
- InitThreads();
-
- mImpl = new Impl(this, type);
-}
-
-Framework::~Framework()
-{
- if (mRunning)
- {
- Quit();
- }
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Shutdown ELDBus.
- DALI_LOG_INFO( gDBusLogging, Debug::General, "Shutting down DBus\n" );
- eldbus_shutdown();
-#endif
-
- delete mImpl;
-}
-
-bool Framework::Create()
-{
- mInitialised = true;
- mObserver.OnInit();
- return true;
-}
-
-void Framework::Run()
-{
- mRunning = true;
- int ret;
-
- ret = mImpl->AppMain();
- if (ret != APP_ERROR_NONE)
- {
- DALI_LOG_ERROR("Framework::Run(), ui_app_main() is failed. err = %d\n", ret);
- }
- mRunning = false;
-}
-
-void Framework::Quit()
-{
- mImpl->AppExit();
-}
-
-bool Framework::IsMainLoopRunning()
-{
- return mRunning;
-}
-
-void Framework::AddAbortCallback( CallbackBase* callback )
-{
- mImpl->mAbortCallBack = callback;
-}
-
-std::string Framework::GetBundleName() const
-{
- return mBundleName;
-}
-
-void Framework::SetBundleName(const std::string& name)
-{
- mBundleName = name;
-}
-
-std::string Framework::GetBundleId() const
-{
- return mBundleId;
-}
-
-std::string Framework::GetResourcePath()
-{
- std::string resourcePath = "";
-#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
- resourcePath = app_get_resource_path();
-#else // For backwards compatibility with older Tizen versions
-
- // "DALI_APPLICATION_PACKAGE" is used to get the already configured Application package path.
- const char* environmentVariable = "DALI_APPLICATION_PACKAGE";
- char* value = getenv( environmentVariable );
- if ( value != NULL )
- {
- resourcePath = value;
- }
-#endif //TIZEN_PLATFORM_CONFIG_SUPPORTED
-
- return resourcePath;
-}
-
-void Framework::SetBundleId(const std::string& id)
-{
- mBundleId = id;
-}
-
-void Framework::AbortCallback( )
-{
- // if an abort call back has been installed run it.
- if (mImpl->mAbortCallBack)
- {
- CallbackBase::Execute( *mImpl->mAbortCallBack );
- }
- else
- {
- Quit();
- }
-}
-
-void Framework::SetLanguage( const std::string& language )
-{
- mImpl->SetLanguage( language );
-}
-
-void Framework::SetRegion( const std::string& region )
-{
- mImpl->SetRegion( region );
-}
-
-std::string Framework::GetLanguage() const
-{
- return mImpl->GetLanguage();
-}
-
-std::string Framework::GetRegion() const
-{
- return mImpl->GetRegion();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// CLASS HEADER
-#include <gl/egl-image-extensions.h>
-
-// EXTERNAL INCLUDES
-#if DALI_GLES_VERSION >= 30
-#include <GLES3/gl3.h>
-#include <GLES3/gl3ext.h>
-
-#else
-#include <GLES2/gl2.h>
-#endif // DALI_GLES_VERSION >= 30
-
-#include <GLES2/gl2ext.h>
-
-#include <EGL/eglext.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-implementation.h>
-
-// TBM surface support
-#ifndef EGL_NATIVE_SURFACE_TIZEN
-#define EGL_NATIVE_SURFACE_TIZEN 0x32A1
-#endif
-
-namespace
-{
-// function pointers assigned in InitializeEglImageKHR
-PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0;
-PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0;
-PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0;
-} // unnamed namespace
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl)
-: mEglImplementation(eglImpl),
- mImageKHRInitialized(false),
- mImageKHRInitializeFailed(false)
-{
- DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" );
-}
-
-EglImageExtensions::~EglImageExtensions()
-{
-}
-
-void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer)
-{
- if (mImageKHRInitialized == false)
- {
- InitializeEglImageKHR();
- }
-
- if (mImageKHRInitialized == false)
- {
- return NULL;
- }
-
- // Use the EGL image extension
- const EGLint attribs[] =
- {
- EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
- EGL_NONE
- };
-
- EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(),
- EGL_NO_CONTEXT,
- EGL_NATIVE_SURFACE_TIZEN,
- clientBuffer,
- attribs );
-
- DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n");
- if( EGL_NO_IMAGE_KHR == eglImage )
- {
- switch( eglGetError() )
- {
- case EGL_SUCCESS :
- {
- break;
- }
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
- break;
- }
- case EGL_BAD_CONTEXT:
- {
- DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" );
- break;
- }
- case EGL_BAD_PARAMETER:
- {
- DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" );
- break;
- }
- case EGL_BAD_MATCH:
- {
- DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" );
- break;
- }
- case EGL_BAD_ACCESS:
- {
- DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" );
- break;
- }
- case EGL_BAD_ALLOC:
- {
- DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" );
- break;
- }
- default:
- {
- break;
- }
- }
- }
-
- return eglImage;
-}
-
-void EglImageExtensions::DestroyImageKHR(void* eglImageKHR)
-{
- DALI_ASSERT_DEBUG( mImageKHRInitialized );
-
- if( ! mImageKHRInitialized )
- {
- return;
- }
-
- if( eglImageKHR == NULL )
- {
- return;
- }
-
- EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
-
- EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage);
-
- if( EGL_FALSE == result )
- {
- switch( eglGetError() )
- {
- case EGL_BAD_DISPLAY:
- {
- DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
- break;
- }
- case EGL_BAD_PARAMETER:
- {
- DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" );
- break;
- }
- case EGL_BAD_ACCESS:
- {
- DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" );
- break;
- }
- default:
- {
- break;
- }
- }
- }
-}
-
-void EglImageExtensions::TargetTextureKHR(void* eglImageKHR)
-{
- DALI_ASSERT_DEBUG( mImageKHRInitialized );
-
- if( eglImageKHR != NULL )
- {
- EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
-
-#ifdef EGL_ERROR_CHECKING
- GLint glError = glGetError();
-#endif
-
- glEGLImageTargetTexture2DOESProc(GL_TEXTURE_EXTERNAL_OES, reinterpret_cast< GLeglImageOES >( eglImage ) );
-
-#ifdef EGL_ERROR_CHECKING
- glError = glGetError();
- if( GL_NO_ERROR != glError )
- {
- DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError );
- }
-#endif
- }
-}
-
-void EglImageExtensions::InitializeEglImageKHR()
-{
- // avoid trying to reload extended KHR functions, if it fails the first time
- if( ! mImageKHRInitializeFailed )
- {
- eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") );
- eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") );
- glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") );
- }
-
- if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc)
- {
- mImageKHRInitialized = true;
- }
- else
- {
- mImageKHRInitializeFailed = true;
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_KEY_GRAB_H__
-#define __DALI_KEY_GRAB_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/common/dali-vector.h>
-#include "key.h"
-
-namespace Dali
-{
-/**
- * @addtogroup dali_adaptor_framework
- * @{
- */
-
-class Window;
-
-/**
- * @brief Key grab functions.
- * @SINCE_1_0.0
- */
-namespace KeyGrab
-{
-
-/**
- * @brief Grabs the key specified by @a key for @a window only when @a window is the topmost window.
- *
- * This function can be used for following example scenarios:
- * - Mobile - Using volume up/down as zoom up/down in camera apps.
- *
- * @SINCE_1_0.0
- * @param[in] window The window to set
- * @param[in] daliKey The key code to grab (defined in key.h)
- * @return true if the grab succeeds
- */
-DALI_IMPORT_API bool GrabKeyTopmost( Window window, Dali::KEY daliKey );
-
-/**
- * @brief Ungrabs the key specified by @a key for @a window.
- *
- * @SINCE_1_0.0
- * @param[in] window The window to set
- * @param[in] daliKey The key code to ungrab (defined in key.h)
- * @return true if the ungrab succeeds
- * @note If this function is called between key down and up events of a grabbed key,
- * an application doesn't receive the key up event.
- */
-DALI_IMPORT_API bool UngrabKeyTopmost( Window window, Dali::KEY daliKey );
-
-/**
- * @brief Enumeration for key grab mode for platform-level APIs.
- * @SINCE_1_0.0
- */
-enum KeyGrabMode
-{
- TOPMOST = 0, ///< Grab a key only when on the top of the grabbing-window stack mode. @SINCE_1_0.0
- SHARED, ///< Grab a key together with the other client window(s) mode. @SINCE_1_0.0
- OVERRIDE_EXCLUSIVE, ///< Grab a key exclusively regardless of the grabbing-window's position on the window stack with the possibility of overriding the grab by the other client window mode. @SINCE_1_0.0
- EXCLUSIVE ///< Grab a key exclusively regardless of the grabbing-window's position on the window stack mode. @SINCE_1_0.0
-};
-
-/**
- * @PLATFORM
- * @brief Grabs the key specified by @a key for @a window in @a grabMode.
- *
- * @details This function can be used for following example scenarios:
- * - TV - A user might want to change the volume or channel of the background TV contents while focusing on the foregrund app.
- * - Mobile - When a user presses Home key, the homescreen appears regardless of current foreground app.
- * - Mobile - Using volume up/down as zoom up/down in camera apps.
- *
- * @SINCE_1_0.0
- * @PRIVLEVEL_PLATFORM
- * @PRIVILEGE_KEYGRAB
- * @param[in] window The window to set
- * @param[in] daliKey The key code to grab (defined in key.h)
- * @param[in] grabMode The grab mode for the key
- * @return true if the grab succeeds
- */
-DALI_IMPORT_API bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode );
-
-/**
- * @PLATFORM
- * @brief Ungrabs the key specified by @a key for @a window.
- *
- * @SINCE_1_0.0
- * @PRIVLEVEL_PLATFORM
- * @PRIVILEGE_KEYGRAB
- * @param[in] window The window to set
- * @param[in] daliKey The key code to ungrab (defined in key.h)
- * @return true if the ungrab succeeds
- * @note If this function is called between key down and up events of a grabbed key,
- * an application doesn't receive the key up event.
- */
-DALI_IMPORT_API bool UngrabKey( Window window, Dali::KEY daliKey );
-
-
-/**
- * @PLATFORM
- * @brief Grabs the list of keys specified by Dali::Vector of keys for @a window in Dali::Vector of grabModes.
- *
- * @details This function can be used for following example scenarios:
- * - TV - A user might want to change the volume or channel of the background TV contents while focusing on the foregrund app.
- * - Mobile - When a user presses Home key, the homescreen appears regardless of current foreground app.
- * - Mobile - Using volume up/down as zoom up/down in camera apps.
- *
- * @SINCE_1_2.0
- * @PRIVLEVEL_PLATFORM
- * @PRIVILEGE_KEYGRAB
- * @param[in] window The window to set
- * @param[in] daliKeyVector The Dali::Vector of key codes to grab (defined in key.h)
- * @param[in] grabModeVector The Dali::Vector of grab modes for the keys
- * @param[in] returnVector The Dali::Vector of return boolean values for the results of multiple grab succeeds/fails
- * @return bool false when error occurs
- */
-DALI_IMPORT_API bool GrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, const Dali::Vector<KeyGrabMode>& grabModeVector, Dali::Vector<bool>& returnVector);
-
-
-/**
- * @PLATFORM
- * @brief Ungrabs the list of keys specified by Dali::Vector of keys for @a window.
- *
- * @SINCE_1_2.0
- * @PRIVLEVEL_PLATFORM
- * @PRIVILEGE_KEYGRAB
- * @param[in] window The window to set
- * @param[in] daliKeyVector The Dali::Vector of key codes to ungrab (defined in key.h)
- * @param[in] returnVector The Dali::Vector of return boolean values for the results of multiple ungrab succeeds/fails
- * @return bool false when error occurs
- * @note If this function is called between key down and up events of a grabbed key,
- * an application doesn't receive the key up event.
- */
-DALI_IMPORT_API bool UngrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, Dali::Vector<bool>& returnVector);
-
-
-} // namespace KeyGrab
-
-/**
- * @}
- */
-} // namespace Dali
-
-#endif // __DALI_KEY_GRAB_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "native-image-source-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/gl-defines.h>
-#include <cstring>
-#include <tbm_surface_internal.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-image-extensions.h>
-#include <gl/egl-factory.h>
-#include <adaptor-impl.h>
-#include <render-surface.h>
-
-// Allow this to be encoded and saved:
-#include <bitmap-saver.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n";
-const char* SAMPLER_TYPE = "samplerExternalOES";
-
-tbm_format FORMATS_BLENDING_REQUIRED[] = {
- TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444,
- TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444,
- TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551,
- TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555,
- TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551,
- TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888,
- TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888,
- TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010,
- TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102
-};
-
-const int NUM_FORMATS_BLENDING_REQUIRED = 18;
-
-}
-
-using Dali::Integration::PixelBuffer;
-
-NativeImageSource* NativeImageSource::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
-{
- NativeImageSource* image = new NativeImageSource( width, height, depth, nativeImageSource );
- DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." );
-
- if( image )
- {
- image->Initialize();
- }
-
- return image;
-}
-
-NativeImageSource::NativeImageSource( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
-: mWidth( width ),
- mHeight( height ),
- mOwnTbmSurface( false ),
- mTbmSurface( NULL ),
- mTbmFormat( 0 ),
- mBlendingRequired( false ),
- mColorDepth( depth ),
- mEglImageKHR( NULL ),
- mEglImageExtensions( NULL ),
- mSetSource( false )
-{
- DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );
- EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();
- mEglImageExtensions = eglFactory.GetImageExtensions();
- DALI_ASSERT_DEBUG( mEglImageExtensions );
-
- mTbmSurface = GetSurfaceFromAny( nativeImageSource );
-
- if( mTbmSurface != NULL )
- {
- tbm_surface_internal_ref( mTbmSurface );
- mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
- mWidth = tbm_surface_get_width( mTbmSurface );
- mHeight = tbm_surface_get_height( mTbmSurface );
- }
-}
-
-void NativeImageSource::Initialize()
-{
- if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 )
- {
- return;
- }
-
- tbm_format format = TBM_FORMAT_RGB888;
- int depth = 0;
-
- switch( mColorDepth )
- {
- case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
- {
- format = TBM_FORMAT_RGBA8888;
- depth = 32;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_8:
- {
- format = TBM_FORMAT_C8;
- depth = 8;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_16:
- {
- format = TBM_FORMAT_RGB565;
- depth = 16;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_24:
- {
- format = TBM_FORMAT_RGB888;
- depth = 24;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_32:
- {
- format = TBM_FORMAT_RGBA8888;
- depth = 32;
- break;
- }
- default:
- {
- DALI_LOG_WARNING( "Wrong color depth.\n" );
- return;
- }
- }
-
- // set whether blending is required according to pixel format based on the depth
- /* default pixel format is RGB888
- If depth = 8, Pixel::A8;
- If depth = 16, Pixel::RGB565;
- If depth = 32, Pixel::RGBA8888 */
- mBlendingRequired = ( depth == 32 || depth == 8 );
-
- mTbmSurface = tbm_surface_create( mWidth, mHeight, format );
- mOwnTbmSurface = true;
-}
-
-tbm_surface_h NativeImageSource::GetSurfaceFromAny( Any source ) const
-{
- if( source.Empty() )
- {
- return NULL;
- }
-
- if( source.GetType() == typeid( tbm_surface_h ) )
- {
- return AnyCast< tbm_surface_h >( source );
- }
- else
- {
- return NULL;
- }
-}
-
-NativeImageSource::~NativeImageSource()
-{
- if( mOwnTbmSurface )
- {
- if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
- {
- DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" );
- }
- }
- else
- {
- if( mTbmSurface != NULL )
- {
- tbm_surface_internal_unref( mTbmSurface );
- }
- }
-}
-
-Any NativeImageSource::GetNativeImageSource() const
-{
- return Any( mTbmSurface );
-}
-
-bool NativeImageSource::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
-{
- if( mTbmSurface != NULL )
- {
- tbm_surface_info_s surface_info;
-
- if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE )
- {
- DALI_LOG_ERROR( "Fail to map tbm_surface\n" );
-
- width = 0;
- height = 0;
-
- return false;
- }
-
- tbm_format format = surface_info.format;
- uint32_t stride = surface_info.planes[0].stride;
- unsigned char* ptr = surface_info.planes[0].ptr;
-
- width = mWidth;
- height = mHeight;
- size_t lineSize;
- size_t offset;
- size_t cOffset;
-
- switch( format )
- {
- case TBM_FORMAT_RGB888:
- {
- lineSize = width*3;
- pixelFormat = Pixel::RGB888;
- pixbuf.resize( lineSize*height );
- unsigned char* bufptr = &pixbuf[0];
-
- for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
- {
- for( unsigned int c = 0; c < width; ++c )
- {
- cOffset = c*3;
- offset = cOffset + r*stride;
- *(bufptr+cOffset) = ptr[offset+2];
- *(bufptr+cOffset+1) = ptr[offset+1];
- *(bufptr+cOffset+2) = ptr[offset];
- }
- }
- break;
- }
- case TBM_FORMAT_RGBA8888:
- {
- lineSize = width*4;
- pixelFormat = Pixel::RGBA8888;
- pixbuf.resize( lineSize*height );
- unsigned char* bufptr = &pixbuf[0];
-
- for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
- {
- for( unsigned int c = 0; c < width; ++c )
- {
- cOffset = c*4;
- offset = cOffset + r*stride;
- *(bufptr+cOffset) = ptr[offset+3];
- *(bufptr+cOffset+1) = ptr[offset+2];
- *(bufptr+cOffset+2) = ptr[offset+1];
- *(bufptr+cOffset+3) = ptr[offset];
- }
- }
- break;
- }
- default:
- {
- DALI_ASSERT_ALWAYS( 0 && "Tbm surface has unsupported pixel format.\n" );
-
- return false;
- }
- }
-
- if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
- {
- DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" );
- }
-
- return true;
- }
-
- DALI_LOG_WARNING( "TBM surface does not exist.\n" );
-
- width = 0;
- height = 0;
-
- return false;
-}
-
-bool NativeImageSource::EncodeToFile(const std::string& filename) const
-{
- std::vector< unsigned char > pixbuf;
- unsigned int width(0), height(0);
- Pixel::Format pixelFormat;
-
- if(GetPixels(pixbuf, width, height, pixelFormat))
- {
- return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);
- }
- return false;
-}
-
-void NativeImageSource::SetSource( Any source )
-{
- if( mOwnTbmSurface )
- {
- if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
- {
- DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" );
- }
-
- mTbmSurface = NULL;
- mOwnTbmSurface = false;
- }
- else
- {
- if( mTbmSurface != NULL )
- {
- tbm_surface_internal_unref( mTbmSurface );
- mTbmSurface = NULL;
- }
- }
-
- mTbmSurface = GetSurfaceFromAny( source );
-
- if( mTbmSurface != NULL )
- {
- mSetSource = true;
- tbm_surface_internal_ref( mTbmSurface );
- mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
- mWidth = tbm_surface_get_width( mTbmSurface );
- mHeight = tbm_surface_get_height( mTbmSurface );
- }
-}
-
-bool NativeImageSource::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
-{
- uint32_t* formats;
- uint32_t formatNum;
- tbm_format format = TBM_FORMAT_RGB888;
-
- switch( colorDepth )
- {
- case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
- {
- format = TBM_FORMAT_RGBA8888;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_8:
- {
- format = TBM_FORMAT_C8;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_16:
- {
- format = TBM_FORMAT_RGB565;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_24:
- {
- format = TBM_FORMAT_RGB888;
- break;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_32:
- {
- format = TBM_FORMAT_RGBA8888;
- break;
- }
- }
-
- if( tbm_surface_query_formats( &formats, &formatNum ) )
- {
- for( unsigned int i = 0; i < formatNum; i++ )
- {
- if( formats[i] == format )
- {
- free( formats );
- return true;
- }
- }
- }
-
- free( formats );
- return false;
-}
-
-bool NativeImageSource::GlExtensionCreate()
-{
- // casting from an unsigned int to a void *, which should then be cast back
- // to an unsigned int in the driver.
- EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface);
- if( !eglBuffer )
- {
- return false;
- }
-
- mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );
-
- return mEglImageKHR != NULL;
-}
-
-void NativeImageSource::GlExtensionDestroy()
-{
- if( mEglImageKHR )
- {
- mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
-
- mEglImageKHR = NULL;
- }
-}
-
-unsigned int NativeImageSource::TargetTexture()
-{
- mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
-
- return 0;
-}
-
-void NativeImageSource::PrepareTexture()
-{
- if( mSetSource )
- {
- void* eglImage = mEglImageKHR;
-
- if( GlExtensionCreate() )
- {
- TargetTexture();
- }
-
- mEglImageExtensions->DestroyImageKHR( eglImage );
-
- mSetSource = false;
- }
-}
-
-int NativeImageSource::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const
-{
- switch (depth)
- {
- case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
- {
- // ToDo: Get the default screen depth
- return 32;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_8:
- {
- return 8;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_16:
- {
- return 16;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_24:
- {
- return 24;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_32:
- {
- return 32;
- }
- default:
- {
- DALI_ASSERT_DEBUG(0 && "unknown color enum");
- return 0;
- }
- }
-}
-
-const char* NativeImageSource::GetCustomFragmentPreFix()
-{
- return FRAGMENT_PREFIX;
-}
-
-const char* NativeImageSource::GetCustomSamplerTypename()
-{
- return SAMPLER_TYPE;
-}
-
-int NativeImageSource::GetEglImageTextureTarget()
-{
- return GL_TEXTURE_EXTERNAL_OES;
-}
-
-bool NativeImageSource::CheckBlending( tbm_format format )
-{
- if( mTbmFormat != format )
- {
- for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i)
- {
- if( format == FORMATS_BLENDING_REQUIRED[i] )
- {
- mBlendingRequired = true;
- break;
- }
- }
- mTbmFormat = format;
- }
-
- return mBlendingRequired;
-}
-
-} // namespace Adaptor
-
-} // namespace internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
-#define __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <tbm_surface.h>
-#include <dali/devel-api/images/native-image-interface-extension.h>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <native-image-source.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class EglImageExtensions;
-
-/**
- * Dali internal NativeImageSource.
- */
-class NativeImageSource: public NativeImageInterface::Extension
-{
-public:
-
- /**
- * Create a new NativeImageSource internally.
- * Depending on hardware the width and height may have to be a power of two.
- * @param[in] width The width of the image.
- * @param[in] height The height of the image.
- * @param[in] depth color depth of the image.
- * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
- * @return A smart-pointer to a newly allocated image.
- */
- static NativeImageSource* New(unsigned int width,
- unsigned int height,
- Dali::NativeImageSource::ColorDepth depth,
- Any nativeImageSource);
-
- /**
- * @copydoc Dali::NativeImageSource::GetNativeImageSource()
- */
- Any GetNativeImageSource() const;
-
- /**
- * @copydoc Dali::NativeImageSource::GetPixels()
- */
- bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const;
-
- /**
- * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
- */
- bool EncodeToFile(const std::string& filename) const;
-
- /**
- * @copydoc Dali::NativeImageSource::SetSource( Any source )
- */
- void SetSource( Any source );
-
- /**
- * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
- */
- bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth );
-
- /**
- * destructor
- */
- ~NativeImageSource();
-
- /**
- * @copydoc Dali::NativeImageSource::GlExtensionCreate()
- */
- bool GlExtensionCreate();
-
- /**
- * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
- */
- void GlExtensionDestroy();
-
- /**
- * @copydoc Dali::NativeImageSource::TargetTexture()
- */
- unsigned int TargetTexture();
-
- /**
- * @copydoc Dali::NativeImageSource::PrepareTexture()
- */
- void PrepareTexture();
-
- /**
- * @copydoc Dali::NativeImageSource::GetWidth()
- */
- unsigned int GetWidth() const
- {
- return mWidth;
- }
-
- /**
- * @copydoc Dali::NativeImageSource::GetHeight()
- */
- unsigned int GetHeight() const
- {
- return mHeight;
- }
-
- /**
- * @copydoc Dali::NativeImageSource::RequiresBlending()
- */
- bool RequiresBlending() const
- {
- return mBlendingRequired;
- }
-
- /**
- * @copydoc Dali::NativeImageInterface::GetExtension()
- */
- NativeImageInterface::Extension* GetNativeImageInterfaceExtension()
- {
- return this;
- }
-
- /**
- * @copydoc Dali::NativeImageInterface::Extension::GetCustomFragmentPreFix()
- */
- const char* GetCustomFragmentPreFix();
-
- /**
- * @copydoc Dali::NativeImageInterface::Extension::GetCustomSamplerTypename()
- */
- const char* GetCustomSamplerTypename();
-
- /**
- * @copydoc Dali::NativeImageInterface::Extension::GetEglImageTextureTarget()
- */
- int GetEglImageTextureTarget();
-
-private:
-
- /**
- * Private constructor; @see NativeImageSource::New()
- * @param[in] width The width of the image.
- * @param[in] height The height of the image.
- * @param[in] colour depth of the image.
- * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
- */
- NativeImageSource(unsigned int width,
- unsigned int height,
- Dali::NativeImageSource::ColorDepth depth,
- Any nativeImageSource);
-
- void Initialize();
-
- int GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const;
-
- tbm_surface_h GetSurfaceFromAny( Any source ) const;
-
- bool CheckBlending( tbm_format format );
-
-private:
-
- unsigned int mWidth; ///< image width
- unsigned int mHeight; ///< image heights
- bool mOwnTbmSurface; ///< Whether we created pixmap or not
- tbm_surface_h mTbmSurface;
- tbm_format mTbmFormat;
- bool mBlendingRequired; ///< Whether blending is required
- Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image
- void* mEglImageKHR; ///< From EGL extension
- EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions
- bool mSetSource;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <native-render-surface.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/threading/conditional-wait.h>
-
-#include <Ecore_Wayland.h>
-#include <tbm_bufmgr.h>
-#include <tbm_surface_queue.h>
-#include <tbm_surface_internal.h>
-
-// INTERNAL INCLUDES
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-#include <base/display-connection.h>
-#include <integration-api/thread-synchronization-interface.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gRenderSurfaceLogFilter;
-#endif
-
-struct NativeRenderSurface::Impl
-{
- Impl( Dali::PositionSize positionSize, const std::string& name, bool isTransparent )
- : mPosition( positionSize ),
- mTitle( name ),
- mRenderNotification( NULL ),
- mColorDepth( isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24 ),
- mTbmFormat( isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888 ),
- mOwnSurface( false ),
- mDrawableCompleted( false ),
- mTbmQueue( NULL ),
- mConsumeSurface( NULL ),
- mThreadSynchronization( NULL )
- {
- }
-
- PositionSize mPosition;
- std::string mTitle;
- TriggerEventInterface* mRenderNotification;
- ColorDepth mColorDepth;
- tbm_format mTbmFormat;
- bool mOwnSurface;
- bool mDrawableCompleted;
-
- tbm_surface_queue_h mTbmQueue;
- tbm_surface_h mConsumeSurface;
- ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization
- ConditionalWait mTbmSurfaceCondition;
-};
-
-NativeRenderSurface::NativeRenderSurface(Dali::PositionSize positionSize,
- const std::string& name,
- bool isTransparent)
-: mImpl( new Impl( positionSize, name, isTransparent ) )
-{
- ecore_wl_init(NULL);
- CreateNativeRenderable();
- setenv( "EGL_PLATFORM", "tbm", 1 );
-}
-
-NativeRenderSurface::~NativeRenderSurface()
-{
- // release the surface if we own one
- if( mImpl->mOwnSurface )
- {
- ReleaseDrawable();
-
- if( mImpl->mTbmQueue )
- {
- tbm_surface_queue_destroy( mImpl->mTbmQueue );
- }
-
- delete mImpl;
-
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n" );
- }
-}
-
-void NativeRenderSurface::SetRenderNotification( TriggerEventInterface* renderNotification )
-{
- mImpl->mRenderNotification = renderNotification;
-}
-
-tbm_surface_h NativeRenderSurface::GetDrawable()
-{
- return mImpl->mConsumeSurface;
-}
-
-Any NativeRenderSurface::GetSurface()
-{
- return Any( NULL );
-}
-
-void NativeRenderSurface::InitializeEgl( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
- unsetenv( "EGL_PLATFORM" );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- eglImpl.ChooseConfig( true, mImpl->mColorDepth );
-}
-
-void NativeRenderSurface::CreateEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- eglImpl.CreateSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mImpl->mTbmQueue ), mImpl->mColorDepth );
-}
-
-void NativeRenderSurface::DestroyEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.DestroySurface();
-}
-
-bool NativeRenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- if( !mImpl->mTbmQueue )
- {
- return false;
- }
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- return eglImpl.ReplaceSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mImpl->mTbmQueue ) );
-}
-
-void NativeRenderSurface::StartRender()
-{
-}
-
-bool NativeRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
-{
- // nothing to do for pixmaps
- return true;
-}
-
-void NativeRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.SwapBuffers();
-
- if( mImpl->mThreadSynchronization )
- {
- mImpl->mThreadSynchronization->PostRenderStarted();
- }
-
- if( tbm_surface_queue_can_acquire( mImpl->mTbmQueue, 1 ) )
- {
- if( tbm_surface_queue_acquire( mImpl->mTbmQueue, &mImpl->mConsumeSurface ) != TBM_SURFACE_QUEUE_ERROR_NONE )
- {
- DALI_LOG_ERROR( "Failed to aquire a tbm_surface\n" );
- return;
- }
- }
-
- tbm_surface_internal_ref( mImpl->mConsumeSurface );
-
- if( replacingSurface )
- {
- ConditionalWait::ScopedLock lock( mImpl->mTbmSurfaceCondition );
- mImpl->mDrawableCompleted = true;
- mImpl->mTbmSurfaceCondition.Notify( lock );
- }
-
- // create damage for client applications which wish to know the update timing
- if( !replacingSurface && mImpl->mRenderNotification )
- {
- // use notification trigger
- // Tell the event-thread to render the tbm_surface
- mImpl->mRenderNotification->Trigger();
- }
-
- if( mImpl->mThreadSynchronization )
- {
- // wait until the event-thread completed to use the tbm_surface
- mImpl->mThreadSynchronization->PostRenderWaitForCompletion();
- }
-
- // release the consumed surface after post render was completed
- ReleaseDrawable();
-}
-
-void NativeRenderSurface::StopRender()
-{
- ReleaseLock();
-}
-
-PositionSize NativeRenderSurface::GetPositionSize() const
-{
- return mImpl->mPosition;
-}
-
-void NativeRenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
-}
-
-void NativeRenderSurface::SetViewMode( ViewMode viewMode )
-{
-}
-
-void NativeRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
-{
- mImpl->mThreadSynchronization = &threadSynchronization;
-}
-
-RenderSurface::Type NativeRenderSurface::GetSurfaceType()
-{
- return RenderSurface::NATIVE_RENDER_SURFACE;
-}
-
-void NativeRenderSurface::CreateNativeRenderable()
-{
- // check we're creating one with a valid size
- DALI_ASSERT_ALWAYS( mImpl->mPosition.width > 0 && mImpl->mPosition.height > 0 && "tbm_surface size is invalid" );
-
- mImpl->mTbmQueue = tbm_surface_queue_create( 3, mImpl->mPosition.width, mImpl->mPosition.height, mImpl->mTbmFormat, TBM_BO_DEFAULT );
-
- if( mImpl->mTbmQueue )
- {
- mImpl->mOwnSurface = true;
- }
- else
- {
- mImpl->mOwnSurface = false;
- }
-}
-
-void NativeRenderSurface::ReleaseLock()
-{
- if( mImpl->mThreadSynchronization )
- {
- mImpl->mThreadSynchronization->PostRenderComplete();
- }
-}
-
-void NativeRenderSurface::WaitUntilSurfaceReplaced()
-{
- ConditionalWait::ScopedLock lock( mImpl->mTbmSurfaceCondition );
- while( !mImpl->mDrawableCompleted )
- {
- mImpl->mTbmSurfaceCondition.Wait( lock );
- }
-
- mImpl->mDrawableCompleted = false;
-}
-
-void NativeRenderSurface::ReleaseDrawable()
-{
- if( mImpl->mConsumeSurface )
- {
- tbm_surface_internal_unref( mImpl->mConsumeSurface );
-
- if( tbm_surface_internal_is_valid( mImpl->mConsumeSurface ) )
- {
- tbm_surface_queue_release( mImpl->mTbmQueue, mImpl->mConsumeSurface );
- }
- mImpl->mConsumeSurface = NULL;
- }
-}
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <tizen/tilt-sensor-impl.h>
-
-// EXTERNAL INCLUDES
-#include <cmath>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace // unnamed namespace
-{
-const char* const SIGNAL_TILTED = "tilted";
-
-const float MAX_ORIENTATION_ROLL_VALUE = 90.f;
-const float MAX_ORIENTATION_PITCH_VALUE = 180.f;
-const float MAX_ACCELEROMETER_VALUE = 9.8f;
-
-// Type Registration
-Dali::BaseHandle Create()
-{
- return Dali::Internal::Adaptor::TiltSensor::Get();
-}
-
-Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), Create );
-
-Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal );
-
-} // unnamed namespace
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#ifdef SENSOR_ENABLED
-static void sensor_changed_cb (sensor_h sensor, sensor_event_s *event, void *user_data)
-{
- TiltSensor* tiltSensor = reinterpret_cast< TiltSensor* >( user_data );
-
- if(tiltSensor)
- {
- tiltSensor->Update(event);
- }
-
- return;
-}
-
-static std::string get_sensor_error_string(int errorValue)
-{
- std::string ret;
-
- switch(errorValue)
- {
- case SENSOR_ERROR_IO_ERROR:
- ret = "SENSOR_ERROR_IO_ERROR";
- break;
- case SENSOR_ERROR_INVALID_PARAMETER:
- ret = "SENSOR_ERROR_INVALID_PARAMETER";
- break;
- case SENSOR_ERROR_NOT_SUPPORTED:
- ret = "SENSOR_ERROR_NOT_SUPPORTED";
- break;
- case SENSOR_ERROR_PERMISSION_DENIED:
- ret = "SENSOR_ERROR_PERMISSION_DENIED";
- break;
- case SENSOR_ERROR_OUT_OF_MEMORY:
- ret = "SENSOR_ERROR_OUT_OF_MEMORY";
- break;
- case SENSOR_ERROR_NOT_NEED_CALIBRATION:
- ret = "SENSOR_ERROR_NOT_NEED_CALIBRATION";
- break;
- case SENSOR_ERROR_OPERATION_FAILED:
- ret = "SENSOR_ERROR_OPERATION_FAILED";
- break;
- }
-
- return ret;
-}
-#endif
-
-Dali::TiltSensor TiltSensor::New()
-{
- Dali::TiltSensor sensor = Dali::TiltSensor(new TiltSensor());
-
- return sensor;
-}
-
-Dali::TiltSensor TiltSensor::Get()
-{
- Dali::TiltSensor sensor;
-
- Dali::SingletonService service( SingletonService::Get() );
-
- if ( service )
- {
- // Check whether the keyboard focus manager is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::TiltSensor ) );
- if(handle)
- {
- // If so, downcast the handle of singleton to keyboard focus manager
- sensor = Dali::TiltSensor( dynamic_cast< TiltSensor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- // Create a singleton instance
- sensor = TiltSensor::New();
- service.Register( typeid( sensor ), sensor );
- handle = sensor;
- }
- }
-
- return sensor;
-}
-
-TiltSensor::~TiltSensor()
-{
- Disconnect();
-}
-
-bool TiltSensor::Connect()
-{
-#ifdef SENSOR_ENABLED
- if(mState != DISCONNECTED)
- {
- Stop();
- Disconnect();
- }
-
- const int interval = 1000/mFrequencyHertz;
-
- int ret = 0;
- bool isSupported = false;
-
- // try to use Orientation sensor at first for less power consumption.
- ret = sensor_is_supported(SENSOR_ORIENTATION, &isSupported);
-
- if(ret < 0)
- {
- DALI_LOG_ERROR("sensor_is_supported() failed : %s\n", get_sensor_error_string(ret).c_str());
- return false;
- }
-
- if(isSupported == true)
- {
- mSensorType = SENSOR_ORIENTATION;
- }
- else
- {
- DALI_LOG_ERROR("sensor does not support SENSOR_ORIENTATION\n");
-
- sensor_is_supported(SENSOR_ACCELEROMETER, &isSupported);
-
- if(isSupported == false)
- {
- DALI_LOG_ERROR("sensor does not support both SENSOR_ORIENTATION and SENSOR_ACCELEROMETER\n");
- return false;
- }
-
- mSensorType = SENSOR_ACCELEROMETER;
- }
-
- ret = sensor_get_default_sensor(mSensorType, &mSensor); /* mSensor should not be deleted */
-
- if(ret < 0)
- {
- DALI_LOG_ERROR("sensor_get_default_sensor() failed : %s\n", get_sensor_error_string(ret).c_str());
- return false;
- }
-
- sensor_create_listener(mSensor, &mSensorListener);
- sensor_listener_set_event_cb(mSensorListener, interval, sensor_changed_cb, this);
- sensor_listener_set_interval(mSensorListener, interval);
-
- sensor_listener_set_option(mSensorListener, SENSOR_OPTION_DEFAULT /* Not receive data when LCD is off and in power save mode */);
-
- mState = CONNECTED;
-
- return true;
-#endif
-
- return false;
-}
-
-void TiltSensor::Disconnect()
-{
- if(mSensorListener)
- {
- if(mState == STARTED)
- {
- Stop();
- }
-
- if(mState == STOPPED || mState == CONNECTED)
- {
-#ifdef SENSOR_ENABLED
- sensor_listener_unset_event_cb(mSensorListener);
- sensor_listener_stop(mSensorListener);
- sensor_destroy_listener(mSensorListener);
-#endif
- mSensor = NULL;
- mSensorListener = NULL;
- mState = DISCONNECTED;
- }
- }
-}
-
-bool TiltSensor::Start()
-{
- if( mSensorListener && ( mState == CONNECTED || mState == STOPPED ) )
- {
-#ifdef SENSOR_ENABLED
- int ret = 0;
- ret = sensor_listener_start(mSensorListener);
- if(ret != SENSOR_ERROR_NONE)
- {
- DALI_LOG_ERROR("sensor_listener_start() failed : %s\n", get_sensor_error_string(ret).c_str());
- Disconnect();
- return false;
- }
-
- mState = STARTED;
- return true;
-#endif
- }
- else
- {
- if( mState == STARTED )
- {
- DALI_LOG_ERROR("TiltSensor is already started. Current state [%d]\n", mState);
- }
- else
- {
- // mState is DISCONNECTED
- DALI_LOG_ERROR("TiltSensor is disconnected. Current state [%d]\n", mState);
- }
- return false;
- }
- return false;
-}
-
-void TiltSensor::Stop()
-{
-#ifdef SENSOR_ENABLED
- if(mSensorListener && mState == STARTED)
- {
- sensor_listener_stop( mSensorListener );
- mState = STOPPED;
- }
-#endif
-}
-
-bool TiltSensor::IsStarted() const
-{
- return ( mSensorListener && mState == STARTED );
-}
-
-float TiltSensor::GetRoll() const
-{
- return mRoll;
-}
-
-float TiltSensor::GetPitch() const
-{
- return mPitch;
-}
-
-Quaternion TiltSensor::GetRotation() const
-{
- return mRotation;
-}
-
-TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal()
-{
- return mTiltedSignal;
-}
-
-void TiltSensor::SetUpdateFrequency( float frequencyHertz )
-{
- DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" );
-
- if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) )
- {
- mFrequencyHertz = frequencyHertz;
-
-#ifdef SENSOR_ENABLED
- if(mSensorListener)
- {
- const int interval = 1000/mFrequencyHertz;
- sensor_listener_set_interval(mSensorListener, interval);
- }
-#endif
- }
-}
-
-float TiltSensor::GetUpdateFrequency() const
-{
- return mFrequencyHertz;
-}
-
-void TiltSensor::SetRotationThreshold(Radian rotationThreshold)
-{
- mRotationThreshold = rotationThreshold;
-}
-
-Radian TiltSensor::GetRotationThreshold() const
-{
- return mRotationThreshold;
-}
-
-bool TiltSensor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
-{
- bool connected( true );
- TiltSensor* sensor = dynamic_cast<TiltSensor*>( object );
-
- if( sensor && SIGNAL_TILTED == signalName )
- {
- sensor->TiltedSignal().Connect( tracker, functor );
- }
- else
- {
- // signalName does not match any signal
- connected = false;
- }
-
- return connected;
-}
-
-TiltSensor::TiltSensor()
-: mState(DISCONNECTED),
- mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ),
- mSensor( NULL ),
- mSensorListener( NULL ),
- mRoll( 0.0f ),
- mPitch( 0.0f ),
- mRotation( Radian(0.0f), Vector3::YAXIS ),
- mRotationThreshold( 0.0f )
-{
- // connect sensor
- Connect();
-}
-
-#ifdef SENSOR_ENABLED
-void TiltSensor::Update(sensor_event_s *event)
-{
- Radian newRoll( 0.0f );
- Radian newPitch( 0.0f );
- Quaternion newRotation;
-
- if(mSensorType == SENSOR_ORIENTATION)
- {
- newRoll = Clamp( float(event->values[2] / MAX_ORIENTATION_ROLL_VALUE) /* -90 < roll < 90 */, -1.0f/*min*/, 1.0f/*max*/ );
- newPitch = Clamp( float(event->values[1] / MAX_ORIENTATION_PITCH_VALUE) /* -180 < pitch < 180 */, -1.0f/*min*/, 1.0f/*max*/ );
- }
- else if(mSensorType == SENSOR_ACCELEROMETER)
- {
- newRoll = Clamp( float(event->values[0] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ );
- newPitch = Clamp( float(event->values[1] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ );
- }
- else
- {
- DALI_LOG_ERROR("Invalid sensor type\n");
- return;
- }
-
- newRotation = Quaternion( Radian( newRoll * Math::PI * -0.5f ), Vector3::YAXIS ) *
- Quaternion( Radian( newPitch * Math::PI * -0.5f ), Vector3::XAXIS );
-
- Radian angle(Quaternion::AngleBetween(newRotation, mRotation));
-
- // If the change in value is more than the threshold then emit tilted signal.
- if( angle >= mRotationThreshold )
- {
- mRoll = newRoll;
- mPitch = newPitch;
- mRotation = newRotation;
-
- // emit signal
- if ( !mTiltedSignal.Empty() )
- {
- Dali::TiltSensor handle( this );
- mTiltedSignal.Emit( handle );
- }
- }
-}
-#endif // SENSOR_ENABLED
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
-#define __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#ifdef CAPI_SYSTEM_SENSOR_SUPPORT
-#include <sensor/sensor.h>
-
-#define SENSOR_ENABLED
-#endif
-
-#include <deque>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <public-api/adaptor-framework/timer.h>
-#include <devel-api/adaptor-framework/tilt-sensor.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * TiltSensor provides pitch & roll values when the device is tilted.
- */
-class TiltSensor : public Dali::BaseObject
-{
-public:
-
- typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType;
-
- /**
- * Create a TiltSensor.
- * This should only be called once by the Adaptor class.
- * @return A newly allocated tilt-sensor.
- */
- static Dali::TiltSensor New();
-
- /**
- * @copydoc Dali::TiltSensor::Get()
- */
- static Dali::TiltSensor Get();
-
- /**
- * @copydoc Dali::TiltSensor::Start()
- */
- bool Start();
-
- /**
- * @copydoc Dali::TiltSensor::Stop()
- */
- void Stop();
-
- /**
- * @copydoc Dali::TiltSensor::IsStarted()
- */
- bool IsStarted() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetRoll()
- */
- float GetRoll() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetPitch()
- */
- float GetPitch() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetRotation()
- */
- Quaternion GetRotation() const;
-
- /**
- * @copydoc Dali::TiltSensor::TiltedSignal()
- */
- TiltedSignalType& TiltedSignal();
-
- /**
- * @copydoc Dali::TiltSensor::SetUpdateFrequency()
- */
- void SetUpdateFrequency( float frequencyHertz );
-
- /**
- * @copydoc Dali::TiltSensor::GetUpdateFrequency()
- */
- float GetUpdateFrequency() const;
-
- /**
- * @copydoc Dali::TiltSensor::SetRotationThreshold()
- */
- void SetRotationThreshold(Radian rotationThreshold);
-
- /**
- * @copydoc Dali::TiltSensor::GetRotationThreshold()
- */
- Radian GetRotationThreshold() const;
-
- /**
- * Connects a callback function with the object's signals.
- * @param[in] object The object providing the signal.
- * @param[in] tracker Used to disconnect the signal.
- * @param[in] signalName The signal to connect to.
- * @param[in] functor A newly allocated FunctorDelegate.
- * @return True if the signal was connected.
- * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
- */
- static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
-
- /**
- * Update sensor data
- * @note This is called by static sensor callback function
- * @param[in] event sensor event data
- */
-#ifdef SENSOR_ENABLED
- void Update(sensor_event_s *event);
-#endif
-
-private:
-
- enum State
- {
- DISCONNECTED,
- CONNECTED,
- STARTED,
- STOPPED
- };
-
- /**
- * Private constructor; see also TiltSensor::New()
- */
- TiltSensor();
-
- /**
- * Destructor
- */
- virtual ~TiltSensor();
-
- /**
- * Connect sensor device
- */
- bool Connect();
- /**
- * Disconnect sensor device
- */
- void Disconnect();
-
- // Undefined
- TiltSensor(const TiltSensor&);
-
- // Undefined
- TiltSensor& operator=(TiltSensor&);
-
-private:
- State mState;
- float mFrequencyHertz;
-
-#ifdef SENSOR_ENABLED
- sensor_type_e mSensorType;
- sensor_h mSensor;
- sensor_listener_h mSensorListener;
-#else
- int mSensorType;
- int* mSensor;
- int* mSensorListener;
-#endif
-
- float mRoll;
- float mPitch;
- Quaternion mRotation;
-
- Radian mRotationThreshold;
-
- TiltedSignalType mTiltedSignal;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::TiltSensor& GetImplementation(Dali::TiltSensor& sensor)
-{
- DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
-
- BaseObject& handle = sensor.GetBaseObject();
-
- return static_cast<Internal::Adaptor::TiltSensor&>(handle);
-}
-
-inline const Internal::Adaptor::TiltSensor& GetImplementation(const Dali::TiltSensor& sensor)
-{
- DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
-
- const BaseObject& handle = sensor.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::TiltSensor&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tts-player-impl.h"
-
-// EXTERNAL INCLUDES
-#include <tts.h>
-#include <stdio.h>
-
-#include <dali/public-api/object/type-registry.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace // unnamed namespace
-{
-
-/**
- * Helper function to convert Tizen-specific TTS state to external state.
- * @param state The Tizen TTS state.
- * @return The external TTS state.
- */
-Dali::TtsPlayer::State InternalToExternalState( tts_state_e state )
-{
- switch( state )
- {
- case TTS_STATE_CREATED:
- {
- return Dali::TtsPlayer::UNAVAILABLE;
- }
- case TTS_STATE_READY:
- {
- return Dali::TtsPlayer::READY;
- }
- case TTS_STATE_PLAYING:
- {
- return Dali::TtsPlayer::PLAYING;
- }
- case TTS_STATE_PAUSED:
- {
- return Dali::TtsPlayer::PAUSED;
- }
- }
-
- return Dali::TtsPlayer::UNAVAILABLE;
-}
-
-} // unnamed namespace
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* TtsPlayer::gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TTS_PLAYER");
-#endif
-
-Dali::TtsPlayer TtsPlayer::New(Dali::TtsPlayer::Mode mode)
-{
- Dali::TtsPlayer player = Dali::TtsPlayer(new TtsPlayer(mode));
-
- return player;
-}
-
-TtsPlayer::TtsPlayer(Dali::TtsPlayer::Mode mode)
-: mInitialized(false),
- mUnplayedString(""),
- mUtteranceId(0),
- mTtsMode(mode)
-{
- Initialize();
-}
-
-TtsPlayer::~TtsPlayer()
-{
- // If it is playing, stop it
- Stop();
-
- // Unset the callback funtion for TTS state change
- int retVal = tts_unset_state_changed_cb(mTtsHandle);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
-
- // Destroy the TTS handle and disconnects the daemon
- retVal = tts_destroy(mTtsHandle);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
-}
-
-void TtsPlayer::Initialize()
-{
- // Create the TTS handle
- int retVal = tts_create(&mTtsHandle);
-
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else
- {
- // Set the callback funtion for TTS state change
- retVal = tts_set_state_changed_cb(mTtsHandle, &StateChangedCallback, this);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
-
- // Check tts mode
- tts_mode_e ttsMode = TTS_MODE_DEFAULT;
- switch (mTtsMode)
- {
- case Dali::TtsPlayer::DEFAULT:
- ttsMode = TTS_MODE_DEFAULT;
- break;
- case Dali::TtsPlayer::NOTIFICATION:
- ttsMode = TTS_MODE_NOTIFICATION;
- break;
- case Dali::TtsPlayer::SCREEN_READER:
- ttsMode = TTS_MODE_SCREEN_READER;
- break;
- default:
- break;
- }
-
- // Set mode
- retVal = tts_set_mode(mTtsHandle, ttsMode);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
-
- // Connect the TTS daemon asynchronously
- retVal = tts_prepare(mTtsHandle);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- }
-}
-
-void TtsPlayer::Play(const std::string& text)
-{
- if(mInitialized)
- {
- Stop();
-
- // Add text to the queue, and use normal speed, default language and default voice set by the user
- int retVal = tts_add_text(mTtsHandle, text.c_str(), NULL, TTS_VOICE_TYPE_AUTO, TTS_SPEED_AUTO, &mUtteranceId);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else
- {
- // Start synthesizing voice from text in the queue and play synthesized audio data
- retVal = tts_play(mTtsHandle);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- }
- }
- else
- {
- mUnplayedString = text;
- }
-}
-
-void TtsPlayer::Stop()
-{
- if(mInitialized)
- {
- // Check the current TTS state
- tts_state_e state;
- int retVal = tts_get_state(mTtsHandle, &state);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else if(state == TTS_STATE_PLAYING || state == TTS_STATE_PAUSED)
- {
- // If it is playing or paused, stop playing and clear the queue
- retVal = tts_stop(mTtsHandle);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- }
- }
-}
-
-void TtsPlayer::Pause()
-{
- if(mInitialized)
- {
- // Check the current TTS state
- tts_state_e state;
- int retVal = tts_get_state(mTtsHandle, &state);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else if(state == TTS_STATE_PLAYING)
- {
- // If the player is playing, pause it.
- retVal = tts_pause(mTtsHandle);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- }
- }
-}
-
-void TtsPlayer::Resume()
-{
- if(mInitialized)
- {
- // Check the current TTS state
- tts_state_e state;
- int retVal = tts_get_state(mTtsHandle, &state);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else if(state == TTS_STATE_PAUSED)
- {
- // If the player is paused, resume it.
- retVal = tts_play(mTtsHandle);
- if( retVal != TTS_ERROR_NONE )
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- }
- }
-}
-
-Dali::TtsPlayer::State TtsPlayer::GetState()
-{
- Dali::TtsPlayer::State ttsState = Dali::TtsPlayer::UNAVAILABLE;
-
- if(mInitialized)
- {
- // Check the current TTS state
- tts_state_e state;
- int retVal = tts_get_state(mTtsHandle, &state);
- if(retVal != TTS_ERROR_NONE)
- {
- LogErrorCode(static_cast<tts_error_e>(retVal));
- }
- else
- {
- ttsState = InternalToExternalState( state );
- }
- }
-
- return ttsState;
-}
-
-Dali::TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal()
-{
- return mStateChangedSignal;
-}
-
-void TtsPlayer::EmitStateChangedSignal( tts_state_e previous, tts_state_e current )
-{
- // Convert the previous and current states to external states and emit them as a signal.
- if( !mStateChangedSignal.Empty() )
- {
- mStateChangedSignal.Emit( InternalToExternalState( previous ), InternalToExternalState( current ) );
- }
-}
-
-void TtsPlayer::StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData)
-{
- // Get the implementation (this is a static function).
- TtsPlayer* obj = static_cast<TtsPlayer*>(userData);
-
- // Emit the signal.
- obj->EmitStateChangedSignal( previous, current );
-
- if(!obj->mInitialized && current == TTS_STATE_READY)
- {
- obj->mInitialized = true;
-
- // if there is queued text before initialization, play it
- if(obj->mUnplayedString != "")
- {
- obj->Play(obj->mUnplayedString);
- obj->mUnplayedString = "";
- }
- }
-}
-
-void TtsPlayer::LogErrorCode(tts_error_e reason)
-{
- std::string error_string;
-
- switch (reason)
- {
- case TTS_ERROR_NONE:
- {
- break;
- }
- case TTS_ERROR_OUT_OF_MEMORY:
- {
- error_string = "TTS: Out of Memory\n";
- break;
- }
- case TTS_ERROR_IO_ERROR:
- {
- error_string = "TTS: I/O error\n";
- break;
- }
- case TTS_ERROR_INVALID_PARAMETER:
- {
- error_string = "TTS: Invalid parameter\n";
- break;
- }
- case TTS_ERROR_OUT_OF_NETWORK:
- {
- error_string = "TTS: Out of network\n";
- break;
- }
- case TTS_ERROR_INVALID_STATE:
- {
- error_string = "TTS: Invalid state\n";
- break;
- }
- case TTS_ERROR_INVALID_VOICE:
- {
- error_string = "TTS: Invalid voice\n";
- break;
- }
- case TTS_ERROR_ENGINE_NOT_FOUND:
- {
- error_string = "TTS: No available engine\n";
- break;
- }
- case TTS_ERROR_TIMED_OUT:
- {
- error_string = "TTS: No answer from the daemon\n";
- break;
- }
- case TTS_ERROR_OPERATION_FAILED:
- {
- error_string = "TTS: Operation failed\n";
- break;
- }
- default:
- {
- error_string = "Invalid TTS error code\n";
- break;
- }
- }
-
- if(reason != TTS_ERROR_NONE)
- {
- DALI_LOG_WARNING("[%s:%d] tts error : %s\n", __FUNCTION__, __LINE__, error_string.c_str());
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_TTS_PLAYER_H__
-#define __DALI_INTERNAL_TTS_PLAYER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <tts.h>
-#include <string>
-
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <tts-player.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Text-to-speech player
- */
-class TtsPlayer : public Dali::BaseObject
-{
-
-public:
-
- /**
- * Create a TtsPlayer with the given mode.
- * This should only be called once by the Adaptor class for each given mode.
- * @param mode the mode of tts-player
- * @return A newly created TtsPlayer.
- */
- static Dali::TtsPlayer New(Dali::TtsPlayer::Mode mode);
-
- /**
- * @copydoc TtsPlayer::Play()
- */
- void Play(const std::string& text);
-
- /**
- * @copydoc TtsPlayer::Stop()
- */
- void Stop();
-
- /**
- * @copydoc TtsPlayer::Pause()
- */
- void Pause();
-
- /**
- * @copydoc TtsPlayer::Resume()
- */
- void Resume();
-
- /**
- * @copydoc TtsPlayer::GetState()
- */
- Dali::TtsPlayer::State GetState();
-
- /**
- * @copydoc TtsPlayer::StateChangedSignal()
- */
- Dali::TtsPlayer::StateChangedSignalType& StateChangedSignal();
-
-private:
-
- /**
- * Private Constructor; see also TtsPlayer::New()
- * @param mode the mode of tts-player
- */
- TtsPlayer(Dali::TtsPlayer::Mode mode);
-
- /**
- * Destructor
- */
- virtual ~TtsPlayer();
-
- /**
- * Initializes the player.
- */
- void Initialize();
-
- /**
- * Logs the error code.
- * @param[in] reason The error code
- */
- void LogErrorCode(tts_error_e reason);
-
- /**
- * Used to emit the state changed signal from outside the object (EG. A static function).
- * @param[in] previous The previous state
- * @param[in] current The current state
- */
- void EmitStateChangedSignal( tts_state_e previous, tts_state_e current );
-
- /**
- * Called when the state of TTS is changed.
- *
- * @param[in] tts The handle for TTS
- * @param[in] previous A previous state
- * @param[in] current A current state
- * @param[in] userData The user data passed from the callback registration function.
- */
- static void StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData);
-
- // Undefined
- TtsPlayer(const TtsPlayer&);
-
- // Undefined
- TtsPlayer& operator=(TtsPlayer&);
-
-private:
-
- Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes
- bool mInitialized; ///< Whether the TTS player is initialised successfully or not
- std::string mUnplayedString; ///< The text that can not be played because tts engine is not yet initialized
- tts_h mTtsHandle; ///< The handle of TTS
- int mUtteranceId; ///< The utterance ID
-
- Dali::TtsPlayer::Mode mTtsMode; ///< The current mode of tts engine
-
-#if defined(DEBUG_ENABLED)
-public:
- static Debug::Filter* gLogFilter;
-#endif
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::TtsPlayer& GetImplementation(Dali::TtsPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast<Internal::Adaptor::TtsPlayer&>(handle);
-}
-
-inline const Internal::Adaptor::TtsPlayer& GetImplementation(const Dali::TtsPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::TtsPlayer&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_TTS_PLAYER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <vconf.h>
-#include <vconf-keys.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include "vsync-monitor.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-// constants to keep code readability with unsigned int has to be used as boolean (due to multithreading)
-const unsigned int TRUE = 1u;
-const unsigned int FALSE = 0u;
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VSYNC_MONITOR");
-#endif
-
-const char * const DRM_DEVICE( "/dev/dri/card0" );
-const int FD_NONE( -1 );
-
-void ScreenStatusChanged(keynode_t* node, void* data)
-{
- VSyncMonitor* vsyncMonitor( static_cast< VSyncMonitor* >( data ) );
-
- int status = 0;
- vconf_get_int( VCONFKEY_PM_STATE, &status );
-
- // status values
- // - VCONFKEY_PM_STATE_NORMAL : turn vsync on
- // - VCONFKEY_PM_STATE_LCDDIM : turn vsync off
- // - VCONFKEY_PM_STATE_LCDOFF : turn vsync off
- // - VCONFKEY_PM_STATE_SLEEP : turn vsync off
- const unsigned int screenOn( VCONFKEY_PM_STATE_NORMAL == status );
-
- vsyncMonitor->SetHardwareVSyncAvailable( screenOn );
-
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "%s, Screen %s.\n", __PRETTY_FUNCTION__, screenOn ? "On" : "Off" );
-}
-
-} // unnamed namespace
-
-VSyncMonitor::VSyncMonitor()
-: mFileDescriptor( FD_NONE ),
- mUseHardwareVSync( TRUE ),
- mHardwareVSyncAvailable( FALSE )
-{
- vconf_notify_key_changed( VCONFKEY_PM_STATE, ScreenStatusChanged, this );
-}
-
-VSyncMonitor::~VSyncMonitor()
-{
- Terminate();
-
- vconf_ignore_key_changed( VCONFKEY_PM_STATE, ScreenStatusChanged );
-}
-
-void VSyncMonitor::SetUseHardwareVSync( bool useHardware )
-{
- mUseHardwareVSync = useHardware;
-}
-
-void VSyncMonitor::SetHardwareVSyncAvailable( bool hardwareVSyncAvailable )
-{
- mHardwareVSyncAvailable = hardwareVSyncAvailable;
-}
-
-void VSyncMonitor::Initialize()
-{
- DALI_ASSERT_DEBUG( mFileDescriptor == FD_NONE && "VSyncMonitor::Initialize() called twice" );
-
- // Read initial 'use hardware' status
- ScreenStatusChanged( NULL, this );
-
- // open /dev node
- mFileDescriptor = open( DRM_DEVICE, O_RDWR );
-
- // setup vblank request - block and wait for next vblank
- mVBlankInfo.request.type = DRM_VBLANK_NEXTONMISS;
- mVBlankInfo.request.sequence = 0;
- mVBlankInfo.request.signal = 0;
-
- // setup vblank reply - block and wait for next vblank
- mVBlankInfo.reply.type = DRM_VBLANK_NEXTONMISS;
- mVBlankInfo.reply.sequence = 0;
- mVBlankInfo.reply.tval_sec = 0;
- mVBlankInfo.reply.tval_usec = 0;
-}
-
-void VSyncMonitor::Terminate()
-{
- if( mFileDescriptor != FD_NONE )
- {
- close( mFileDescriptor );
- mFileDescriptor = FD_NONE;
- }
-}
-
-bool VSyncMonitor::UseHardware()
-{
- return mUseHardwareVSync && mHardwareVSyncAvailable && (FD_NONE != mFileDescriptor );
-}
-
-bool VSyncMonitor::DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds )
-{
- DALI_ASSERT_DEBUG( mFileDescriptor != FD_NONE && "ECoreX::VSyncMonitor is not initialized" );
-
- if( 0 == drmWaitVBlank( mFileDescriptor, &mVBlankInfo ) )
- {
- frameNumber = mVBlankInfo.reply.sequence;
- seconds = mVBlankInfo.reply.tval_sec;
- microseconds = mVBlankInfo.reply.tval_usec;
-
- return true;
- }
-
- return false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-application-impl.h"
-
-// INTERNAL INCLUDE
-#include <widget.h>
-#include <widget-impl.h>
-#include <widget-controller.h>
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-WidgetApplicationPtr WidgetApplication::New(
- int* argc,
- char **argv[],
- const std::string& stylesheet)
-{
- WidgetApplicationPtr widgetApplication( new WidgetApplication (argc, argv, stylesheet ) );
- return widgetApplication;
-}
-
-WidgetApplication::WidgetApplication( int* argc, char** argv[], const std::string& stylesheet )
-:Application(argc, argv, stylesheet, Dali::WidgetApplication::OPAQUE, PositionSize(), Framework::WIDGET)
-{
- DALI_LOG_ERROR("WidgetApplication is not implemented in 3.0 tizen profile.\n");
-}
-
-WidgetApplication::~WidgetApplication()
-{
-}
-
-
-void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
-{
-}
-
-void WidgetApplication::AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair )
-{
- mCreateWidgetFunctionContainer.push_back( pair );
-}
-
-WidgetApplication::CreateWidgetFunctionPair WidgetApplication::GetWidgetCreatingFunctionPair( const std::string& widgetName )
-{
- for( CreateWidgetFunctionContainer::const_iterator iter = mCreateWidgetFunctionContainer.begin(); iter != mCreateWidgetFunctionContainer.end(); ++iter )
- {
- if( widgetName.find((*iter).first) != std::string::npos )
- {
- return *iter;
- }
- }
-
- return CreateWidgetFunctionPair( "", NULL );
-}
-
-void WidgetApplication::AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget )
-{
- mWidgetInstanceContainer.push_back( WidgetInstancePair(widgetBaseInstance, widget) );
-}
-
-Dali::Widget WidgetApplication::GetWidget( widget_base_instance_h widgetBaseInstance )
-{
- for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
- {
- if( (*iter).first == widgetBaseInstance )
- {
- return (*iter).second;
- }
- }
- return Dali::Widget();
-}
-
-void WidgetApplication::DeleteWidget( widget_base_instance_h widgetBaseInstance )
-{
- for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
- {
- if( (*iter).first == widgetBaseInstance )
- {
- mWidgetInstanceContainer.erase(iter);
- break;
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-application-impl.h"
-
-// INTERNAL INCLUDE
-#include <widget.h>
-#include <widget-impl.h>
-#include <widget-controller.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace
-{
-
-int OnInstanceInit(widget_base_instance_h instanceHandle, bundle *content, int w, int h, void *classData)
-{
- char *id;
- widget_base_context_get_id(instanceHandle, &id);
-
- widget_base_class_on_create(instanceHandle, content, w, h);
-
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // After DALi can support multi window, this part should be changed.
- Dali::Window window = application->GetWindow();
- window.ShowIndicator(Dali::Window::INVISIBLE);
- Any nativeHandle = window.GetNativeHandle();
- Ecore_Wl_Window * wlWindow = AnyCast<Ecore_Wl_Window*>( nativeHandle );
- widget_base_context_window_bind( instanceHandle, id, wlWindow );
- window.SetSize( Dali::Window::WindowSize( w, h ) );
-
- Dali::Internal::Adaptor::WidgetApplication::CreateWidgetFunctionPair pair = application->GetWidgetCreatingFunctionPair(std::string(id));
- Dali::WidgetApplication::CreateWidgetFunction createFunction = pair.second;
-
- Dali::Widget widgetInstance = createFunction( pair.first );
- application->AddWidget( instanceHandle, widgetInstance );
-
- Dali::Internal::Adaptor::Widget::Impl *widgetImpl = new Dali::Internal::Adaptor::Widget::Impl(instanceHandle);
- Internal::Adaptor::GetImplementation(widgetInstance).SetImpl( widgetImpl );
-
- std::string encodedContentString = "";
-
- if( bundle_get_count( content ) )
- {
- bundle_raw *bundleRaw;
- int len;
- bundle_encode(content, &bundleRaw, &len);
- char* encodedContent = reinterpret_cast< char* >( bundleRaw );
- encodedContentString = std::string( encodedContent );
- free(bundleRaw);
- }
-
- Internal::Adaptor::GetImplementation(widgetInstance).OnCreate( encodedContentString, window );
-
- return 0;
-}
-
-int OnInstanceDestroy(widget_base_instance_h instanceHandle, widget_base_destroy_type_e reason, bundle *content, void *classData)
-{
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // Get Dali::Widget instance.
- Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
-
- Dali::Widget::Termination destroyReason = Dali::Widget::Termination::TEMPORARY;
-
- if(reason == WIDGET_BASE_DESTROY_TYPE_PERMANENT)
- {
- destroyReason = Dali::Widget::Termination::PERMANENT;
- }
-
- std::string encodedContentString = "";
-
- if( bundle_get_count( content ) )
- {
- bundle_raw *bundleRaw;
- int len;
- bundle_encode(content, &bundleRaw, &len);
- char* encodedContent = reinterpret_cast< char* >( bundleRaw );
- encodedContentString = std::string(encodedContent);
- free(bundleRaw);
- }
-
- Internal::Adaptor::GetImplementation(widgetInstance).OnTerminate( encodedContentString, destroyReason );
-
- widget_base_class_on_destroy(instanceHandle, reason, content);
-
- application->DeleteWidget( instanceHandle );
-
- return 0;
-}
-
-int OnInstancePause(widget_base_instance_h instanceHandle, void *classData)
-{
- widget_base_class_on_pause(instanceHandle);
-
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // Get Dali::Widget instance.
- Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
-
- Internal::Adaptor::GetImplementation(widgetInstance).OnPause();
-
- return 0;
-}
-
-int OnInstanceResume(widget_base_instance_h instanceHandle, void *classData)
-{
- widget_base_class_on_resume(instanceHandle);
-
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // Get Dali::Widget instance.
- Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
-
- Internal::Adaptor::GetImplementation(widgetInstance).OnResume();
-
- return 0;
-}
-
-int OnInstanceResize(widget_base_instance_h instanceHandle, int w, int h, void *classData)
-{
- widget_base_class_on_resize(instanceHandle, w, h);
-
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // Get Dali::Widget instance.
- Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
-
- Dali::Window window = application->GetWindow();
- window.SetSize( Dali::Window::WindowSize(w, h) );
- Internal::Adaptor::GetImplementation(widgetInstance).OnResize(window);
-
- return 0;
-}
-
-int OnInstanceUpdate(widget_base_instance_h instanceHandle, bundle *content, int force, void *classData)
-{
- widget_base_class_on_update(instanceHandle, content, force);
-
- Dali::Internal::Adaptor::WidgetApplication* application = static_cast<Dali::Internal::Adaptor::WidgetApplication*>(classData);
-
- // Get Dali::Widget instance.
- Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
-
- std::string encodedContentString = "";
-
- if( bundle_get_count( content ) )
- {
- bundle_raw *bundleRaw;
- int len;
- bundle_encode(content, &bundleRaw, &len);
- char* encodedContent = reinterpret_cast< char* >( bundleRaw );
- encodedContentString = std::string(encodedContent);
- free(bundleRaw);
- }
-
- Internal::Adaptor::GetImplementation(widgetInstance).OnUpdate( encodedContentString, force );
-
- return 0;
-}
-
-} // anonymous namespace
-
-namespace Adaptor
-{
-
-WidgetApplicationPtr WidgetApplication::New(
- int* argc,
- char **argv[],
- const std::string& stylesheet)
-{
- WidgetApplicationPtr widgetApplication( new WidgetApplication (argc, argv, stylesheet ) );
- return widgetApplication;
-}
-
-WidgetApplication::WidgetApplication( int* argc, char** argv[], const std::string& stylesheet )
-:Application(argc, argv, stylesheet, Dali::WidgetApplication::OPAQUE, PositionSize(), Framework::WIDGET)
-{
-}
-
-WidgetApplication::~WidgetApplication()
-{
-}
-
-
-void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
-{
- AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair(widgetName, createFunction) );
-
- // Register widget class to widget framework
- widget_base_class cls = widget_base_class_get_default();
- cls.ops.create = OnInstanceInit;
- cls.ops.destroy = OnInstanceDestroy;
- cls.ops.pause = OnInstancePause;
- cls.ops.resume = OnInstanceResume;
- cls.ops.resize = OnInstanceResize;
- cls.ops.update = OnInstanceUpdate;
-
- widget_base_class_add(cls, widgetName.c_str(), this);
-}
-
-void WidgetApplication::AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair )
-{
- mCreateWidgetFunctionContainer.push_back( pair );
-}
-
-WidgetApplication::CreateWidgetFunctionPair WidgetApplication::GetWidgetCreatingFunctionPair( const std::string& widgetName )
-{
- for( CreateWidgetFunctionContainer::const_iterator iter = mCreateWidgetFunctionContainer.begin(); iter != mCreateWidgetFunctionContainer.end(); ++iter )
- {
- if( widgetName.find((*iter).first) != std::string::npos )
- {
- return *iter;
- }
- }
-
- return CreateWidgetFunctionPair( "", NULL );
-}
-
-void WidgetApplication::AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget )
-{
- mWidgetInstanceContainer.push_back( WidgetInstancePair(widgetBaseInstance, widget) );
-}
-
-Dali::Widget WidgetApplication::GetWidget( widget_base_instance_h widgetBaseInstance )
-{
- for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
- {
- if( (*iter).first == widgetBaseInstance )
- {
- return (*iter).second;
- }
- }
- return Dali::Widget();
-}
-
-void WidgetApplication::DeleteWidget( widget_base_instance_h widgetBaseInstance )
-{
- for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
- {
- if( (*iter).first == widgetBaseInstance )
- {
- mWidgetInstanceContainer.erase(iter);
- break;
- }
- }
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_WIDGET_APPLICATION_H
-#define DALI_INTERNAL_WIDGET_APPLICATION_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#ifdef WIDGET_SUPPOERTED
-#include <widget_base.h>
-#endif
-
-// INTERNAL INCLUDES
-#include <application-impl.h>
-#include <widget-application.h>
-
-namespace Dali
-{
-class Widget;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class WidgetApplication;
-typedef IntrusivePtr<WidgetApplication> WidgetApplicationPtr;
-
-/**
- * Implementation of the WidgetApplication class.
- */
-class WidgetApplication : public Application
-{
-public:
-
-#ifndef WIDGET_SUPPOERTED
- typedef void* widget_base_instance_h;
-#endif
- typedef std::pair<const std::string, Dali::WidgetApplication::CreateWidgetFunction > CreateWidgetFunctionPair;
- typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer;
-
- /**
- * Create a new widget application
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- */
- static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet );
-
-public:
-
- /**
- * @copydoc Dali::WidgetApplication::RegisterWidgetCreator()
- */
- void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction );
-
- /**
- * Add widget name - CreateWidgetFunction pair to container.
- */
- void AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair );
-
- /**
- * Find and get CreateWidgetFunctionPair in container by widget name.
- */
- CreateWidgetFunctionPair GetWidgetCreatingFunctionPair( const std::string& widgetName );
-
- /**
- * Add widget_base_instance_h - Widget instance pair to container.
- */
- void AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget );
-
- /**
- * Find and get Widget instance in container by widget_base_instance_h.
- */
- Dali::Widget GetWidget( widget_base_instance_h widgetBaseInstance );
-
- /**
- * Delete widget_base_instance_h - Widget instance pair in container.
- */
- void DeleteWidget( widget_base_instance_h widgetBaseInstance );
-
-protected:
-
- /**
- * Private Constructor
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- */
- WidgetApplication( int* argc, char **argv[], const std::string& stylesheet );
-
- /**
- * Destructor
- */
- virtual ~WidgetApplication();
-
- // Undefined
- WidgetApplication(const Application&);
- WidgetApplication& operator=(Application&);
-
-private:
-
- typedef std::pair< widget_base_instance_h, Dali::Widget > WidgetInstancePair;
- typedef std::vector< WidgetInstancePair > WidgetInstanceContainer;
-
- CreateWidgetFunctionContainer mCreateWidgetFunctionContainer;
- WidgetInstanceContainer mWidgetInstanceContainer;
-
-};
-
-inline WidgetApplication& GetImplementation(Dali::WidgetApplication& widgetApplication)
-{
- DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
-
- BaseObject& handle = widgetApplication.GetBaseObject();
-
- return static_cast<Internal::Adaptor::WidgetApplication&>(handle);
-}
-
-inline const WidgetApplication& GetImplementation(const Dali::WidgetApplication& widgetApplication)
-{
- DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
-
- const BaseObject& handle = widgetApplication.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::WidgetApplication&>(handle);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_INTERNAL_WIDGET_APPLICATION_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-controller.h"
-
-// EXTERNAL INCLUDES
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Widget::Impl::Impl( widget_base_instance_h instanceHandle )
-: mInstanceHandle( instanceHandle )
-{
-}
-
-Widget::Impl::~Impl()
-{
-}
-
-void Widget::Impl::SetContentInfo( const std::string& contentInfo )
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-controller.h"
-
-// EXTERNAL INCLUDES
-#include <bundle.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Widget::Impl::Impl( widget_base_instance_h instanceHandle )
-: mInstanceHandle( instanceHandle )
-{
-}
-
-Widget::Impl::~Impl()
-{
-}
-
-void Widget::Impl::SetContentInfo( const std::string& contentInfo )
-{
- bundle *contentBundle;
- bundle_raw *contentBundleRaw = reinterpret_cast< bundle_raw* >( const_cast<char*>(contentInfo.c_str()) );
- int len = contentInfo.length();
- contentBundle = bundle_decode(contentBundleRaw, len);
-
- widget_base_context_set_content_info( mInstanceHandle, contentBundle );
-
- bundle_free( contentBundle );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_WIDGET_CONTROLLER_H
-#define DALI_WIDGET_CONTROLLER_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/signals/connection-tracker.h>
-
-// INTERNAL INCLUDES
-#ifdef WIDGET_SUPPOERTED
-#include <widget_base.h>
-#endif
-#include <widget-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief Holds the Implementation for the internal WidgetImpl class
- */
-class Widget::Impl : public ConnectionTracker
-{
-public:
-
-#ifndef WIDGET_SUPPOERTED
- typedef void* widget_base_instance_h;
-#endif
-
- /**
- * Constructor
- */
- Impl( widget_base_instance_h instanceHandle );
-
- /**
- * Destructor
- */
- ~Impl();
-
-public:
-
- /**
- * Set content information to widget framework
- */
- void SetContentInfo( const std::string& contentInfo );
-
-private:
-
- widget_base_instance_h mInstanceHandle;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_WIDGET_CONTROLLER_H
+++ /dev/null
-# tv profile internal files
-adaptor_common_internal_tv_profile_src_files = \
- $(adaptor_tv_dir)/tv-system-settings.cpp \
- $(adaptor_tv_dir)/tv-color-controller-impl.cpp
-
-adaptor_x11_internal_tv_profile_key_src_files = \
- $(adaptor_tv_dir)/key-mapping-tv.cpp
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "key-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-// matches a DALI_KEY enum, to key name
-KeyLookup KeyLookupTable[]=
-{
- // more than one key name can be assigned to a single dali-key code
- // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
-
- { "Escape", DALI_KEY_ESCAPE, false },
- { "Menu", DALI_KEY_MENU, false },
-
- // Now literal strings are used as key names instead of defined symbols in utilX,
- // since these definition in utilX.h is deprecated
- { "XF86Camera", DALI_KEY_CAMERA, false },
- { "XF86Camera_Full", DALI_KEY_CONFIG, false },
- { "XF86PowerOff", DALI_KEY_POWER, true },
- { "XF86Standby", DALI_KEY_PAUSE, false },
- { "Cancel", DALI_KEY_CANCEL, false },
- { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
- { "XF86AudioStop", DALI_KEY_STOP_CD, false },
- { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
- { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
- { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
- { "XF86AudioRewind", DALI_KEY_REWIND, false },
- { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
- { "XF86AudioMedia", DALI_KEY_MEDIA, false },
- { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
- { "XF86AudioMute", DALI_KEY_MUTE, false },
- { "XF86Menu", DALI_KEY_MENU, true },
- { "XF86Home", DALI_KEY_HOME, true },
- { "XF86Back", DALI_KEY_BACK, true },
- { "XF86Send", DALI_KEY_MENU, true },
- { "XF86Phone", DALI_KEY_HOME, true },
- { "XF86Stop", DALI_KEY_BACK, true },
- { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
- { "XF86WWW", DALI_KEY_WEBPAGE, false },
- { "XF86Mail", DALI_KEY_MAIL, false },
- { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
- { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
- { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
- { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
- { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
- { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
- { "XF86Apps", DALI_KEY_APPS, false },
- { "XF86Search", DALI_KEY_SEARCH, false },
- { "XF86Voice", DALI_KEY_VOICE, false },
- { "Hangul", DALI_KEY_LANGUAGE, false },
- { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
- { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
-
- { "BackSpace", DALI_KEY_BACKSPACE, false },
- { "Left", DALI_KEY_CURSOR_LEFT, false },
- { "Right", DALI_KEY_CURSOR_RIGHT, false },
- { "left", DALI_KEY_CURSOR_LEFT, false }, // To be removed after the key name is fixed in the platform
- { "right", DALI_KEY_CURSOR_RIGHT, false }, // To be removed after the key name is fixed in the platform
- { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
- { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
- { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
- { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
- { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
- { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
-};
-
-const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <common/color-controller-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::ColorController ColorController::Get()
-{
- Dali::ColorController colorController;
- return colorController;
-}
-
-ColorController::ColorController()
-{
-}
-
-ColorController::~ColorController()
-{
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
-{
- return false;
-}
-
-bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
-{
- return false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "accessibility-adaptor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
-{
- Dali::AccessibilityAdaptor adaptor;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
- if(handle)
- {
- // If so, downcast the handle
- adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptor() );
- service.Register( typeid( adaptor ), adaptor );
- }
- }
-
- return adaptor;
-}
-
-void AccessibilityAdaptor::OnDestroy()
-{
- // Nothing to do here
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <adaptor-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-void Adaptor::GetDataStoragePath( std::string& path)
-{
- path = DALI_SHADERBIN_DIR;
-}
-
-void Adaptor::GetAppId( std::string& appId )
-{
- appId = "";
-}
-
-void Adaptor::SurfaceInitialized()
-{
-}
-
-void Adaptor::SetupSystemInformation()
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-# ubuntu
-
-adaptor_ubuntu_internal_src_files = \
- $(adaptor_ubuntu_dir)/accessibility-adaptor-impl-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/adaptor-impl-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/framework-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/vsync-monitor-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/tilt-sensor-impl-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/tts-player-impl-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/key-mapping-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/widget-application-impl-ubuntu.cpp \
- $(adaptor_ubuntu_dir)/widget-controller-ubuntu.cpp
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "framework.h"
-
-// EXTERNAL INCLUDES
-#include <Ecore.h>
-#include <Elementary.h>
-#include <X11/Xlib.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <callback-manager.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-/// Application Status Enum
-enum
-{
- APP_CREATE,
- APP_TERMINATE,
- APP_PAUSE,
- APP_RESUME,
- APP_RESET,
- APP_LANGUAGE_CHANGE,
-};
-
-} // Unnamed namespace
-
-/**
- * Impl to hide EFL data members
- */
-struct Framework::Impl
-{
- // Constructor
-
- Impl(void* data)
- : mAbortCallBack( NULL ),
- mCallbackManager( CallbackManager::New() ),
- mLanguage( "NOT_SUPPORTED" ),
- mRegion( "NOT_SUPPORTED" )
- {
- }
-
- ~Impl()
- {
- delete mAbortCallBack;
-
- // we're quiting the main loop so
- // mCallbackManager->RemoveAllCallBacks() does not need to be called
- // to delete our abort handler
- delete mCallbackManager;
- }
-
- std::string GetLanguage() const
- {
- return mLanguage;
- }
-
- std::string GetRegion() const
- {
- return mRegion;
- }
-
- // Data
- CallbackBase* mAbortCallBack;
- CallbackManager *mCallbackManager;
- std::string mLanguage;
- std::string mRegion;
-
- // Static methods
-
- /**
- * Called by AppCore on application creation.
- */
- static bool AppCreate(void *data)
- {
- return static_cast<Framework*>(data)->AppStatusHandler(APP_CREATE, NULL);
- }
-
- /**
- * Called by AppCore when the application should terminate.
- */
- static void AppTerminate(void *data)
- {
- static_cast<Framework*>(data)->AppStatusHandler(APP_TERMINATE, NULL);
- }
-
- /**
- * Called by AppCore when the application is paused.
- */
- static void AppPause(void *data)
- {
- static_cast<Framework*>(data)->AppStatusHandler(APP_PAUSE, NULL);
- }
-
- /**
- * Called by AppCore when the application is resumed.
- */
- static void AppResume(void *data)
- {
- static_cast<Framework*>(data)->AppStatusHandler(APP_RESUME, NULL);
- }
-
- /**
- * Called by AppCore when the language changes on the device.
- */
- static void AppLanguageChange(void* data)
- {
- static_cast<Framework*>(data)->AppStatusHandler(APP_LANGUAGE_CHANGE, NULL);
- }
-
-};
-
-Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
-: mObserver(observer),
- mInitialised(false),
- mRunning(false),
- mArgc(argc),
- mArgv(argv),
- mBundleName(""),
- mBundleId(""),
- mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
- mImpl(NULL)
-{
- InitThreads();
- mImpl = new Impl(this);
-}
-
-Framework::~Framework()
-{
- if (mRunning)
- {
- Quit();
- }
-
- delete mImpl;
-}
-
-void Framework::Run()
-{
- mRunning = true;
-
- elm_init(*mArgc, *mArgv);
-
- Impl::AppCreate(this);
-
- elm_run();
-
- mRunning = false;
-}
-
-void Framework::Quit()
-{
- Impl::AppTerminate(this);
-
- elm_exit();
-}
-
-bool Framework::IsMainLoopRunning()
-{
- return mRunning;
-}
-
-void Framework::AddAbortCallback( CallbackBase* callback )
-{
- mImpl->mAbortCallBack = callback;
-}
-
-std::string Framework::GetBundleName() const
-{
- return mBundleName;
-}
-
-void Framework::SetBundleName(const std::string& name)
-{
- mBundleName = name;
-}
-
-std::string Framework::GetBundleId() const
-{
- return mBundleId;
-}
-
-std::string Framework::GetResourcePath()
-{
- // "DALI_APPLICATION_PACKAGE" is used by Ubuntu specifically to get the already configured Application package path.
- const char* ubuntuEnvironmentVariable = "DALI_APPLICATION_PACKAGE";
- char* value = getenv( ubuntuEnvironmentVariable );
- std::string resourcePath;
- if ( value != NULL )
- {
- resourcePath = value;
- }
-
- return resourcePath;
-}
-
-void Framework::SetBundleId(const std::string& id)
-{
- mBundleId = id;
-}
-
-void Framework::AbortCallback( )
-{
- // if an abort call back has been installed run it.
- if (mImpl->mAbortCallBack)
- {
- CallbackBase::Execute( *mImpl->mAbortCallBack );
- }
- else
- {
- Quit();
- }
-}
-
-bool Framework::AppStatusHandler(int type, void *bundleData)
-{
- switch (type)
- {
- case APP_CREATE:
- {
- mInitialised = true;
-
- mObserver.OnInit();
- break;
- }
-
- case APP_RESET:
- mObserver.OnReset();
- break;
-
- case APP_RESUME:
- mObserver.OnResume();
- break;
-
- case APP_TERMINATE:
- mObserver.OnTerminate();
- break;
-
- case APP_PAUSE:
- mObserver.OnPause();
- break;
-
- case APP_LANGUAGE_CHANGE:
- mObserver.OnLanguageChanged();
- break;
-
- default:
- break;
- }
-
- return true;
-}
-
-void Framework::InitThreads()
-{
- XInitThreads();
-}
-
-std::string Framework::GetLanguage() const
-{
- return mImpl->GetLanguage();
-}
-
-std::string Framework::GetRegion() const
-{
- return mImpl->GetRegion();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "key-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-// matches a DALI_KEY enum, to a key name
-KeyLookup KeyLookupTable[]=
-{
- // more than one key name can be assigned to a single dali-key code
- // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
-
- { "Escape", DALI_KEY_ESCAPE, false },
- { "Menu", DALI_KEY_MENU, false },
-
- // Now literal strings are used as key names instead of defined symbols in utilX,
- // since these definition in utilX.h is deprecated
- { "XF86Camera", DALI_KEY_CAMERA, false },
- { "XF86Camera_Full", DALI_KEY_CONFIG, false },
- { "XF86PowerOff", DALI_KEY_POWER, true },
- { "XF86Standby", DALI_KEY_PAUSE, false },
- { "Cancel", DALI_KEY_CANCEL, false },
- { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
- { "XF86AudioStop", DALI_KEY_STOP_CD, false },
- { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
- { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
- { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
- { "XF86AudioRewind", DALI_KEY_REWIND, false },
- { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
- { "XF86AudioMedia", DALI_KEY_MEDIA, false },
- { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
- { "XF86AudioMute", DALI_KEY_MUTE, false },
- { "XF86Menu", DALI_KEY_MENU, true },
- { "XF86Home", DALI_KEY_HOME, true },
- { "XF86Back", DALI_KEY_BACK, true },
- { "XF86Send", DALI_KEY_MENU, true },
- { "XF86Phone", DALI_KEY_HOME, true },
- { "XF86Stop", DALI_KEY_BACK, true },
- { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
- { "XF86WWW", DALI_KEY_WEBPAGE, false },
- { "XF86Mail", DALI_KEY_MAIL, false },
- { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
- { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
- { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
- { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
- { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
- { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
- { "XF86Apps", DALI_KEY_APPS, false },
- { "XF86Search", DALI_KEY_SEARCH, false },
- { "XF86Voice", DALI_KEY_VOICE, false },
- { "Hangul", DALI_KEY_LANGUAGE, false },
- { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
- { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
-
- { "BackSpace", DALI_KEY_BACKSPACE, false },
- { "Left", DALI_KEY_CURSOR_LEFT, false },
- { "Right", DALI_KEY_CURSOR_RIGHT, false },
- { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
- { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
- { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
- { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
- { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
- { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
-};
-
-const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tilt-sensor-impl.h"
-
-// EXTERNAL INCLUDES
-#include <cmath>
-
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-namespace // unnamed namespace
-{
-
-const char* const SIGNAL_TILTED = "tilted";
-
-const int NUMBER_OF_SAMPLES = 10;
-
-const float MAX_ACCELEROMETER_XY_VALUE = 9.8f;
-
-// Type Registration
-Dali::BaseHandle GetInstance()
-{
- return Dali::Internal::Adaptor::TiltSensor::Get();
-}
-
-Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), GetInstance );
-
-Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal );
-
-} // unnamed namespace
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Dali::TiltSensor TiltSensor::New()
-{
- Dali::TiltSensor sensor = Dali::TiltSensor(new TiltSensor());
-
- return sensor;
-}
-
-Dali::TiltSensor TiltSensor::Get()
-{
- Dali::TiltSensor sensor;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the keyboard focus manager is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::TiltSensor ) );
- if(handle)
- {
- // If so, downcast the handle of singleton to keyboard focus manager
- sensor = Dali::TiltSensor( dynamic_cast< TiltSensor* >( handle.GetObjectPtr() ) );
- }
- else
- {
- // Create a singleton instance
- sensor = TiltSensor::New();
- service.Register( typeid( sensor ), sensor );
- handle = sensor;
- }
- }
-
- return sensor;
-}
-
-TiltSensor::~TiltSensor()
-{
- Stop();
-}
-
-bool TiltSensor::Start()
-{
- // Make sure sensor API is responding
- bool success = Update();
-
- if ( success )
- {
- if ( !mTimer )
- {
- mTimer = Dali::Timer::New( 1000.0f / mFrequencyHertz );
- mTimer.TickSignal().Connect( mTimerSlot, &TiltSensor::Update );
- }
-
- if ( mTimer &&
- !mTimer.IsRunning() )
- {
- mTimer.Start();
- }
- }
-
- return success;
-}
-
-void TiltSensor::Stop()
-{
- if ( mTimer )
- {
- mTimer.Stop();
- mTimer.Reset();
- }
-}
-
-bool TiltSensor::IsStarted() const
-{
- return ( mTimer && mTimer.IsRunning() );
-}
-
-float TiltSensor::GetRoll() const
-{
- return mRoll;
-}
-
-float TiltSensor::GetPitch() const
-{
- return mPitch;
-}
-
-Quaternion TiltSensor::GetRotation() const
-{
- return mRotation;
-}
-
-TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal()
-{
- return mTiltedSignal;
-}
-
-void TiltSensor::SetUpdateFrequency( float frequencyHertz )
-{
- DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" );
-
- if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) )
- {
- mFrequencyHertz = frequencyHertz;
-
- if ( mTimer )
- {
- mTimer.SetInterval( 1000.0f / mFrequencyHertz );
- }
- }
-}
-
-float TiltSensor::GetUpdateFrequency() const
-{
- return mFrequencyHertz;
-}
-
-void TiltSensor::SetRotationThreshold(Radian rotationThreshold)
-{
- mRotationThreshold = rotationThreshold;
-}
-
-Radian TiltSensor::GetRotationThreshold() const
-{
- return mRotationThreshold;
-}
-
-bool TiltSensor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
-{
- bool connected( true );
- TiltSensor* sensor = dynamic_cast<TiltSensor*>( object );
-
- if( sensor && ( SIGNAL_TILTED == signalName ) )
- {
- sensor->TiltedSignal().Connect( tracker, functor );
- }
- else
- {
- // signalName does not match any signal
- connected = false;
- }
-
- return connected;
-}
-
-TiltSensor::TiltSensor()
-: mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ),
- mTimerSlot( this ),
- mSensorFrameworkHandle( -1 ),
- mRoll( 0.0f ),
- mPitch( 0.0f ),
- mRotation( Dali::ANGLE_0, Vector3::YAXIS ),
- mRotationThreshold( 0.0f )
-{
- mRollValues.resize( NUMBER_OF_SAMPLES, 0.0f );
- mPitchValues.resize( NUMBER_OF_SAMPLES, 0.0f );
-}
-
-bool TiltSensor::Update()
-{
- float newRoll = 0.0f;
- float newPitch = 0.0f;
- Quaternion newRotation;
-
- Radian angle(Quaternion::AngleBetween(newRotation, mRotation));
- // If the change in value is more than the threshold then emit tilted signal.
- if( angle > mRotationThreshold )
- {
- mRoll = newRoll;
- mPitch = newPitch;
- mRotation = newRotation;
-
- if ( !mTiltedSignal.Empty() )
- {
- Dali::TiltSensor handle( this );
- mTiltedSignal.Emit( handle );
- }
- }
-
- return true;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
-#define __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <deque>
-#include <dali/public-api/object/base-object.h>
-
-// INTERNAL INCLUDES
-#include <tilt-sensor.h>
-#include <timer.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * TiltSensor provides pitch & roll values when the device is tilted.
- */
-class TiltSensor : public Dali::BaseObject
-{
-public:
-
- typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType;
-
- /**
- * Create a TiltSensor.
- * This should only be called once by the Adaptor class.
- * @return A newly allocated tilt-sensor.
- */
- static Dali::TiltSensor New();
-
- /**
- * @copydoc Dali::TiltSensor::Get()
- */
- static Dali::TiltSensor Get();
-
- /**
- * @copydoc Dali::TiltSensor::Start()
- */
- bool Start();
-
- /**
- * @copydoc Dali::TiltSensor::Stop()
- */
- void Stop();
-
- /**
- * @copydoc Dali::TiltSensor::IsStarted()
- */
- bool IsStarted() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetRoll()
- */
- float GetRoll() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetPitch()
- */
- float GetPitch() const;
-
- /**
- * @copydoc Dali::TiltSensor::GetRotation()
- */
- Quaternion GetRotation() const;
-
- /**
- * @copydoc Dali::TiltSensor::TiltedSignal()
- */
- TiltedSignalType& TiltedSignal();
-
- /**
- * @copydoc Dali::TiltSensor::SetUpdateFrequency()
- */
- void SetUpdateFrequency( float frequencyHertz );
-
- /**
- * @copydoc Dali::TiltSensor::GetUpdateFrequency()
- */
- float GetUpdateFrequency() const;
-
- /**
- * @copydoc Dali::TiltSensor::SetRotationThreshold()
- */
- void SetRotationThreshold(Radian rotationThreshold);
-
- /**
- * @copydoc Dali::TiltSensor::GetRotationThreshold()
- */
- Radian GetRotationThreshold() const;
-
- /**
- * Connects a callback function with the object's signals.
- * @param[in] object The object providing the signal.
- * @param[in] tracker Used to disconnect the signal.
- * @param[in] signalName The signal to connect to.
- * @param[in] functor A newly allocated FunctorDelegate.
- * @return True if the signal was connected.
- * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
- */
- static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
-
-private:
-
- /**
- * Private constructor; see also TiltSensor::New()
- */
- TiltSensor();
-
- /**
- * Destructor
- */
- virtual ~TiltSensor();
-
- /**
- * Timer callback to update the tilt values
- */
- bool Update();
-
- // Undefined
- TiltSensor(const TiltSensor&);
-
- // Undefined
- TiltSensor& operator=(TiltSensor&);
-
-private:
-
- float mFrequencyHertz;
- Dali::Timer mTimer;
- SlotDelegate< TiltSensor > mTimerSlot;
-
- int mSensorFrameworkHandle;
-
- float mRoll;
- float mPitch;
- Quaternion mRotation;
-
- Radian mRotationThreshold;
-
- std::deque<float> mRollValues;
- std::deque<float> mPitchValues;
-
- TiltedSignalType mTiltedSignal;
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::TiltSensor& GetImplementation(Dali::TiltSensor& sensor)
-{
- DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
-
- BaseObject& handle = sensor.GetBaseObject();
-
- return static_cast<Internal::Adaptor::TiltSensor&>(handle);
-}
-
-inline const Internal::Adaptor::TiltSensor& GetImplementation(const Dali::TiltSensor& sensor)
-{
- DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
-
- const BaseObject& handle = sensor.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::TiltSensor&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ADAPTOR_TILT_SENSOR_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tts-player-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* TtsPlayer::gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TTS_PLAYER");
-#endif
-
-Dali::TtsPlayer TtsPlayer::New(Dali::TtsPlayer::Mode mode)
-{
- Dali::TtsPlayer player = Dali::TtsPlayer(new TtsPlayer(mode));
-
- return player;
-}
-
-TtsPlayer::TtsPlayer(Dali::TtsPlayer::Mode mode)
-: mStateChangedSignal()
-{
- DALI_LOG_ERROR("TTS is not implemented in UBUNTU profile.\n");
-}
-
-TtsPlayer::~TtsPlayer()
-{
-}
-
-void TtsPlayer::Play(const std::string& text)
-{
-}
-
-void TtsPlayer::Stop()
-{
-}
-
-void TtsPlayer::Pause()
-{
-}
-
-void TtsPlayer::Resume()
-{
-}
-
-Dali::TtsPlayer::State TtsPlayer::GetState()
-{
- return Dali::TtsPlayer::UNAVAILABLE;
-}
-
-Dali::TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal()
-{
- return mStateChangedSignal;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_TTS_PLAYER_H__
-#define __DALI_INTERNAL_TTS_PLAYER_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-
-#include <string>
-
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/base-object.h>
-#include <tts-player.h>
-
-// INTERNAL INCLUDES
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Text-to-speech player
- */
-class TtsPlayer : public Dali::BaseObject
-{
-
-public:
-
- /**
- * Create a TtsPlayer with the given mode.
- * This should only be called once by the Adaptor class for each given mode.
- * @param mode the mode of tts-player
- * @return A newly created TtsPlayer.
- */
- static Dali::TtsPlayer New(Dali::TtsPlayer::Mode mode);
-
- /**
- * @copydoc TtsPlayer::Play()
- */
- void Play(const std::string& text);
-
- /**
- * @copydoc TtsPlayer::Stop()
- */
- void Stop();
-
- /**
- * @copydoc TtsPlayer::Pause()
- */
- void Pause();
-
- /**
- * @copydoc TtsPlayer::Resume()
- */
- void Resume();
-
- /**
- * @copydoc TtsPlayer::GetState()
- */
- Dali::TtsPlayer::State GetState();
-
- /**
- * @copydoc TtsPlayer::StateChangedSignal()
- */
- Dali::TtsPlayer::StateChangedSignalType& StateChangedSignal();
-
-private:
-
- /**
- * Private Constructor; see also TtsPlayer::New()
- * @param mode the mode of tts-player
- */
- TtsPlayer(Dali::TtsPlayer::Mode mode);
-
- /**
- * Destructor
- */
- virtual ~TtsPlayer();
-
-private:
-
- Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes (non-functional, for interface compatibility).
-
-#if defined(DEBUG_ENABLED)
-public:
- static Debug::Filter* gLogFilter;
-#endif
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-// Helpers for public-api forwarding methods
-
-inline Internal::Adaptor::TtsPlayer& GetImplementation(Dali::TtsPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
-
- BaseObject& handle = player.GetBaseObject();
-
- return static_cast<Internal::Adaptor::TtsPlayer&>(handle);
-}
-
-inline const Internal::Adaptor::TtsPlayer& GetImplementation(const Dali::TtsPlayer& player)
-{
- DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
-
- const BaseObject& handle = player.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::TtsPlayer&>(handle);
-}
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_TTS_PLAYER_H__
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "vsync-monitor.h"
-
-// EXTERNAL INCLUDES
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-// constants to keep code readability with unsigned int has to be used as boolean (due to multithreading)
-const unsigned int TRUE = 1u;
-const unsigned int FALSE = 0u;
-
-const int FD_NONE( -1 );
-
-} // unnamed namespace
-
-VSyncMonitor::VSyncMonitor()
-: mFileDescriptor( FD_NONE ),
- mUseHardwareVSync( FALSE ),
- mHardwareVSyncAvailable( FALSE )
-{
-}
-
-VSyncMonitor::~VSyncMonitor()
-{
- Terminate();
-}
-
-void VSyncMonitor::SetUseHardwareVSync( bool useHardware )
-{
- mUseHardwareVSync = useHardware;
-}
-
-void VSyncMonitor::SetHardwareVSyncAvailable( bool hardwareVSyncAvailable )
-{
- mHardwareVSyncAvailable = hardwareVSyncAvailable;
-}
-
-void VSyncMonitor::Initialize()
-{
- DALI_ASSERT_DEBUG( mFileDescriptor == FD_NONE && "VSyncMonitor::Initialize() called twice" );
-
- // setup vblank request - block and wait for next vblank
- mVBlankInfo.request.type = DRM_VBLANK_NEXTONMISS;
- mVBlankInfo.request.sequence = 0;
- mVBlankInfo.request.signal = 0;
-
- // setup vblank reply - block and wait for next vblank
- mVBlankInfo.reply.type = DRM_VBLANK_NEXTONMISS;
- mVBlankInfo.reply.sequence = 0;
- mVBlankInfo.reply.tval_sec = 0;
- mVBlankInfo.reply.tval_usec = 0;
-}
-
-void VSyncMonitor::Terminate()
-{
-}
-
-bool VSyncMonitor::UseHardware()
-{
- return mUseHardwareVSync && mHardwareVSyncAvailable && (FD_NONE != mFileDescriptor );
-}
-
-
-bool VSyncMonitor::DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds )
-{
- DALI_ASSERT_DEBUG( mFileDescriptor != FD_NONE && "ECoreX::VSyncMonitor is not initialized" );
-
- if( 0 == drmWaitVBlank( mFileDescriptor, &mVBlankInfo ) )
- {
- frameNumber = mVBlankInfo.reply.sequence;
- seconds = mVBlankInfo.reply.tval_sec;
- microseconds = mVBlankInfo.reply.tval_usec;
-
- return true;
- }
-
- return false;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-application-impl.h"
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-WidgetApplicationPtr WidgetApplication::New(
- int* argc,
- char **argv[],
- const std::string& stylesheet)
-{
- WidgetApplicationPtr widgetApplication( new WidgetApplication (argc, argv, stylesheet ) );
- return widgetApplication;
-}
-
-WidgetApplication::WidgetApplication( int* argc, char** argv[], const std::string& stylesheet )
-:Application(argc, argv, stylesheet, Dali::WidgetApplication::OPAQUE, PositionSize(), Framework::NORMAL)
-{
- DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n");
-}
-
-WidgetApplication::~WidgetApplication()
-{
-}
-
-
-void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_WIDGET_APPLICATION_H
-#define DALI_INTERNAL_WIDGET_APPLICATION_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <application-impl.h>
-#include <widget-application.h>
-
-namespace Dali
-{
-class Widget;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class WidgetApplication;
-typedef IntrusivePtr<WidgetApplication> WidgetApplicationPtr;
-
-/**
- * Implementation of the WidgetApplication class.
- */
-class WidgetApplication : public Application
-{
-public:
-
- typedef std::pair<const std::string, Dali::WidgetApplication::CreateWidgetFunction > CreateWidgetFunctionPair;
- typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer;
-
- /**
- * Create a new widget application
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- */
- static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet );
-
-public:
-
- /**
- * @copydoc Dali::WidgetApplication::RegisterWidgetCreator()
- */
- void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction );
-
-protected:
-
- /**
- * Private Constructor
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- */
- WidgetApplication( int* argc, char **argv[], const std::string& stylesheet );
-
- /**
- * Destructor
- */
- virtual ~WidgetApplication();
-
- // Undefined
- WidgetApplication(const Application&);
- WidgetApplication& operator=(Application&);
-
-
-};
-
-inline WidgetApplication& GetImplementation(Dali::WidgetApplication& widgetApplication)
-{
- DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
-
- BaseObject& handle = widgetApplication.GetBaseObject();
-
- return static_cast<Internal::Adaptor::WidgetApplication&>(handle);
-}
-
-inline const WidgetApplication& GetImplementation(const Dali::WidgetApplication& widgetApplication)
-{
- DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
-
- const BaseObject& handle = widgetApplication.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::WidgetApplication&>(handle);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_INTERNAL_WIDGET_APPLICATION_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "widget-controller.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-Widget::Impl::Impl()
-{
-}
-
-Widget::Impl::~Impl()
-{
-}
-
-void Widget::Impl::SetContentInfo( const std::string& contentInfo )
-{
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_WIDGET_CONTROLLER_H
-#define DALI_WIDGET_CONTROLLER_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/signals/connection-tracker.h>
-
-// INTERNAL INCLUDES
-#include <widget-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief Holds the Implementation for the internal WidgetImpl class
- */
-class Widget::Impl : public ConnectionTracker
-{
-public:
-
- /**
- * Constructor
- */
- Impl();
-
- /**
- * Destructor
- */
- ~Impl();
-
-public:
-
- /**
- * Set content information to widget framework
- */
- void SetContentInfo( const std::string& contentInfo );
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // DALI_WIDGET_CONTROLLER_H
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "clipboard-impl.h"
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Clipboard
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-struct Clipboard::Impl
-{
- Impl()
- {
- }
-
- // Put implementation here.
-};
-
-Clipboard::Clipboard(Impl* impl)
-: mImpl(impl)
-{
-}
-
-Clipboard::~Clipboard()
-{
- delete mImpl;
-}
-
-Dali::Clipboard Clipboard::Get()
-{
- Dali::Clipboard clipboard;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) );
- if(handle)
- {
- // If so, downcast the handle
- clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) );
- }
- else
- {
- Clipboard::Impl* impl( new Clipboard::Impl() );
- clipboard = Dali::Clipboard( new Clipboard(impl) );
- service.Register( typeid(Dali::Clipboard), clipboard );
- }
- }
-
- return clipboard;
-}
-bool Clipboard::SetItem(const std::string &itemData )
-{
- return true;
-}
-
-/*
- * Request clipboard service to retrieve an item
- */
-void Clipboard::RequestItem()
-{
-}
-
-/*
- * Get number of items in clipboard
- */
-unsigned int Clipboard::NumberOfItems()
-{
- return -1;
-}
-
-/**
- * Show clipboard window
- * Function to send message to show the Clipboard (cbhm) as no direct API available
- * Reference elementary/src/modules/ctxpopup_copypasteUI/cbhm_helper.c
- */
-void Clipboard::ShowClipboard()
-{
-}
-
-void Clipboard::HideClipboard(bool skipFirstHide)
-{
-}
-
-bool Clipboard::IsVisible() const
-{
- return false;
-}
-
-char* Clipboard::ExcuteBuffered( bool type, void *event )
-{
- return NULL;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "compositor-output.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_MONITOR_INFO");
-#endif
-
-const float MILLIMETRE_TO_INCH = 1.f / 25.4f;
-
-unsigned int gDpiHorizontal = 75;
-unsigned int gDpiVertical = 75;
-
-
-void OutputGeometryCallback( void *data,
- struct wl_output *wl_output,
- int32_t x,
- int32_t y,
- int32_t physical_width,
- int32_t physical_height,
- int32_t subpixel,
- const char *make,
- const char *model,
- int32_t transform)
-{
- CompositorOutput* output = static_cast< CompositorOutput* >( data );
- output->SetMonitorDimensions( physical_width, physical_height );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "Monitor width: %d mm, height: %d mm\n",physical_width, physical_height );
-}
-
-void OutputModeCallback( void *data,
- struct wl_output *wl_output,
- uint32_t flags,
- int32_t width,
- int32_t height,
- int32_t refresh )
-{
-
- if (flags & WL_OUTPUT_MODE_CURRENT)
- {
- CompositorOutput* output = static_cast< CompositorOutput* >( data );
- output->SetMonitorResolution( width, height );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "Monitor refresh rate: %f Hz, resolution: %d x %d\n", static_cast<float>(refresh)/ 1000.f, width, height );
- }
-}
-
-void OutputCallbackDone(void *data,
- struct wl_output *wl_output)
-{
- CompositorOutput* output = static_cast< CompositorOutput* >( data );
- output->CallbacksDone();
-}
-
-void OutputCallbackScale(void *data,
- struct wl_output *wl_output,
- int32_t factor)
-{
- // Need to understand if we need to support output scaling and what impact it has on input handling etc.
-}
-
-
-
-//output typically corresponds to a monitor
-const struct wl_output_listener OutputListener =
-{
- OutputGeometryCallback,
- OutputModeCallback,
- OutputCallbackDone,
- OutputCallbackScale
-};
-}
-CompositorOutput::CompositorOutput()
-:mOutput( NULL ),
- mXresolution( 0 ),
- mYresolution( 0 ),
- mMonitorWidth( 0.f ),
- mMonitorHeight( 0.f ),
- mDataReady( false )
-{
-
-}
-
-CompositorOutput::~CompositorOutput()
-{
- if( mOutput )
- {
- wl_output_destroy( mOutput );
- }
-}
-
-void CompositorOutput::AddListener( WlOutput* outputInterface )
-{
- mOutput = outputInterface;
-
- wl_output_add_listener( mOutput , &OutputListener, this);
-}
-
-void CompositorOutput::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical )
-{
- dpiHorizontal = gDpiHorizontal;
- dpiVertical = gDpiVertical;
-}
-
-bool CompositorOutput::DataReady() const
-{
- return mDataReady;
-}
-
-void CompositorOutput::SetMonitorDimensions( unsigned int width, unsigned int height )
-{
- mMonitorHeight = static_cast<float> ( height ) * MILLIMETRE_TO_INCH;
- mMonitorWidth = static_cast<float>( width ) * MILLIMETRE_TO_INCH;
-}
-
-void CompositorOutput::SetMonitorResolution( unsigned int width, unsigned int height )
-{
- mXresolution = width;
- mYresolution = height;
-}
-
-void CompositorOutput::CallbacksDone()
-{
- mDataReady = true;
-
- // formula for DPI is screen resolution / physical size in inches
- gDpiHorizontal = (static_cast<float>( mXresolution) / mMonitorWidth) + 0.5f;
- gDpiVertical = (static_cast<float>( mYresolution )/ mMonitorHeight) +0.5f;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "Monitor DPI %d x %d\n", gDpiHorizontal, gDpiVertical );
-}
-
-
-
-
-} // Internal
-} // Adaptor
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_COMPOSITOR_OUTPUT_H__
-#define __DALI_INTERNAL_ADAPTOR_COMPOSITOR_OUTPUT_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- *
- * An output is typically a monitor with Wayland.
- * The output is required to view a region of the compositor space.
- * E.g. a monitor may be display the entire compositor space, or just a
- * region of that space.
- * The output interface is published as global during start up, or when a monitor is
- * hotplugged.
- *
- * Information available from the output includes
- * - refresh rate
- * - monitor dimensions in millimetres
- * - monitor resolution
- *
- * We can use this information to calculate DPI for displaying text
- */
-
-class CompositorOutput
-{
-
-public:
-
-
- /**
- * @brief constructor
- * @param[in] inputInterface input interface
- * @param[in] seatInterface Wayland seat interface
- */
- CompositorOutput();
-
- /**
- * @brief non virtual destructor, not intended as base class
- */
- ~CompositorOutput();
-
- /**
- * @brief listen to output callbacks
- * @param outputInterface[in] output interface
- */
- void AddListener( WlOutput* outputInterface );
-
- /**
- * @brief Get DPI
- * @param[out] dpiHorizontal set to the horizontal DPI
- * @param[out] dpiVertical set to the vertical DPI
- */
- static void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical );
-
-
- /**
- * @brief return true if all information about the compositor output has been received
- * and is ready to be read
- * @return true if ready
- */
- bool DataReady() const;
-
-
- /**
- * @brief Set monitor size in millimetres
- * @param[in] width width
- * @param[in] height height
- */
- void SetMonitorDimensions( unsigned int width, unsigned int height );
-
- /**
- * @brief Set monitor resolution in pixels
- * @param[in] width width
- * @param[in] height height
- */
- void SetMonitorResolution( unsigned int width, unsigned int height );
-
-
- /**
- * @brief Called when all callbacks have finished
- * at this point we calculate DPI
- */
- void CallbacksDone();
-
-private:
-
- // @brief Undefined copy constructor.
- CompositorOutput( const CompositorOutput& );
-
- // @brief Undefined assignment operator.
- CompositorOutput& operator=( const CompositorOutput& );
-
- WlOutput* mOutput; ///< Compositor output ( info for attached monitor)
- unsigned int mXresolution; ///< Monitor resolution in pixel
- unsigned int mYresolution; ///< Monitor resolution in pixel
- float mMonitorWidth; ///< width in inches
- float mMonitorHeight; ///< height in inches
- bool mDataReady:1;
-
-};
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_INTERNAL_ADAPTOR_COMPOSITOR_OUTPUT_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "display-connection-impl.h"
-
-// INTERNAL INCLUDES
-#include "compositor-output-region/compositor-output.h"
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-DisplayConnection* DisplayConnection::New()
-{
- return new DisplayConnection();
-}
-
-DisplayConnection::DisplayConnection()
-: mDisplay(NULL)
-{
-}
-
-DisplayConnection::~DisplayConnection()
-{
-
-}
-
-Any DisplayConnection::GetDisplay()
-{
- return Any(mDisplay);
-}
-
-void DisplayConnection::ConsumeEvents()
-{
-}
-
-bool DisplayConnection::InitializeEgl(EglInterface& egl)
-{
- return true;
-}
-
-void DisplayConnection::SetSurfaceType( RenderSurface::Type type )
-{
-}
-
-void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
-{
- CompositorOutput::GetDpi( dpiHorizontal, dpiVertical);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_WAYLAND_DIPLAY_CONNECTION_H__
-#define __DALI_INTERNAL_WAYLAND_DIPLAY_CONNECTION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wayland-egl.h>
-#include <wl-types.h>
-
-// INTERNAL INCLUDES
-#include <base/display-connection.h>
-#include <dali/public-api/object/base-object.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-class DisplayConnection;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * DisplayConnection implementation
- */
-class DisplayConnection : public Dali::BaseObject
-{
-public:
-
- /**
- * @brief Default constructor
- */
- DisplayConnection();
-
- /**
- * @brief Create an initialized DisplayConnection.
- *
- * @return A handle to a newly allocated DisplayConnection resource.
- */
- static DisplayConnection* New();
-
-public:
-
- /**
- * @copydoc Dali::DisplayConnection::GetDisplay
- */
- Any GetDisplay();
-
- /**
- * @copydoc Dali::DisplayConnection::GetDpi
- */
- static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
-
- /**
- * @copydoc Dali::DisplayConnection::ConsumeEvents
- */
- void ConsumeEvents();
-
- /**
- * @copydoc Dali::DisplayConnection::InitializeEgl
- */
- bool InitializeEgl(EglInterface& egl);
-
- void SetSurfaceType( RenderSurface::Type type );
-
-public:
-
- /**
- * Destructor
- */
- virtual ~DisplayConnection();
-
-protected:
-
- EGLNativeDisplayType GetNativeDisplay();
-
- void ReleaseNativeDisplay();
-
- // Undefined
- DisplayConnection(const DisplayConnection&);
-
- // Undefined
- DisplayConnection& operator=(const DisplayConnection& rhs);
-
-private:
- WlDisplay* mDisplay; ///< Wayland-display for rendering
-};
-
-} // namespace Adaptor
-
-} // namespace internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_WAYLAND_DIPLAY_CONNECTION_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <events/event-handler.h>
-
-// EXTERNAL INCLUDES
-#include <cstring>
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/events/key-event.h>
-#include <dali/public-api/events/wheel-event.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/events/key-event-integ.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <dali/integration-api/events/hover-event-integ.h>
-#include <dali/integration-api/events/wheel-event-integ.h>
-
-
-// INTERNAL INCLUDES
-#include <render-surface/render-surface-wl.h>
-#include <events/gesture-manager.h>
-#include <key-impl.h>
-#include <clipboard.h>
-#include <physical-keyboard-impl.h>
-#include <style-monitor-impl.h>
-#include <base/core-event-interface.h>
-#include <base/interfaces/window-event-interface.h>
-
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-namespace
-{
- Integration::Log::Filter* gTouchEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_TOUCH");
-} // unnamed namespace
-#endif
-
-struct EventHandler::Impl : public WindowEventInterface
-{
- // Construction & Destruction
-
- /**
- * Constructor
- */
- Impl( EventHandler* handler )
- : mHandler( handler ),
- mPaused( false )
- {
- }
- /**
- * Destructor
- */
- ~Impl()
- {
- }
- // @todo Consider allowing the EventHandler class to inherit from WindowEventInterface directly
- virtual void TouchEvent( Dali::Integration::Point& point, unsigned long timeStamp )
- {
- mHandler->SendEvent( point, timeStamp );
- }
- virtual void KeyEvent( Integration::KeyEvent& keyEvent )
- {
- mHandler->SendEvent( keyEvent );
- }
- virtual void WheelEvent( Dali::WheelEvent& wheelEvent )
- {
- mHandler->SendWheelEvent( wheelEvent );
- }
- virtual void DamageEvent( Rect<int>& damageArea )
- {
- mHandler->SendEvent( damageArea );
- }
- virtual void WindowFocusOut( )
- {
- // used to do some work with ime
- }
- virtual void WindowFocusIn()
- {
- // used to do some work with ime
- }
- // Data
- EventHandler* mHandler;
- bool mPaused;
-};
-
-/**
- * @TODO the event handler code seems to be common across all adaptors, could do with moving into common
- *
- */
-EventHandler::EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector )
-: mCoreEventInterface(coreEventInterface),
- mGestureManager( gestureManager ),
- mStyleMonitor( StyleMonitor::Get() ),
- mDamageObserver( damageObserver ),
- mRotationObserver( NULL ),
- mDragAndDropDetector( dndDetector ),
- mClipboardEventNotifier( ClipboardEventNotifier::Get() ),
- mClipboard( Dali::Clipboard::Get()),
- mImpl( NULL ),
- mPaused( false )
-{
-
-
- // this code only works with the wayland RenderSurface so need to downcast
- Wayland::RenderSurface* waylandSurface = dynamic_cast< Wayland::RenderSurface* >( surface );
-
- mImpl = new Impl(this );
-
- if( waylandSurface )
- {
- waylandSurface->AssignWindowEventInterface( mImpl );
- }
-}
-
-EventHandler::~EventHandler()
-{
- if(mImpl)
- {
- delete mImpl;
- }
-
- mGestureManager.Stop();
-}
-
-void EventHandler::SendEvent(Integration::Point& point, unsigned long timeStamp)
-{
-
- Integration::TouchEvent touchEvent;
- Integration::HoverEvent hoverEvent;
- Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent(point, timeStamp, touchEvent, hoverEvent);
- if(type != Integration::TouchEventCombiner::DispatchNone )
- {
- DALI_LOG_INFO(gTouchEventLogFilter, Debug::General, "%d: Device %d: Button state %d (%.2f, %.2f)\n", timeStamp, point.GetDeviceId(), point.GetState(), point.GetLocalPosition().x, point.GetLocalPosition().y);
-
- // First the touch and/or hover event & related gesture events are queued
- if(type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( touchEvent );
- mGestureManager.SendEvent(touchEvent);
- }
-
- if(type == Integration::TouchEventCombiner::DispatchHover || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( hoverEvent );
- }
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
- }
-}
-
-void EventHandler::SendEvent(Integration::KeyEvent& keyEvent)
-{
- Dali::PhysicalKeyboard physicalKeyboard = PhysicalKeyboard::Get();
- if ( physicalKeyboard )
- {
- if ( ! KeyLookup::IsDeviceButton( keyEvent.keyName.c_str() ) )
- {
- GetImplementation( physicalKeyboard ).KeyReceived( keyEvent.time > 1 );
- }
- }
-
- // Create send KeyEvent to Core.
- mCoreEventInterface.QueueCoreEvent( keyEvent );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendWheelEvent( WheelEvent& wheelEvent )
-{
- // Create WheelEvent and send to Core.
- Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >(wheelEvent.type), wheelEvent.direction, wheelEvent.modifiers, wheelEvent.point, wheelEvent.z, wheelEvent.timeStamp );
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendEvent( StyleChange::Type styleChange )
-{
- DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" );
- GetImplementation( mStyleMonitor ).StyleChanged(styleChange);
-}
-
-void EventHandler::SendEvent( const DamageArea& area )
-{
- mDamageObserver.OnDamaged( area );
-}
-
-void EventHandler::SendRotationPrepareEvent( const RotationEvent& event )
-{
- if( mRotationObserver != NULL )
- {
- mRotationObserver->OnRotationPrepare( event );
- }
-}
-
-void EventHandler::SendRotationRequestEvent( )
-{
- if( mRotationObserver != NULL )
- {
- mRotationObserver->OnRotationRequest( );
- }
-}
-
-void EventHandler::FeedTouchPoint( TouchPoint& point, int timeStamp)
-{
- Integration::Point convertedPoint( point );
- SendEvent(convertedPoint, timeStamp);
-}
-
-void EventHandler::FeedWheelEvent( WheelEvent& wheelEvent )
-{
- SendWheelEvent( wheelEvent );
-}
-
-void EventHandler::FeedKeyEvent( KeyEvent& event )
-{
- Integration::KeyEvent convertedEvent( event );
- SendEvent( convertedEvent );
-}
-
-void EventHandler::FeedEvent( Integration::Event& event )
-{
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Reset()
-{
- mCombiner.Reset();
-
- // Any touch listeners should be told of the interruption.
- Integration::TouchEvent event;
- Integration::Point point;
- point.SetState( PointState::INTERRUPTED );
- event.AddPoint( point );
-
- // First the touch event & related gesture events are queued
- mCoreEventInterface.QueueCoreEvent( event );
- mGestureManager.SendEvent( event );
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Pause()
-{
- mPaused = true;
- Reset();
-}
-
-void EventHandler::Resume()
-{
- mPaused = false;
- Reset();
-}
-
-void EventHandler::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
-{
- mDragAndDropDetector = detector;
-}
-
-void EventHandler::SetRotationObserver( RotationObserver* observer )
-{
- mRotationObserver = observer;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-# wayland
-
-adaptor_wayland_tizen_internal_src_files = \
- $(adaptor_wayland_dir)/wayland-window.cpp \
- $(adaptor_wayland_dir)/window-impl-wl.cpp \
- $(adaptor_wayland_dir)/display-connection-impl-wl.cpp \
- $(adaptor_wayland_dir)/wayland-manager.cpp \
- $(adaptor_wayland_dir)/input-manager.cpp \
- $(adaptor_wayland_dir)/event-handler-wl.cpp \
- $(adaptor_wayland_dir)/input/input-listeners.cpp \
- $(adaptor_wayland_dir)/input/seat.cpp \
- $(adaptor_wayland_dir)/input/key-mapping-wl.cpp \
- $(adaptor_wayland_dir)/input/text/text-input-listeners.cpp \
- $(adaptor_wayland_dir)/input/text/text-input-manager.cpp \
- $(adaptor_wayland_dir)/input/text/virtual-keyboard-impl-wl.cpp \
- $(adaptor_wayland_dir)/input/text/imf/imf-manager-impl-wl.cpp \
- $(adaptor_wayland_dir)/render-surface/render-surface-wl.cpp \
- $(adaptor_wayland_dir)/clipboard/clipboard-impl-wl.cpp \
- $(adaptor_wayland_dir)/compositor-output-region/compositor-output.cpp
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "input-manager.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/events/key-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <input/input-listeners.h>
-#include <input/text/text-input-listeners.h>
-#include <virtual-keyboard.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-const unsigned int POINTER_DEVICE_ID = 2;
-const unsigned int TOUCH_DEVICE_ID = 3;
-
-} // unnamed namespace
-
-InputManager::InputManager()
-:mDisplay( NULL ),
- mWindowEventInterface( NULL )
-{
-
-}
-InputManager::~InputManager()
-{
- for( Dali::Vector< Seat* >::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- delete (*iter);
- }
- mSeats.Clear();
-}
-
-void InputManager::AssignWindowEventInterface( WindowEventInterface* eventInterface)
-{
- mWindowEventInterface = eventInterface;
- mTextInputManger.AssignWindowEventInterface( mWindowEventInterface );
-}
-
-void InputManager::AssignDisplay( WlDisplay* display )
-{
- mDisplay = display;
- mTextInputManger.AssignDisplay( mDisplay );
-}
-
-void InputManager::AssignSurface( WlSurface* surface)
-{
- for( Dali::Vector< Seat* >::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- Seat* seat = (*iter);
- seat->SetSurfaceInterface( surface );
- }
-}
-
-
-void InputManager::AddSeatListener( Dali::WlSeat* seatInterface )
-{
- Seat* seat = new Seat( this, seatInterface );
-
- AddSeat( seat );
- mTextInputManger.AddSeat( seat );
-
- // listen to seat events
- wl_seat_add_listener( seatInterface, Wayland::GetSeatListener(), this );
-
-}
-
-void InputManager::AddTextInputManager( Dali::WlTextInputManager* textInputManager )
-{
-
- for( Dali::Vector< Seat* >::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- Seat* seat = (*iter);
-
- // Create a text input object for each seat
- WlTextInput* textInput = wl_text_input_manager_create_text_input( textInputManager );
- seat->SetTextInputInterface( textInput );
-
- wl_text_input_add_listener( textInput, Wayland::GetTextInputListener(), &mTextInputManger );
- }
-
-}
-
-void InputManager::PointerEnter( Seat* seat, unsigned int serial, WlSurface* surface, float x, float y )
-{
- if( mWindowEventInterface )
- {
- mWindowEventInterface->WindowFocusIn();
- }
-}
-
-void InputManager::PointerLeave( Seat* seat, unsigned int serial, WlSurface* surface )
-{
- if( mWindowEventInterface )
- {
- mWindowEventInterface->WindowFocusOut();
- }
-
-}
-
-void InputManager::PointerMotion( Seat* seat, unsigned int timestamp, float x, float y )
-{
- if( mWindowEventInterface )
- {
- Integration::Point point;
- point.SetDeviceId( POINTER_DEVICE_ID );
- point.SetState( PointState::MOTION );
- point.SetScreenPosition( Vector2( x , y ) );
- mWindowEventInterface->TouchEvent( point, timestamp );
- }
-}
-
-void InputManager::PointerButton( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int button, unsigned int state )
-{
- // think about handling multiple pointer button states, if DALi starts to support them
- if( mWindowEventInterface )
- {
- const Dali::Vector2& pointer( seat->GetLastPointerPosition() );
-
- Integration::Point point;
- point.SetDeviceId( POINTER_DEVICE_ID );
- point.SetScreenPosition( pointer );
-
- if( state == 1 )
- {
- point.SetState( PointState::DOWN );
- }
- else
- {
- point.SetState( PointState::UP );
- }
-
- mWindowEventInterface->TouchEvent( point, timestamp );
- }
-}
-
-void InputManager::PointerAxis( Seat* seat, unsigned int timestamp, unsigned int axis, float value )
-{
-
- if( mWindowEventInterface )
- {
- WheelEvent wheelEvent( WheelEvent::MOUSE_WHEEL,
- axis,
- static_cast< int >( seat->GetDepressedKeyboardModifiers() ),
- seat->GetLastPointerPosition(),
- value,
- timestamp );
-
- mWindowEventInterface->WheelEvent( wheelEvent );
- }
-}
-
-void InputManager::KeyboardKeymap( Seat* seat, unsigned int format, int fd, unsigned int size )
-{
- seat->KeyboardKeymap( format, fd, size );
-}
-
-void InputManager::KeyFocusEnter( Seat* seat, unsigned int serial, WlSurface* surface, WlArray* keys )
-{
- // ignore for now
-}
-
-void InputManager::KeyFocusLeave( Seat* seat, unsigned int serial, WlSurface* surface )
-{
- // ignore for now
-}
-
-void InputManager::KeyEvent( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int keycode, unsigned int state )
-{
- Integration::KeyEvent keyEvent( seat->GetDALiKeyEvent( serial, timestamp, keycode, state ) );
-
- mWindowEventInterface->KeyEvent( keyEvent);
-
-}
-
-
-void InputManager::KeyModifiers( Seat* seat,
- unsigned int serial,
- unsigned int depressed,
- unsigned int latched,
- unsigned int locked,
- unsigned int group )
-{
- seat->SetDepressedKeyboardModifiers( depressed );
-}
-
-void InputManager::KeyRepeatInfo( Seat* seat, int32_t rate, int32_t delay)
-{
- if(( rate >= 0 ) && ( delay >= 0))
- {
- seat->SetKeyRepeatInfo( static_cast< unsigned int >( rate) , static_cast< unsigned int >(delay ));
- }
-}
-
-void InputManager::TouchDown( Seat* seat, unsigned int serial, unsigned int timestamp, WlSurface* surface, int touchId, float x, float y)
-{
- // think about handling multiple pointer button states, if DALi starts to support them
- if( mWindowEventInterface )
- {
- const Dali::Vector2& pointer( seat->GetLastPointerPosition() );
-
- Integration::Point point;
- point.SetDeviceId( touchId );
- point.SetState( PointState::DOWN );
- point.SetScreenPosition( pointer );
- mWindowEventInterface->TouchEvent( point, timestamp );
- }
-}
-
-
-void InputManager::TouchUp( Seat* seat, unsigned int serial, unsigned int timestamp, int touchId )
-{
- if( mWindowEventInterface )
- {
- const Dali::Vector2& pointer( seat->GetLastPointerPosition() );
-
- Integration::Point point;
- point.SetDeviceId( touchId );
- point.SetState( PointState::UP );
- point.SetScreenPosition( pointer );
- mWindowEventInterface->TouchEvent( point, timestamp );
- }
-}
-
-void InputManager::TouchMotion( Seat* seat, unsigned int timestamp, int touchId, float x, float y )
-{
- if( mWindowEventInterface )
- {
- const Dali::Vector2& pointer( seat->GetLastPointerPosition() );
-
- Integration::Point point;
- point.SetDeviceId( touchId );
- point.SetState( PointState::MOTION );
- point.SetScreenPosition( pointer );
- mWindowEventInterface->TouchEvent( point, timestamp );
- }
-}
-
-void InputManager::TouchFrame( Seat* seat )
-{
- // un-used
-}
-
-void InputManager::TouchCancel( Seat* seat )
-{
- if( mWindowEventInterface )
- {
- const Dali::Vector2& pointer( seat->GetLastPointerPosition() );
-
- // it looks like DALi just checks the first touch point for interruption
- // so touchId can be zero
- Integration::Point point;
- point.SetState( PointState::INTERRUPTED );
- point.SetScreenPosition( pointer );
- mWindowEventInterface->TouchEvent( point, 0 );
- }
-}
-
-Seat* InputManager::GetSeat( const WlKeyboard* keyboard )
-{
- for( Dali::Vector< Seat *>::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- if( (*iter)->GetKeyboardInterface() == keyboard )
- {
- return (*iter);
- }
- }
- return NULL;
-}
-
-Seat* InputManager::GetSeat( const WlPointer* pointer )
-{
- for( Dali::Vector< Seat *>::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- if( (*iter)->GetPointerInterface() == pointer )
- {
- return (*iter);
- }
- }
- return NULL;
-}
-
-Seat* InputManager::GetSeat( const WlTouch* touch )
-{
- for( Dali::Vector< Seat* >::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- if( (*iter)->GetTouchInterface() == touch )
- {
- return (*iter);
- }
- }
- return NULL;
-}
-
-Seat* InputManager::GetSeat( const WlSeat* seat)
-{
- for( Dali::Vector< Seat* >::Iterator iter = mSeats.Begin(); iter != mSeats.End() ; ++iter )
- {
- if( (*iter)->GetSeatInterface() == seat )
- {
- return (*iter);
- }
- }
- return NULL;
-}
-
-void InputManager::AddSeat( Seat* seat )
-{
- mSeats.PushBack( seat );
-}
-
-
-}
-}
-}
+++ /dev/null
-#ifndef __DALI_WAYLAND_INPUT_H__
-#define __DALI_WAYLAND_INPUT_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/window-event-interface.h>
-#include <wl-types.h>
-#include <input/input-interface.h>
-#include <input/seat.h>
-#include <input/text/text-input-manager.h>
-
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * @brief Listens to Wayland input events.
- * Translates the wayland events into DALi events and forwards them to a WindowEventInterface
- */
-class InputManager : public InputInterface
-{
-
-public:
-
-
- /**
- * @brief Constructor
- */
- InputManager();
-
- /**
- * @brief Destructor
- */
- virtual ~InputManager();
-
- /**
- * @brief Assign the window event interface
- * @param[in] eventInterface event interface
- */
- void AssignWindowEventInterface( WindowEventInterface* eventInterface);
-
- /**
- * @brief Assign the Wayland connection
- * @param[in] display Wayland display
- */
- void AssignDisplay( WlDisplay* display );
-
- /**
- * @brief Assign the Wayland surface
- * @param[in] surface wayland surface
- */
- void AssignSurface( WlSurface* surface);
-
- /**
- * @brief listen to events on this seat
- * @param[in] seatInterface output interface
- */
- void AddSeatListener( Dali::WlSeat* seatInterface );
-
- /**
- * @brief add text input manager interface
- * @param[in] textInputManager text input manager
- */
- void AddTextInputManager( Dali::WlTextInputManager* textInputManager );
-
-
-protected: //InputInterface, pointer events
-
- /**
- * @copydoc InputInterface::PointerEnter
- */
- virtual void PointerEnter( Seat* seat, unsigned int serial, WlSurface* surface, float x, float y );
-
- /**
- * @copydoc InputInterface::PointerLeave
- */
- virtual void PointerLeave( Seat* seat, unsigned int serial, WlSurface* surface );
-
- /**
- * @copydoc InputInterface::PointerMotion
- */
- virtual void PointerMotion( Seat* seat, unsigned int timestamp, float x, float y );
-
- /**
- * @copydoc InputInterface::PointerButton
- */
- virtual void PointerButton( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int button, unsigned int state );
-
- /**
- * @copydoc InputInterface::PointerAxis
- */
- virtual void PointerAxis( Seat* seat, unsigned int timestamp, unsigned int axis, float value );
-
-
-protected: //InputInterface, keyboard events
-
- /**
- * @copydoc InputInterface::KeyboardKeymap
- */
- virtual void KeyboardKeymap( Seat* seat, unsigned int format, int fd, unsigned int size );
-
- /**
- * @copydoc InputInterface::KeyFocusEnter
- */
- virtual void KeyFocusEnter( Seat* seat, unsigned int serial, WlSurface* surface, WlArray* keys );
-
- /**
- * @copydoc InputInterface::KeyFocusLeave
- */
- virtual void KeyFocusLeave( Seat* seat, unsigned int serial, WlSurface* surface );
-
- /**
- * @copydoc InputInterface::KeyEvent
- */
- virtual void KeyEvent( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int keycode, unsigned int state );
-
- /**
- * @copydoc InputInterface::KeyModifiers
- */
- virtual void KeyModifiers( Seat* seat,
- unsigned int serial,
- unsigned int depressed,
- unsigned int latched,
- unsigned int locked,
- unsigned int group );
-
- /**
- * @copydoc InputInterface::KeyRepeatInfo
- */
- virtual void KeyRepeatInfo( Seat* seat, int32_t rate, int32_t delay);
-
-protected: //InputInterface, touch events
-
- /**
- * @copydoc InputInterface::TouchDown
- */
- virtual void TouchDown( Seat* seat, unsigned int serial, unsigned int timestamp, WlSurface* surface, int touchId, float x, float y);
-
- /**
- * @copydoc InputInterface::TouchUp
- */
- virtual void TouchUp( Seat* seat, unsigned int serial, unsigned int timestamp, int touchId );
-
- /**
- * @copydoc InputInterface::TouchMotion
- */
- virtual void TouchMotion( Seat* seat, unsigned int timestamp, int touchId, float x, float y );
-
- /**
- * @copydoc InputInterface::TouchFrame
- */
- virtual void TouchFrame( Seat* seat );
-
- /**
- * @copydoc InputInterface::TouchCancel
- */
- virtual void TouchCancel( Seat* seat );
-
-
-protected: //InputInterface Helper functions
-
- /**
- * @copydoc InputInterface::GetSeat( const WlKeyboard* keyboard )
- */
- virtual Seat* GetSeat( const WlKeyboard* keyboard );
-
- /**
- * @copydoc InputInterface::GetSeat( const WlPointer* pointer )
- */
- virtual Seat* GetSeat( const WlPointer* pointer );
-
- /**
- * @copydoc InputInterface::GetSeat( const WlTouch* touch )
- */
- virtual Seat* GetSeat( const WlTouch* touch );
-
- /**
- * @copydoc InputInterface::GetSeat( const WlSeat* seat )
- */
- virtual Seat* GetSeat( const WlSeat* seat );
-
-public:
-
- /**
- * @brief Add a new seat ( collection of input devices)
- * @param[in] wlRegistry
- * @param[in] seatName seat name / id
- * @param[in] version interface version
- */
- void AddSeat( Seat* seat );
-
-
-private:
-
- Dali::Vector< Seat* > mSeats;
- TextInputManager mTextInputManger;
- WlDisplay* mDisplay;
- WindowEventInterface* mWindowEventInterface;
-
-};
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_WAYLAND_INPUT_H__
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_INPUT_INTERFACE_H__
-#define __DALI_INTERNAL_ADAPTOR_INPUT_INTERFACE_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wl-types.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class Seat;
-
-/**
- * @brief interface used by the Wayland input listeners to signal an event.
- *
- * The events that come from keyboard, pointer and touch devices are from a specific seat.
- * A single seat can have multiple keyboards, pointers and touch devices connected to it.
- *
- * For example you can have a car with 4 seats each with their own touch screen that
- * are run by a central device with multi-display output.
- *
- * Some input events have serial numbers and time stamps.
- *
- * Serial numbers description from Wayland documentation:
- * "To avoid race conditions, input events that are likely to trigger further requests
- * (such as button presses, key events, pointer motions) carry serial numbers, and requests such as
- * wl_surface.set_popup require that the serial number of the triggering event is specified."
- *
- * Time stamps description from Wayland documentation:
- * "Input events also carry timestamps with millisecond granularity.
- * Their base is undefined, so they can't be compared against system time
- * (as obtained with clock_gettime or gettimeofday). They can be compared
- * with each other though, and for instance be used to identify sequences
- * of button presses as double or triple clicks."
- */
-class InputInterface
-{
-
-public: // Pointer events. See wl_pointer_listener in wayland-client-protocol.h for more information.
-
- /**
- * @brief Called when a seat's pointer has entered a surface
- *
- * When focus enters a surface, the pointer image is
- * undefined and a client should respond to this event by setting
- * an appropriate pointer image with the set_cursor request.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] surface surface
- * @param[in] x x coordinate in surface-relative coordinates ( not screen )
- * @param[in] y y coordinate in surface-relative coordinates ( not screen )
- */
- virtual void PointerEnter( Seat* seat, unsigned int serial, WlSurface* surface, float x, float y) = 0;
-
- /**
- * @brief Called when a seat's pointer leaves a surface
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] surface surface
- *
- * The leave notification is sent before the enter notification for
- * the new focus.
- */
- virtual void PointerLeave( Seat* seat, unsigned int serial, WlSurface* surface ) = 0;
-
- /**
- * @brief pointer motion event
- *
- * @param[in] seat the seat that produced the event
- * @param[in] timestamp timestamp with millisecond granularity
- * @param[in] x x coordinate in surface-relative coordinates ( not screen )
- * @param[in] y y coordinate in surface-relative coordinates ( not screen )
- *
- */
- virtual void PointerMotion( Seat* seat, unsigned int timestamp, float x, float y ) = 0;
-
- /**
- * @brief pointer click and release events
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] timestamp timestamp with millisecond granularity
- * @param[in] button pointer button pressed
- * @param[in] state button state ( 1 = down, 0 = up)
- *
- * The location of the click is given by the last motion or enter
- * event.
- */
- virtual void PointerButton( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int button, unsigned int state ) = 0;
-
- /**
- * @brief Pointer scroll and other axis notifications.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] timestamp timestamp with millisecond granularity
- * @param[in] axis pointer axis
- * @param[in] value length of a vector along the specified axis in a coordinate space identical to those of motion event
- */
- virtual void PointerAxis( Seat* seat, unsigned int timestamp, unsigned int axis, float value ) = 0;
-
-public: // Key events. See wl_keyboard_listener in wayland-client-protocol.h for more information.
-
- /**
- * @brief keyboard mapping
- * Provides a file descriptor which can be memory-mapped to a keyboard mapping description
- *
- * @param[in] seat the seat that produced the event
- * @param[in] format see wl_keyboard_keymap_format
- * @param[in] fd file descriptor
- * @param[in] size size of the memory mapped region in bytes
- */
- virtual void KeyboardKeymap( Seat* seat, unsigned int format, int fd, unsigned int size ) = 0;
-
- /**
- * @brief The seat's keyboard focus has entered a surface
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] surface surface
- * @param[in] keys the currently pressed keys
- */
- virtual void KeyFocusEnter( Seat* seat, unsigned int serial, WlSurface* surface, WlArray* keys ) = 0;
-
- /**
- * @brief The seat's keyboard focus has left a surface
- *
- * The leave notification is sent before the enter notification for the new focus.
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] surface surface
- */
- virtual void KeyFocusLeave( Seat* seat, unsigned int serial, WlSurface* surface ) = 0;
-
- /**
- * @brief Key has been pressed or released
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] timestamp timestamp
- * @param[in] keycode raw hardware key code
- * @param[in] state
- */
- virtual void KeyEvent( Seat* seat, unsigned int serial, unsigned int timestamp, unsigned int keycode, unsigned int state) = 0;
-
- /**
- * @brief Key modifier state has changed
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] depressed modifiers depressed
- * @param[in] latched modifiers latched
- * @param[in] locked modifiers locked
- * @param[in[ group group
- */
- virtual void KeyModifiers( Seat* seat,
- unsigned int serial,
- unsigned int depressed,
- unsigned int latched,
- unsigned int locked,
- unsigned int group) = 0;
-
-
- /**
- * @brief Key repeat rate and delay.
- *
- * Informs DALi of the keyboard's repeat rate and delay.
- *
- * Event sent when wl_keyboard object created, before any key events
- * If rate == zero, repeating is disabled
- *
- * @param[in] seat the seat that produced the event
- * @param[in] rate rate of repeating keys in characters per second
- * @param[in] delay delay in milliseconds since key down until repeating starts
- */
- virtual void KeyRepeatInfo( Seat* seat, int32_t rate, int32_t delay) = 0;
-
-
-public: // touch events. See wl_touch_listener in wayland-client-protocol.h for more information.
-
- /**
- * @brief Touch down event on a surface.
- *
- * Future events from this touch point will have the same id which is valid
- * until a touch up event.
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] timestamp timestamp
- * @param[in] surface surface
- * @param[in] touchId unique touch id valid until touch is released
- * @param[in] x coordinate in surface-relative coordinates
- * @param[in[ y coordinate in surface-relative coordinates
- */
- virtual void TouchDown( Seat* seat, unsigned int serial, unsigned int timestamp, WlSurface* surface, int touchId, float x, float y) = 0;
-
- /**
- * @brief Touch up event on a surface.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] timestamp timestamp with millisecond granularity
- * @param[in] touchId unique touch id valid until touch is released ( can be re-used for future events)
- */
- virtual void TouchUp( Seat* seat, unsigned int serial, unsigned int timestamp, int touchId ) = 0;
-
- /**
- * @brief Touch Motion event on a surface.
- * Events relating to the same touch point can be identified by the touchId
- *
- * @param[in] seat the seat that produced the event
- * @param[in] timestamp timestamp with millisecond granularity
- * @param[in] touchId unique touch id valid until touch is released ( then can be re-used)
- * @param[in] x coordinate in surface-relative coordinates
- * @param[in[ y coordinate in surface-relative coordinates
- */
- virtual void TouchMotion( Seat* seat, unsigned int timestamp, int touchId, float x, float y ) = 0;
-
- /**
- * @brief end of touch frame event
- * Unsure what this means.
- * @param[in] seat the seat that produced the event
- */
- virtual void TouchFrame( Seat* seat ) = 0;
-
- /**
- * @brief Cancel current touch session
- * If Wayland Compositor decides current touch stream is a global
- * gesture we have to cancel any touch / gesture detection.
- *
- * Touch cancellation applies to all touch points currently active on
- * our surface. TouchPoint::Interrupted will be sent to dali-core
- *
- * @param[in] seat the seat that produced the event
- */
- virtual void TouchCancel( Seat* seat ) = 0;
-
-public: // Helper functions used to find the seat associated with the keyboard/pointer/touch device
-
- /**
- * @brief get the seat that contains the keyboard interface
- * @param[in] keyboard wayland keyboard interface
- * @return the seat the keyboard belongs to
- */
- virtual Seat* GetSeat( const WlKeyboard* keyboard ) = 0;
-
- /**
- * @brief get the seat that contains the pointer interface
- * @param[in] pointer wayland pointer interface
- * @return the seat the pointer belongs to
- */
- virtual Seat* GetSeat( const WlPointer* pointer ) = 0;
-
- /**
- * @brief get the seat that contains the touch interface
- * @param[in] touch wayland touch interface
- * @return the seat the touch device belongs to
- */
- virtual Seat* GetSeat( const WlTouch* touch ) = 0;
-
- /**
- * @brief get the seat that contains the wayland seat interface
- * @param[in] seat wayland seat interface
- * @return the seat the touch device belongs to
- */
- virtual Seat* GetSeat( const WlSeat* seat ) = 0;
-
-protected:
-
- /**
- * @brief Constructor
- */
- InputInterface()
- {
- }
-
- /**
- * @brief destructor
- */
- virtual ~InputInterface()
- {
- }
-
- // Undefined copy constructor.
- InputInterface( const InputInterface& );
-
- // Undefined assignment operator.
- InputInterface& operator=( const InputInterface& );
-};
-
-
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_INTERNAL_ADAPTOR_INPUT_INTERFACE_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-// CLASS HEADER
-#include "input-listeners.h"
-
-// EXTERNAL INCLUDES
-#include <cctype>
-#include <stdio.h>
-
-// INTERNAL INCLUDES
-#include "input-interface.h"
-#include "seat.h"
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-/************
- *
- * Pointer events callbacks. See wl_pointer_listener in wayland-client-protocol.h for a description
- *
- ************/
-void PointerEnter( void* data,
- WlPointer* pointer,
- unsigned int serial,
- WlSurface* surface,
- wl_fixed_t surfaceX,
- wl_fixed_t surfaceY)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( pointer );
-
- float x = static_cast<float>( wl_fixed_to_double(surfaceX) );
- float y = static_cast<float>( wl_fixed_to_double(surfaceY) );
-
- seat->SetPointerPosition( Vector2(x, y) ); // record last pointer position
-
- input->PointerEnter( seat, serial, surface, x, y );
-}
-
-void PointerLeave( void* data,
- WlPointer* pointer,
- unsigned int serial,
- WlSurface* surface )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( pointer );
-
- input->PointerLeave( seat, serial, surface );
-}
-
-void PointerMotion( void* data,
- WlPointer* pointer,
- unsigned int timestamp,
- wl_fixed_t surfaceX,
- wl_fixed_t surfaceY )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( pointer );
-
- float x = static_cast<float>( wl_fixed_to_double( surfaceX) );
- float y = static_cast<float>( wl_fixed_to_double( surfaceY) );
-
- seat->SetPointerPosition( Vector2(x, y) ); // record last pointer position
-
- input->PointerMotion( seat, timestamp, x, y );
-}
-
-void PointerButton( void* data,
- WlPointer* pointer,
- unsigned int serial,
- unsigned int timestamp,
- unsigned int button,
- unsigned int state )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( pointer );
-
- input->PointerButton( seat, serial, timestamp, button, state );
-
-}
-
-void PointerAxis( void* data,
- WlPointer* pointer,
- unsigned int timestamp,
- unsigned int axis,
- wl_fixed_t value )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( pointer );
-
- float length = static_cast<float>( wl_fixed_to_double( value ) );
-
- input->PointerAxis( seat, timestamp, axis, length);
-}
-
-/************
- *
- * Key event callbacks. See wl_keyboard_listener wayland-client-protocol.h for a description
- *
- ************/
-void KeyboardKeymap( void* data,
- WlKeyboard* keyboard,
- unsigned int format,
- int fd,
- unsigned int size )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyboardKeymap( seat, format, fd, size );
-
-}
-
-void KeyFocusEnter( void* data,
- WlKeyboard* keyboard,
- unsigned int serial,
- WlSurface* surface,
- WlArray* keys )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyFocusEnter( seat, serial, surface, keys );
-}
-
-void KeyFocusLeave( void* data,
- WlKeyboard* keyboard,
- unsigned int serial,
- WlSurface* surface )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyFocusLeave( seat, serial, surface );
-}
-
-void KeyEvent( void* data,
- WlKeyboard* keyboard,
- unsigned int serial,
- unsigned int timestamp,
- unsigned int keycode,
- unsigned int state)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyEvent( seat, serial, timestamp, keycode, state );
-}
-
-void KeyModifiers( void* data, WlKeyboard* keyboard,
- unsigned int serial,
- unsigned int depressed,
- unsigned int latched,
- unsigned int locked,
- unsigned int group)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyModifiers( seat, serial, depressed, latched, locked, group );
-
-
-}
-
-void KeyRepeatInfo( void* data,
- WlKeyboard* keyboard,
- int32_t rate,
- int32_t delay)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( keyboard );
-
- input->KeyRepeatInfo( seat, rate, delay );
-
-}
-
-/************
- *
- * Touch event callbacks See wl_touch_listener wayland-client-protocol.h for a description
- *
- ************/
-void TouchDown( void* data,
- WlTouch* touch,
- unsigned int serial,
- unsigned int timestamp,
- WlSurface* surface,
- int touchId,
- wl_fixed_t surfaceX,
- wl_fixed_t surfaceY)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( touch );
-
- float x = static_cast<float>( wl_fixed_to_double( surfaceX) );
- float y = static_cast<float>( wl_fixed_to_double( surfaceY) );
-
-
- input->TouchDown( seat, serial, timestamp, surface, touchId, x, y );
-}
-
-void TouchUp( void* data,
- WlTouch* touch,
- unsigned int serial,
- unsigned int timestamp,
- int touchId )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( touch );
-
- input->TouchUp( seat, serial, timestamp, touchId );
-}
-
-void TouchMotion( void* data,
- WlTouch* touch,
- unsigned int timestamp,
- int touchId,
- wl_fixed_t surfaceX,
- wl_fixed_t surfaceY)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( touch );
-
- float x = static_cast<float>( wl_fixed_to_double( surfaceX) );
- float y = static_cast<float>( wl_fixed_to_double( surfaceY) );
-
- input->TouchMotion( seat, timestamp, touchId, x, y );
-}
-
-void TouchFrame( void* data, WlTouch* touch )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( touch );
-
- input->TouchFrame( seat );
-}
-
-void TouchCancel( void* data, WlTouch* touch )
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( touch );
-
- input->TouchCancel( seat );
-}
-
-/**
- * pointer listener interface ( wl_pointer_listener )
- */
-const WlPointerListener PointerListener =
-{
- PointerEnter,
- PointerLeave,
- PointerMotion,
- PointerButton,
- PointerAxis,
-};
-
-/**
- * Keyboard listener interface ( wl_keyboard_listener )
- */
-const WlKeyboardListener KeyboardListener =
-{
- KeyboardKeymap,
- KeyFocusEnter,
- KeyFocusLeave,
- KeyEvent,
- KeyModifiers,
- KeyRepeatInfo
-};
-
-/**
- * Touch listener interface ( wl_touch_listener )
- */
-const WlTouchListener TouchListener =
-{
- TouchDown,
- TouchUp,
- TouchMotion,
- TouchFrame,
- TouchCancel
-};
-
-/**
- * @brief emitted whenever a seat gains or loses the pointer, keyboard or touch capabilities.
- * @param[in] data user data
- * @param[in] seatInterface seat interface
- * @param[in] caps enum containing the complete set of capabilities this seat has.
- */
-void SeatHandleCapabilities( void* data, WlSeat* seatInterface, unsigned int caps)
-{
-
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( seatInterface );
-
-
- // go through either adding or removing pointer/keyboard/touch interfaces
- // most devices are hot plug so this function may be called many times
- // a single keyboard/ pointer / touch interface handles multiple devices
- // e.g. if you plug in 2 mouses, you will still only get a single pointer_interface
-
- if( caps & WL_SEAT_CAPABILITY_POINTER )
- {
- // at least one pointer available
- seat->SetPointerInterface( Seat::INTERFACE_AVAILABLE );
- }
- else
- {
- // all pointer devices removed, or never connected
- seat->SetPointerInterface( Seat::INTERFACE_NOT_AVAILABLE );
- }
-
- if( caps & WL_SEAT_CAPABILITY_KEYBOARD )
- {
- // at least one keyboard available
- seat->SetKeyboardInterface( Seat::INTERFACE_AVAILABLE );
- }
- else
- {
- // all keyboard devices removed, or never connected
- seat->SetKeyboardInterface( Seat::INTERFACE_NOT_AVAILABLE );
- }
-
- if( caps & WL_SEAT_CAPABILITY_TOUCH )
- {
- // new touch device found
- seat->SetTouchInterface( Seat::INTERFACE_AVAILABLE );
- }
- else
- {
- // all touch devices removed, or never connected
- seat->SetTouchInterface( Seat::INTERFACE_NOT_AVAILABLE );
- }
-
-}
-
-void SeatName(void* data, WlSeat* seatInterface, const char* name)
-{
- InputInterface* input = static_cast< InputInterface* >( data );
- Seat* seat = input->GetSeat( seatInterface );
- seat->SetName( name );
-}
-
-const WlSeatListener SeatListener =
-{
- SeatHandleCapabilities, //emitted whenever a seat gains or loses the pointer, keyboard or touch capabilities.
- SeatName, // used to help identify seat in multi-seat configurations
-};
-
-} // unnamed namespace
-
-
-namespace Wayland
-{
-
-const WlSeatListener* GetSeatListener()
-{
- return &SeatListener;
-}
-
-const WlPointerListener* GetPointerListener()
-{
- return &PointerListener;
-}
-
-const WlTouchListener* GetTouchListener()
-{
- return &TouchListener;
-}
-
-const WlKeyboardListener* GetKeyboardListener()
-{
- return &KeyboardListener;
-}
-
-}
-}
-}
-}
+++ /dev/null
-#ifndef __DALI_WAYLAND_INPUT_LISTENERS_H__
-#define __DALI_WAYLAND_INPUT_LISTENERS_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wl-types.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Wayland
-{
-/**
- * Functions for getting wayland listener objects as defined in wayland-client-protocol.h
- * The listen objects contain C callbacks, which currently expect the user data-field
- * to be a DALi InputInterface pointer.
- *
- * E.g. if setting the keyboard listener
- *
- * wl_keyboard_add_listener( keyboard, &Wayland::GetKeyboardListener(), &InputInterface );
- *
- */
-
-
-/**
- * @brief Listens for keyboard / touch / pointer interfaces being enabled /disabled on a seat.
- * @return seat listener
- */
-const WlSeatListener* GetSeatListener();
-
-/**
- * @brief returns a pointer to the callbacks used to listen to pointer events
- * @return pointer listener
- */
-const WlPointerListener* GetPointerListener();
-
-/**
- * @brief returns a pointer to the callbacks used to listen to touch events
- * @return touch listener
- */
-const WlTouchListener* GetTouchListener();
-
-/**
- * @brief returns a pointer to the callbacks used to listen to keyboard events
- * @return keyboard listener
- */
-const WlKeyboardListener* GetKeyboardListener();
-
-} // Wayland
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_WAYLAND_INPUT_LISTENERS_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <key-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-// matches a DALI_KEY enum, to a key name
-KeyLookup KeyLookupTable[]=
-{
- // more than one key name can be assigned to a single dali-key code
- // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
-
- { "Escape", DALI_KEY_ESCAPE, false },
- { "Menu", DALI_KEY_MENU, false },
-
- // Now literal strings are used as key names instead of defined symbols in utilX,
- // since these definition in utilX.h is deprecated
- { "XF86Camera", DALI_KEY_CAMERA, false },
- { "XF86Camera_Full", DALI_KEY_CONFIG, false },
- { "XF86PowerOff", DALI_KEY_POWER, true },
- { "XF86Standby", DALI_KEY_PAUSE, false },
- { "Cancel", DALI_KEY_CANCEL, false },
- { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
- { "XF86AudioStop", DALI_KEY_STOP_CD, false },
- { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
- { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
- { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
- { "XF86AudioRewind", DALI_KEY_REWIND, false },
- { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
- { "XF86AudioMedia", DALI_KEY_MEDIA, false },
- { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
- { "XF86AudioMute", DALI_KEY_MUTE, false },
- { "XF86Menu", DALI_KEY_MENU, true },
- { "XF86Home", DALI_KEY_HOME, true },
- { "XF86Back", DALI_KEY_BACK, true },
- { "XF86Send", DALI_KEY_MENU, true },
- { "XF86Phone", DALI_KEY_HOME, true },
- { "XF86Stop", DALI_KEY_BACK, true },
- { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
- { "XF86WWW", DALI_KEY_WEBPAGE, false },
- { "XF86Mail", DALI_KEY_MAIL, false },
- { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
- { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
- { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
- { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
- { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
- { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
- { "XF86Apps", DALI_KEY_APPS, false },
- { "XF86Search", DALI_KEY_SEARCH, false },
- { "XF86Voice", DALI_KEY_VOICE, false },
- { "Hangul", DALI_KEY_LANGUAGE, false },
- { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
- { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
-
- { "BackSpace", DALI_KEY_BACKSPACE, false },
- { "Left", DALI_KEY_CURSOR_LEFT, false },
- { "Right", DALI_KEY_CURSOR_RIGHT, false },
- { "left", DALI_KEY_CURSOR_LEFT, false }, // To be removed after the key name is fixed in the platform
- { "right", DALI_KEY_CURSOR_RIGHT, false }, // To be removed after the key name is fixed in the platform
- { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
- { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
- { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
- { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
- { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
- { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
-};
-
-const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "seat.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <cctype>
-#include <sys/mman.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <cstring>
-
-// INTERNAL INCLUDES
-#include "input-listeners.h"
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-const unsigned int DEFAULT_KEY_REPEAT_RATE = 25;
-const unsigned int DEFAULT_KEY_REPEAT_DELAY = 400;
-}
-
-Seat::Seat( InputInterface* inputInterface, WlSeat* seatInterface )
-:mPointer( NULL ),
- mKeyboard( NULL ),
- mTouch( NULL ),
- mWaylandSeat( seatInterface ),
- mTextInput( NULL ),
- mSurface( NULL ),
- mInputInterface( inputInterface ),
- mPointerPosition( 0, 0),
- mDepressedKeyboardModifiers(0),
- mKeyRepeatRate( DEFAULT_KEY_REPEAT_RATE ),
- mKeyRepeatDelay( DEFAULT_KEY_REPEAT_DELAY )
-{
-}
-
-Seat::~Seat()
-{
- DestroyPointerInterface();
- DestroyTouchInterface();
- DestroyKeyboardInterface();
-}
-
-void Seat::SetTextInputInterface( WlTextInput* textInput )
-{
- mTextInput = textInput;
-}
-
-void Seat::SetSurfaceInterface( WlSurface* surface )
-{
- mSurface = surface;
-}
-
-void Seat::SetPointerInterface( InterfaceStatus status )
-{
- if( status == INTERFACE_AVAILABLE )
- {
- if( ! mPointer )
- {
- WlPointer* pointerInterface = wl_seat_get_pointer( mWaylandSeat );
-
- // store the interface and add an event listener
- wl_pointer_add_listener( pointerInterface, Wayland::GetPointerListener(), mInputInterface );
-
- mPointer = pointerInterface;
- }
- }
- else
- {
- DestroyPointerInterface();
- }
-}
-
-void Seat::SetTouchInterface( InterfaceStatus status )
-{
- if( status == INTERFACE_AVAILABLE )
- {
- // check if it's configured already
- if( ! mTouch )
- {
- WlTouch* touchInterface = wl_seat_get_touch( mWaylandSeat );
-
- wl_touch_add_listener( touchInterface, Wayland::GetTouchListener(), mInputInterface );
-
- // store the interface and add an event listener
- mTouch = touchInterface;
- }
- }
- else
- {
- DestroyTouchInterface();
- }
-
-}
-
-void Seat::SetKeyboardInterface( InterfaceStatus status )
-{
- if( status == INTERFACE_AVAILABLE )
- {
- // check if it's configured already
- if( ! mKeyboard )
- {
- WlKeyboard* keyboardInterface = wl_seat_get_keyboard( mWaylandSeat );
-
- wl_keyboard_add_listener( keyboardInterface, Wayland::GetKeyboardListener(), mInputInterface );
-
- // store the interface and add an event listener
- mKeyboard = keyboardInterface;
- }
- }
- else
- {
- DestroyKeyboardInterface();
- }
-}
-
-WlPointer* Seat::GetPointerInterface()
-{
- return mPointer;
-}
-
-WlTouch* Seat::GetTouchInterface()
-{
- return mTouch;
-}
-
-WlKeyboard* Seat::GetKeyboardInterface()
-{
- return mKeyboard;
-}
-
-WlSeat* Seat::GetSeatInterface()
-{
- return mWaylandSeat;
-}
-
-WlTextInput* Seat::GetTextInputInterface()
-{
- return mTextInput;
-}
-
-WlSurface* Seat::GetSurface()
-{
- return mSurface;
-}
-
-void Seat::DestroyPointerInterface()
-{
- if( mPointer )
- {
- wl_pointer_destroy( mPointer );
- mPointer = NULL;
- }
-}
-
-void Seat::DestroyTouchInterface()
-{
- if( mTouch )
- {
- wl_touch_destroy( mTouch );
- mTouch = NULL;
- }
-}
-
-void Seat::DestroyKeyboardInterface()
-{
- if( mKeyboard )
- {
- wl_keyboard_destroy( mKeyboard );
- mKeyboard = NULL;
- }
-}
-
-void Seat::SetName( const char* name )
-{
- mName = std::string( mName );
-}
-const std::string& Seat::GetName() const
-{
- return mName;
-}
-
-const Dali::Vector2& Seat::GetLastPointerPosition() const
-{
- return mPointerPosition;
-}
-
-void Seat::SetPointerPosition( Dali::Vector2 position)
-{
- mPointerPosition = position;
-}
-
-void Seat::KeyboardKeymap( unsigned int format, int fd, unsigned int size )
-{
-
- if( !mXkbData.mContext )
- {
- mXkbData.mContext = xkb_context_new( XKB_CONTEXT_NO_FLAGS );
- }
-
- if( !mXkbData.mContext )
- {
- DALI_LOG_ERROR("xkb_context_new failed\n");
- close(fd);
- return;
- }
-
- // current formats defined in wayland-client-protocol.h
- // WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP =0, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1=1
-
- if( format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1 )
- {
- DALI_LOG_ERROR("expected WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1\n");
- close(fd);
- return;
- }
-
- // memory map the shared region between us and XKB
- char* map = static_cast<char*> (mmap( NULL, size, PROT_READ, MAP_SHARED, fd, 0));
- if( map == MAP_FAILED)
- {
- DALI_LOG_ERROR("mmap xkb failed\n");
- close(fd);
- return;
- }
-
- mXkbData.mKeymap = xkb_map_new_from_string(mXkbData.mContext, map, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
-
- munmap(map, size);
- close(fd);
-
- if (! mXkbData.mKeymap )
- {
- DALI_LOG_ERROR(" xkb_map_new_from_string failed\n");
- return;
- }
-
- mXkbData.mState = xkb_state_new( mXkbData.mKeymap );
-
- if( ! mXkbData.mState )
- {
- xkb_map_unref(mXkbData.mKeymap );
- mXkbData.mKeymap = NULL;
- return;
- }
-
- // store the bit which each mod will set when calling xkb_state_serialize_mods
- mXkbData.mControlMask = 1 << xkb_map_mod_get_index( mXkbData.mKeymap, XKB_MOD_NAME_CTRL);
- mXkbData.mAltMask = 1 << xkb_map_mod_get_index( mXkbData.mKeymap, XKB_MOD_NAME_ALT);
- mXkbData.mShiftMask = 1 << xkb_map_mod_get_index( mXkbData.mKeymap, XKB_MOD_NAME_SHIFT);
-
-}
-
-Dali::KeyEvent Seat::GetDALiKeyEventFromSymbol( unsigned int serial,
- unsigned int timestamp,
- unsigned int symbol,
- unsigned int state,
- unsigned int modifiers )
-{
- char key[256] = { 0 };
- char keyName[256] = { 0 };
-
- // get its name
- xkb_keysym_get_name( symbol, key, sizeof(key));
-
- // copy the keyname
- memcpy(keyName, key, sizeof(keyName));
-
- if (keyName[0] == '\0')
- {
- snprintf(keyName, sizeof(keyName), "Keycode-%u", symbol);
- }
-
- Dali::KeyEvent keyEvent;
-
- keyEvent.keyCode = symbol; // we don't get the keycode so just the symbol
- if( state == 1)
- {
- keyEvent.state = KeyEvent::Down;
- }
- else
- {
- keyEvent.state = KeyEvent::Up;
- }
-
- keyEvent.keyPressed = keyName;
- keyEvent.keyPressedName = keyName;
- keyEvent.time = timestamp;
- keyEvent.keyModifier = modifiers;
-
- return keyEvent;
-
-}
-
-
-Dali::KeyEvent Seat::GetDALiKeyEvent( unsigned int serial, unsigned int timestamp, unsigned int keycode, unsigned int state )
-{
- unsigned int code( 0 );
- unsigned int symbolCount( 0 );
- const xkb_keysym_t* symbols( NULL );
- xkb_keysym_t symbol = XKB_KEY_NoSymbol;
- char key[256] = { 0 };
- char keyName[256] = { 0 };
-
- // X11 historically has a min keycode of 8 instead of 1, XKB follow this
- code = keycode + 8;
-
- //get the key symbols
- symbolCount = xkb_key_get_syms( mXkbData.mState, code, &symbols);
-
- if( symbolCount == 1)
- {
- symbol = symbols[0];
- }
-
- // get its name
- xkb_keysym_get_name( symbol, key, sizeof(key));
-
- // copy the keyname
- memcpy(keyName, key, sizeof(keyName));
-
- if (keyName[0] == '\0')
- {
- snprintf(keyName, sizeof(keyName), "Keycode-%u", code);
- }
-
- // todo support key repeat settings
-
- Dali::KeyEvent keyEvent;
-
- keyEvent.keyCode = code;
- if( state == 1)
- {
- keyEvent.state = KeyEvent::Down;
- }
- else
- {
- keyEvent.state = KeyEvent::Up;
- }
- keyEvent.keyPressed = keyName;
- keyEvent.keyPressedName = keyName;
- keyEvent.time = timestamp;
- keyEvent.keyModifier = mDepressedKeyboardModifiers;
-
- return keyEvent;
-
-}
-unsigned int Seat::GetDepressedKeyboardModifiers() const
-{
- return mDepressedKeyboardModifiers;
-}
-
-void Seat::SetDepressedKeyboardModifiers( unsigned int modifiers)
-{
- mDepressedKeyboardModifiers = modifiers;
-}
-
-void Seat::SetKeyRepeatInfo( unsigned int rate, unsigned int delay )
-{
- mKeyRepeatRate = rate;
- mKeyRepeatDelay = delay;
-}
-
-} // Internal
-} // Adaptor
-} // Dali
+++ /dev/null
-#ifndef __DALI_WAYLAND_SEAT_H__
-#define __DALI_WAYLAND_SEAT_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <xkbcommon/xkbcommon.h>
-#include <dali/public-api/math/vector2.h>
-#include <dali/public-api/events/key-event.h>
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class InputInterface;
-
-/**
- *
- * A single seat is a group of keyboards, pointers and touch devices.
- *
- * For example you can have a car with 4 seats each with their own touch screen that
- * is run by a central computer with a multi-display output.
- *
- * Or you may have two people / two seats in an office sharing the same screen at the same time.
- *
- *
- * There is a single wl_pointer / wl_touch and wl_keyboard interface per seat.
- * But each interface can have multiple devices. E.g. wl_pointer interface may have 2
- * mouse pointers attached.
- *
- * Input devices can be hot plugged. However wl_pointer / wl_touch and wl_keyboard interface
- * will only be destroyed when the interface has no devices associated with it.
- * E.g. if a seat has a single mouse, when you unplug the mouse the interface is deleted.
- * If a seat has two mice, only when you unplug both mice is the interface deleted.
- *
- */
-class Seat
-{
-
-public:
-
- /**
- * @brief Seat interface status for a device class ( keyboard, touch, pointer )
- */
- enum InterfaceStatus
- {
- INTERFACE_AVAILABLE, ///< Occurs when at least 1 device for this device class is plugged in
- INTERFACE_NOT_AVAILABLE, ///< Occurs when all devices for a device class are unplugged (e.g. all mice )
- };
-
- /**
- * @brief constructor
- * @param[in] inputInterface input interface
- * @param[in] seatInterface Wayland seat interface
- */
- Seat( InputInterface* inputInterface, WlSeat* seatInterface );
-
- /**
- * @brief non virtual destructor, not intended as base class
- */
- ~Seat();
-
- /**
- * @brief set Tizen Wayland Text Input interface
- * @param[in] textInputManager interface
- */
- void SetTextInputInterface( WlTextInput* textInput );
-
- /**
- * @brief set the surface
- * @param[in] surface Wayland surface currently associated with this seat ( for input panel / IMF )
- */
- void SetSurfaceInterface( WlSurface* surface );
-
- /**
- * @brief Set the pointer interface
- * @param[in] pointer Wayland pointer interface
- * @param[in] status of the interface
- */
- void SetPointerInterface( InterfaceStatus status );
-
- /**
- * @brief Set the touch interface
- * @param[in] pointer Wayland pointer interface
- * @param[in] status of the interface
- */
- void SetTouchInterface( InterfaceStatus status );
-
- /**
- * @brief Set the keyboard interface
- * @param[in] pointer Wayland pointer interface
- * @param[in] status of the interface
- */
- void SetKeyboardInterface( InterfaceStatus status );
-
- /**
- * @brief Get the pointer interface
- * @return Wayland pointer interface
- */
- WlPointer* GetPointerInterface();
-
- /**
- * @brief Get the touch interface
- * @return Wayland touch interface
- */
- WlTouch* GetTouchInterface();
-
- /**
- * @brief Get the keyboard interface
- * @return Wayland keyboard interface
- */
- WlKeyboard* GetKeyboardInterface();
-
- /**
- * @brief Get the keyboard interface
- * @return Wayland keyboard interface
- */
- WlSeat* GetSeatInterface();
-
- /**
- * @brief Get the text input interface
- * @return Wayland text input interface
- */
- WlTextInput* GetTextInputInterface();
-
- /**
- * @brief Get the surface
- * @return Wayland surface
- */
- WlSurface* GetSurface();
-
- /**
- * @brief calls wl_pointer_destroy on the pointer interface
- */
- void DestroyPointerInterface();
-
- /**
- * @brief calls wl_touch_destroy on the touch interface
- */
- void DestroyTouchInterface();
-
- /**
- * @brief calls wl_touch_keyboard on the keyboard interface
- */
- void DestroyKeyboardInterface();
-
- /**
- * @brief place holder store the seat name
- * Currently we don't store the name as DALi core isn't seat name aware
- * Need to think about adding Seat name to touch / key events.
- * @param[in] name seat name
- */
- void SetName( const char* name );
-
- /**
- * @brief get the seat name
- * E.g. may return "front-passenger-seat"
- * @return seat name
- */
- const std::string& GetName() const;
-
- /**
- * @brief get the last known pointer position
- * @return pointer position
- */
- const Dali::Vector2& GetLastPointerPosition() const;
-
- /**
- * @brief set the pointer position
- * So we need to cache mouse x/y position, for pointer down events which
- * don't have x,y position attached
- * @param[in] position pointer position
- */
- void SetPointerPosition( Dali::Vector2 position);
-
- /**
- * @brief keyboard mapping
- * Provides a file descriptor which can be memory-mapped to a keyboard mapping description
- * @param[in] seat the seat that produced the event
- * @param[in] format see wl_keyboard_keymap_format
- * @param[in] fd file descriptor
- * @param[in] size size of the memory mapped region in bytes
- */
- void KeyboardKeymap( unsigned int format, int fd, unsigned int size );
-
- /**
- * @brief get current depressed keyboard modifiers (not latched)
- * @return keyboard modifiers
- */
- unsigned int GetDepressedKeyboardModifiers() const ;
-
- /**
- * @brief get current depressed keyboard modifiers (not latched)
- * @param[in] modifiers depressed keyboard modifiers
- */
- void SetDepressedKeyboardModifiers( unsigned int modifiers);
-
- /**
- * @brief set key repeat rate and delay
- * @param[in] rate repeat rate in milliseconds
- * @param[in] delay delay in milliseconds
- */
- void SetKeyRepeatInfo( unsigned int rate, unsigned int delay );
-
-
- /**
- * @brief Key has been pressed or released.
- * Used for key events from Tizen Wayland wl_text_input interface.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] timestamp timestamp
- * @param[in] symbol key symbol
- * @param[in] state key state
- * @param[in] modifiers keyboard modifiers
- * @return Key event
- */
-
- Dali::KeyEvent GetDALiKeyEventFromSymbol( unsigned int serial,
- unsigned int timestamp,
- unsigned int symbol,
- unsigned int state,
- unsigned int modifiers );
-
- /**
- * @brief Key has been pressed or released. Used
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial serial number
- * @param[in] timestamp timestamp
- * @param[in] keycode raw hardware key code
- * @param[in] state
- * @return Key event
- */
- KeyEvent GetDALiKeyEvent( unsigned int serial, unsigned int timestamp, unsigned int keycode, unsigned int state );
-
-
-private: // data specific to a single seat
-
- /**
- * Keyboard data
- */
- struct XkbData
- {
- XkbData()
- :mContext( NULL ),
- mKeymap( NULL ),
- mState( NULL ),
- mControlMask( 0 ),
- mAltMask( 0 ),
- mShiftMask( 0 ),
- mControlDown( 0 ),
- mShiftDown( 0 ),
- mAltDown( 0 )
- {
-
- }
- struct xkb_context *mContext;
- struct xkb_keymap* mKeymap;
- struct xkb_state* mState;
- xkb_mod_mask_t mControlMask;
- xkb_mod_mask_t mAltMask;
- xkb_mod_mask_t mShiftMask;
- bool mControlDown:1;
- bool mShiftDown:1;
- bool mAltDown:1;
- };
-
- XkbData mXkbData; ///< Keyboard data. Believe this can vary per seat
- std::string mName; ///< Seat name
- WlPointer* mPointer; ///< Wayland Pointer interface ( for multiple pointers )
- WlKeyboard* mKeyboard; ///< Wayland Keyboard interface ( for multiple keyboards )
- WlTouch* mTouch; ///< Wayland Touch interface ( for multiple touch devices )
- WlSeat* mWaylandSeat; ///< Wayland Seat interface
- WlTextInput* mTextInput; ///< Wayland Tizen Text input interface (Virtual Keyboard / IMF)
- WlSurface* mSurface; ///< Surface currently used by this seat
- InputInterface* mInputInterface; ///< DALi Wayland Input interface
- Vector2 mPointerPosition; ///< Current pointer X,Y position
- unsigned int mDepressedKeyboardModifiers; ///< keyboard modifiers
- unsigned int mKeyRepeatRate;
- unsigned int mKeyRepeatDelay;
-
-
-};
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_WAYLAND_SEAT_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <imf-manager-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-#include <adaptor-impl.h>
-#include <string.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
-#endif
-
-// Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
-size_t Utf8SequenceLength(const unsigned char leadByte)
-{
- size_t length = 0;
-
- if ((leadByte & 0x80) == 0 ) //ASCII character (lead bit zero)
- {
- length = 1;
- }
- else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
- {
- length = 2;
- }
- else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
- {
- length = 3;
- }
- else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
- {
- length = 4;
- }
-
- return length;
-}
-
-unsigned int ConvertByteToVisualPosition( const char* utf8String, unsigned int cursorBytePosition )
-{
-
- // check first byte so know how many bytes a character is represented by as keyboard returns cursor position in bytes. Which is different for some languages.
- size_t visualCharacterIndex = 0;
- size_t byteIndex = 0;
-
- // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
- const char leadByte = utf8String[byteIndex];
- while( leadByte != '\0' )
- {
- // attr->end_index is provided as a byte position not character and we need to know the character position.
- const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character.
- if ( byteIndex == cursorBytePosition )
- {
- return visualCharacterIndex;
- // end loop as found cursor position that matches byte position
- }
- else
- {
- byteIndex += currentSequenceLength; // jump to next character
- visualCharacterIndex++; // increment character count so we know our position for when we get a match
- }
- DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( utf8String ));
- }
-
- return visualCharacterIndex;
-}
-
-BaseHandle Create()
-{
- return ImfManager::Get();
-}
-
-TypeRegistration IMF_MANAGER_TYPE( typeid(Dali::ImfManager), typeid(Dali::BaseHandle), Create );
-
-
-}
-bool ImfManager::IsAvailable()
-{
- bool available( false );
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- available = service.GetSingleton( typeid( Dali::ImfManager ) );
- }
- return available;
-}
-
-Dali::ImfManager ImfManager::Get()
-{
- Dali::ImfManager manager;
-
- Dali::SingletonService service( SingletonService::Get() );
- if (! service )
- {
- return manager;
- }
-
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
- if( handle )
- {
- // If so, downcast the handle
- manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
- }
- else if ( Adaptor::IsAvailable() )
- {
- // Create instance and register singleton only if the adaptor is available
- manager = Dali::ImfManager( new ImfManager() );
- service.Register( typeid( manager ), manager );
- }
- else
- {
- DALI_LOG_ERROR("Failed to get native window handle\n");
- }
- return manager;
-}
-ImfManager::ImfManager()
-: mTextInputManager( TextInputManager::Get() ),
- mPreEditCursorPosition( 0 ),
- mEditCursorPosition( 0 ),
- mRestoreAfterFocusLost( false )
-{
- ConnectCallbacks();
-}
-ImfManager::~ImfManager()
-{
- DisconnectCallbacks();
-}
-
-void ImfManager::ConnectCallbacks()
-{
- mTextInputManager.PreEditStringSignal().Connect( this, &ImfManager::PreEditStringChange );
- mTextInputManager.PreEditCursorSignal().Connect( this, &ImfManager::PreEditCursorChange );
- mTextInputManager.CommitStringSignal().Connect( this, &ImfManager::CommitString );
- mTextInputManager.DeleteSurroundingTextSignal().Connect( this, &ImfManager::DeleteSurroundingText );
-
-}
-void ImfManager::DisconnectCallbacks()
-{
- mTextInputManager.PreEditStringSignal().Disconnect( this, &ImfManager::PreEditStringChange );
- mTextInputManager.PreEditCursorSignal().Disconnect( this, &ImfManager::PreEditCursorChange );
- mTextInputManager.CommitStringSignal().Disconnect( this, &ImfManager::CommitString );
- mTextInputManager.DeleteSurroundingTextSignal().Disconnect( this, &ImfManager::DeleteSurroundingText );
-}
-
-void ImfManager::PreEditStringChange( unsigned int serial, const std::string text, const std::string commit )
-{
-
- int visualCursorPosition = 0;
- if( text.length() > 0 )
- {
- visualCursorPosition = ConvertByteToVisualPosition( text.c_str(), mPreEditCursorPosition );
- }
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged to %s, pre-edit cursor %d \n",text.c_str(), mPreEditCursorPosition );
-
-
- // get the latest visual cursor pre-edit position
-
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::PREEDIT, text, visualCursorPosition, visualCursorPosition );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if( callbackData.update )
- {
- mEditCursorPosition = callbackData.cursorPosition;
- mSurroundingText = callbackData.currentText;
- }
-
- if( callbackData.preeditResetRequired )
- {
- mPreEditCursorPosition = 0;
- }
-}
-void ImfManager::PreEditCursorChange( int cursor )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditCursorChange %d\n", cursor );
-
- mPreEditCursorPosition = cursor;
-
-}
-
-void ImfManager::CommitString( unsigned int serial, const std::string commit )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitString\n", commit.c_str() );
-
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::COMMIT, commit, 0, 0 );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if( callbackData.update )
- {
- SetCursorPosition( callbackData.cursorPosition );
- SetSurroundingText( callbackData.currentText );
- mEditCursorPosition = callbackData.cursorPosition;
- mPreEditCursorPosition = mEditCursorPosition;
- NotifyCursorPosition();
- }
-
-}
-void ImfManager::NotifyCursorPosition()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition \n" );
-
- // Set surrounding text also sets the cursor/ anchor position
- SetSurroundingText( mSurroundingText );
-}
-
-void ImfManager::DeleteSurroundingText( int index, unsigned int length )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurroundingText %d %d \n", index, length );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::DELETESURROUNDING, std::string(),index, length );
- Dali::ImfManager handle( this );
- mEventSignal.Emit( handle, imfData );
-}
-
-void ImfManager::Activate()
-{
- Dali::ImfManager handle( this );
- mActivatedSignal.Emit( handle );
-
-}
-
-void ImfManager::Deactivate()
-{
- // do nothing for now
-}
-
-void ImfManager::Reset()
-{
- mSurroundingText = "";
- mPreEditCursorPosition = 0;
- mEditCursorPosition = 0;
- mTextInputManager.Reset();
-}
-
-void* ImfManager::GetContext()
-{
- return this;
-}
-
-bool ImfManager::RestoreAfterFocusLost() const
-{
- return mRestoreAfterFocusLost;
-}
-
-void ImfManager::SetRestoreAfterFocusLost( bool toggle )
-{
- mRestoreAfterFocusLost = toggle;
-}
-
-unsigned int ImfManager::GetCursorPosition() const
-{
- return mEditCursorPosition;
-}
-
-void ImfManager::SetCursorPosition( unsigned int cursorPosition )
-{
- mEditCursorPosition = cursorPosition;
-}
-
-void ImfManager::SetSurroundingText( const std::string& text )
-{
- mSurroundingText = text;
- mTextInputManager.SetSurroundingText( text, mEditCursorPosition, mEditCursorPosition /*anchor*/ );
-}
-
-const std::string& ImfManager::GetSurroundingText() const
-{
- return mSurroundingText;
-}
-
-void ImfManager::NotifyTextInputMultiLine( bool multiLine )
-{
-}
-
-Dali::Rect< int > ImfManager::GetInputMethodArea()
-{
- TextInputManager::SeatInfo& info = mTextInputManager.GetLastActiveSeat();
- return info.mInputPanelDimensions;
-}
-
-void ImfManager::ApplyOptions(const InputMethodOptions& options)
-{
-}
-
-void ImfManager::SetInputPanelData( const std::string& data )
-{
-}
-
-void ImfManager::GetInputPanelData( std::string& data )
-{
-}
-
-Dali::ImfManager::State ImfManager::GetInputPanelState()
-{
- return Dali::ImfManager::DEFAULT;
-}
-
-void ImfManager::SetReturnKeyState( bool visible )
-{
-}
-
-void ImfManager::AutoEnableInputPanel( bool enabled )
-{
-}
-
-void ImfManager::ShowInputPanel()
-{
-}
-
-void ImfManager::HideInputPanel()
-{
-}
-
-Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
-{
- return Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD;
-}
-
-std::string ImfManager::GetInputPanelLocale()
-{
- return NULL;
-}
-
-Dali::ImfManager::TextDirection ImfManager::GetTextDirection()
-{
- TextInputManager::SeatInfo& info = mTextInputManager.GetLastActiveSeat();
- return (Dali::ImfManager::TextDirection)info.mTextDirection;
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_IMF_MANAGER_WL_H
-#define __DALI_INTERNAL_IMF_MANAGER_WL_H
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-
-#include <dali/public-api/object/base-object.h>
-#include <dali/integration-api/events/key-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <imf-manager.h>
-#include "../text-input-manager.h"
-
-namespace Dali
-{
-
-class RenderSurface;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * @brief ImfManager
- *
- * Handles text input editing with the virtual keyboard.
- * The Tizen 3 Wayland text interface is still in development so some
- * features are not available to test like text prediction.
- * When this available we may need to add / test wl_text_input_commit_state
- *
- * To debug low level communication to the Wayland Compositor (Enlightenment) use environment variable
- * export WAYLAND_DEBUG=1
- *
- */
-class ImfManager : public Dali::BaseObject, public ConnectionTracker
-{
-public:
- typedef Dali::ImfManager::ImfManagerSignalType ImfManagerSignalType;
- typedef Dali::ImfManager::ImfEventSignalType ImfEventSignalType;
- typedef Dali::ImfManager::StatusSignalType ImfStatusSignalType;
- typedef Dali::ImfManager::VoidSignalType ImfVoidSignalType;
- typedef Dali::ImfManager::KeyboardTypeSignalType ImfKeyboardTypeSignalType;
- typedef Dali::ImfManager::KeyboardResizedSignalType KeyboardResizedSignalType;
- typedef Dali::ImfManager::LanguageChangedSignalType LanguageChangedSignalType;
-
-public:
-
- /**
- * @brief Check whether the ImfManager is available.
- * @return true if available, false otherwise
- */
- static bool IsAvailable();
-
- /**
- * @brief Get the IMF manager instance
- * It creates the instance if it has not already been created.
- * Internally, a check should be made using IsAvailable() before this is called as we do not want
- * to create an instance if not needed by applications.
- * @see IsAvailable()
- * @return handle to ImfManager
- */
- static Dali::ImfManager Get();
-
- /**
- * @brief Constructor
- */
- ImfManager();
-
- /**
- * Connect Callbacks required for IMF.
- * If you don't connect imf callbacks, you can't get the key events.
- * The events are PreeditChanged, Commit and DeleteSurrounding.
- */
- void ConnectCallbacks();
-
- /**
- * @brief Disconnect Callbacks attached to imf context.
- */
- void DisconnectCallbacks();
-
- /**
- * @copydoc Dali::ImfManager::Activate()
- */
- void Activate();
-
- /**
- * @copydoc Dali::ImfManager::Deactivate()
- */
- void Deactivate();
-
- /**
- * @copydoc Dali::ImfManager::Reset()
- */
- void Reset();
-
- /**
- * @copydoc Dali::ImfManager::GetContext()
- */
- void* GetContext();
-
- /**
- * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
- */
- bool RestoreAfterFocusLost() const;
-
- /**
- * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
- */
- void SetRestoreAfterFocusLost( bool toggle );
-
-
- // Cursor related
- /**
- * @copydoc Dali::ImfManager::NotifyCursorPosition()
- */
- void NotifyCursorPosition();
-
- /**
- * @copydoc Dali::ImfManager::SetCursorPosition()
- */
- void SetCursorPosition( unsigned int cursorPosition );
-
- /**
- * @copydoc Dali::ImfManager::GetCursorPosition()
- */
- unsigned int GetCursorPosition() const;
-
- /**
- * @copydoc Dali::ImfManager::SetSurroundingText()
- */
- void SetSurroundingText( const std::string& text );
-
- /**
- * @copydoc Dali::ImfManager::GetSurroundingText()
- */
- const std::string& GetSurroundingText() const;
-
- /**
- * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
- */
- void NotifyTextInputMultiLine( bool multiLine );
-
- /**
- * @copydoc Dali::ImfManager::GetTextDirection()
- */
- Dali::ImfManager::TextDirection GetTextDirection();
-
- /**
- * @copydoc Dali::ImfManager::GetInputMethodArea()
- */
- Dali::Rect<int> GetInputMethodArea();
-
- /**
- * @copydoc Dali::ImfManager::ApplyOptions()
- */
- void ApplyOptions( const InputMethodOptions& options );
-
- /**
- * @copydoc Dali::ImfManager::SetInputPanelData()
- */
- void SetInputPanelData( const std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelData()
- */
- void GetInputPanelData( std::string& data );
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelState()
- */
- Dali::ImfManager::State GetInputPanelState();
-
- /**
- * @copydoc Dali::ImfManager::SetReturnKeyState()
- */
- void SetReturnKeyState( bool visible );
-
- /**
- * @copydoc Dali::ImfManager::AutoEnableInputPanel()
- */
- void AutoEnableInputPanel( bool enabled );
-
- /**
- * @copydoc Dali::ImfManager::ShowInputPanel()
- */
- void ShowInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::HideInputPanel()
- */
- void HideInputPanel();
-
- /**
- * @copydoc Dali::ImfManager::GetKeyboardType()
- */
- Dali::ImfManager::KeyboardType GetKeyboardType();
-
- /**
- * @copydoc Dali::ImfManager::GetInputPanelLocale()
- */
- std::string GetInputPanelLocale();
-
-public: // Signals
-
- /**
- * @copydoc Dali::ImfManager::ActivatedSignal()
- */
- ImfManagerSignalType& ActivatedSignal() { return mActivatedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::EventReceivedSignal()
- */
- ImfEventSignalType& EventReceivedSignal() { return mEventSignal; }
-
- /**
- * @copydoc Dali::ImfManager::StatusChangedSignal()
- */
- ImfStatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; }
-
- /**
- * @copydoc Dali::ImfManager::ResizedSignal()
- */
- KeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; }
-
- /**
- * @copydoc Dali::ImfManager::LanguageChangedSignal()
- */
- LanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; }
-
- /**
- * @copydoc Dali::ImfManager::KeyboardTypeChangedSignal()
- */
- ImfKeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; }
-
- /**
- * @brief Called when an IMF Pre-Edit change event is received.
- * We are still predicting what the user is typing. The latest string is what the IMF module thinks
- * the user wants to type.
- *
- * @param[in] serial event serial
- * @param[in] text pre-edit string
- * @param[in] commit commit string
- */
- void PreEditStringChange( unsigned int serial, const std::string text, const std::string commit );
-
- /**
- * @brief Called when an IMF Pre-Edit cursor event is received.
- * @param[in] cursor cursor position
- */
- void PreEditCursorChange( int cursor );
-
- /**
- * @brief called when IMF tell us to commit the text
- * @param[in] serial event serial
- * @param[in] commit text to commit
- */
- void CommitString( unsigned int serial, const std::string commit );
-
- /**
- * @brief called when deleting surround text
- * @param[in] index character index to start deleting from
- * @param[in] length number of characters to delete
- */
- void DeleteSurroundingText( int index, unsigned int length );
-
-protected:
-
- /**
- * @brief Destructor.
- */
- virtual ~ImfManager();
-
-
-private:
-
- ImfManagerSignalType mActivatedSignal;
- ImfEventSignalType mEventSignal;
- ImfStatusSignalType mKeyboardStatusSignal;
- KeyboardResizedSignalType mKeyboardResizeSignal;
- LanguageChangedSignalType mKeyboardLanguageChangedSignal;
- ImfKeyboardTypeSignalType mKeyboardTypeChangedSignal;
-
- // Undefined
- ImfManager( const ImfManager& );
- ImfManager& operator=( ImfManager& );
-
-private:
-
- TextInputManager& mTextInputManager;
- std::string mSurroundingText;
- int mPreEditCursorPosition;
- int mEditCursorPosition;
- bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
-
-public:
-
-inline static Internal::Adaptor::ImfManager& GetImplementation(Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<Internal::Adaptor::ImfManager&>(handle);
-}
-
-inline static const Internal::Adaptor::ImfManager& GetImplementation(const Dali::ImfManager& imfManager)
-{
- DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
-
- const BaseObject& handle = imfManager.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::ImfManager&>(handle);
-}
-
-};
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_IMF_MANAGER_WL_H
+++ /dev/null
-#ifndef __DALI_INTERNAL_ADAPTOR_TEXT_INPUT_INTERFACE_H__
-#define __DALI_INTERNAL_ADAPTOR_TEXT_INPUT_INTERFACE_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wl-types.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class Seat;
-
-/**
- * @brief interface used to wrap events that come form the Tizen specific Text input interface (wl_text_input_listener).
- *
- * wayland-extension/protocol/text.xml has been used for the callback descriptions
- *
- * The events are for from a specific seat & surface combination.
- *
- * Once the text input interface is enabled, all key presses come from it
- * except for specifc hardware keys ( volume up / down ) which still get routed
- * to the wl_keyboard interface.
- *
- *
- */
-class TextInputInterface
-{
-
-public:
-
- /**
- * @brief Notify the text input has received focus. Typically in response to an activate request.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] surface wayland surface
- */
- virtual void Enter( Seat* seat, WlSurface* surface ) = 0;
-
- /**
- * @brief Notify the text input when it lost focus.
- * Either in response to a deactivate request or when the assigned surface lost focus or was destroyed.
- * @param[in] seat the seat that produced the event
- */
- virtual void Leave( Seat* seat ) = 0;
-
- /**
- * @brief key modifiers names.
- * The position in the array is the index of the modifier as used in the modifiers
- * bitmask in the keysym event
- * @param[in] seat the seat that produced the event
- * @param[in] map modifier map
- */
- virtual void ModifiersMap( Seat* seat, WlArray *map ) = 0;
-
- /**
- * @brief called when the input panel state changes
- * @param[in] seat the seat that produced the event
- * @param[in] state 0 == panel hidden, 1 == panel visible
- */
- virtual void InputPanelState( Seat* seat, uint32_t state ) = 0;
-
- /**
- * @brief pre-edit string
- * Notify when a new composing text (pre-edit) should be set around the
- * current cursor position. Any previously set composing text should
- * be removed.
- * The commit text can be used to replace the preedit text on reset
- * (for example on unfocus).
- *
- * The text input should also handle all preedit_style and preedit_cursor
- * events occurring directly before preedit_string.
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param [in] text text
- * @param [in] commit commit text
- *
- */
- virtual void PreeditString( Seat* seat, uint32_t serial, const char *text, const char *commit ) = 0;
-
- /**
- * @brief Set styling information on composing text.
- * The style is applied for length bytes from index relative to the beginning of the composing
- * text (as byte offset). Multiple styles can be applied to a composing
- * text by sending multiple preedit_styling events.
- * this event occurs with a preedit_string event.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] index start of the text style
- * @param[in] length of the text style
- * @param[in] style text style
- */
- virtual void PreeditStyling( Seat* seat, uint32_t index, uint32_t length, uint32_t style ) = 0;
-
- /**
- * @brief Set the cursor position inside the composing text (as byte offset)
- * relative to the start of the composing text.
- * When index is a negative number no cursor is shown.
- *
- * this event occurs with a preedit_string event.
- * @param[in] seat the seat that produced the event
- * @param[in] index start of the text style
- */
- virtual void PreeditCursor( Seat* seat, int32_t index ) = 0;
-
- /**
- * @brief Notify when text should be inserted into a DALi text control.
- * The text to commit could be either just a single character after a key press or the
- * result of some composing (pre-edit). It could be also an empty text
- * when some text should be removed (see delete_surrounding_text) or when
- * the input cursor should be moved (see cursor_position).
- * Any previously set composing text should be removed.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] text the text to commit
- */
- virtual void CommitString( Seat* seat, uint32_t serial, const char *text ) = 0;
-
- /**
- * @brief Notify when the cursor or anchor position should be modified.
- * This event should be handled as part of a following commit_string event.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] index relative to the current cursor (in bytes).
- * @param[in] anchor cursor anchor
- */
- virtual void CursorPosition( Seat* seat, int32_t index, int32_t anchor) = 0;
-
- /**
- * @brief Notify when the text around the current cursor position should be deleted.
- * Index is relative to the current cursor (in bytes).
- * Length is the length of deleted text (in bytes).
- * This event should be handled as part of a following commit_string event.
- * @param[in] seat the seat that produced the event
- * @param[in] index relative to the current cursor (in bytes).
- * @param[in] length length of the text to be deleted
- */
- virtual void DeleteSurroundingText( Seat* seat, int32_t index, uint32_t length ) = 0;
-
-
- /**
- * @brief Notify when a key event was sent
- * Key events should not be used for normal text input operations,
- * which should be done with commit_string, delete_surrounding_text, etc.
- * The key event follows the wl_keyboard key event convention.
- * Sym is a XKB keysym, state a wl_keyboard key_state.
- * Modifiers are a mask for effective modifiers
- * (where the modifier indices are set by the modifiers_map event)
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] time time stamp
- * @param[in] sym symbol
- * @param[in] state state
- * @param[in] modifiers modifiers
- */
- virtual void Keysym( Seat* seat,
- uint32_t serial,
- uint32_t time,
- uint32_t sym,
- uint32_t state,
- uint32_t modifiers) = 0;
-
- /**
- * @brief Set the language of the input text.
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] language The "language" argument is a RFC-3066 format language tag.
- */
- virtual void Language( Seat* seat, uint32_t serial, const char *language ) = 0;
-
- /**
- * @brief Set the text direction of input text.
- *
- * It is mainly needed for showing input cursor on correct side of the
- * editor when there is no input yet done and making sure neutral
- * direction text is laid out properly.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] direction ( see text_direction enum in wayland-extension/protocol/text.xml )
- */
- virtual void TextDirection( Seat* seat, uint32_t serial, uint32_t direction ) = 0;
-
- /**
- * @brief Notify when the input panels ask to select the characters
- * from the start cursor position to the end cursor position.
- *
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] start start index
- * @param[in] end end index
- */
- virtual void SelectionRegion( Seat* seat, uint32_t serial, int32_t start, int32_t end) = 0;
-
- /**
- * @brief Notify when the input panels ask to send private command
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] command private command string
- */
- virtual void PrivateCommand( Seat* seat, uint32_t serial, const char *command) = 0;
-
- /**
- * @brief Notify when the geometry of the input panel changed.
- * @param[in] seat the seat that produced the event
- * @param[in] x position
- * @param[in] y position
- * @param[in] width panel width
- * @param[in] height panel height
- */
- virtual void InputPanelGeometry( Seat* seat,
- uint32_t x,
- uint32_t y,
- uint32_t width,
- uint32_t height) = 0;
-
- /**
- * @brief Notify when the input panels ask to send input panel data
- * Not sure what this is for exactly
- * @param[in] seat the seat that produced the event
- * @param[in] serial of the latest known text input state
- * @param[in] data input panel data
- * @param[in] dataLength data length
- *
- */
- virtual void InputPanelData( Seat* seat,
- uint32_t serial,
- const char* data,
- uint32_t dataLength ) = 0;
-
-public: // Helper functions used to find the seat associated with the keyboard/pointer/touch device
-
- /**
- * @brief get the seat that contains the text input interface
- * @param[in] textInput wayland textinput interface
- * @return the seat the keyboard belongs to
- */
- virtual Seat* GetSeat( const WlTextInput* textInput) = 0;
-
-protected:
-
- /**
- * @brief Constructor
- */
- TextInputInterface()
- {
- }
-
- /**
- * @brief destructor
- */
- virtual ~TextInputInterface()
- {
- }
-
- // Undefined copy constructor.
- TextInputInterface( const TextInputInterface& );
-
- // Undefined assignment operator.
- TextInputInterface& operator=( const TextInputInterface& );
-};
-
-
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_INTERNAL_ADAPTOR_TEXT_INPUT_INTERFACE_H__
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-// CLASS HEADER
-#include "text-input-listeners.h"
-
-// INTERNAL INCLUDES
-#include <input/text/text-input-interface.h>
-#include <input/seat.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-
-void Enter( void* data, WlTextInput* textInput, WlSurface* surface )
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->Enter( seat, surface );
-}
-
-void Leave( void* data, WlTextInput* textInput )
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->Leave( seat );
-}
-
-void ModifiersMap( void* data, WlTextInput* textInput, struct wl_array* map )
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->ModifiersMap( seat, map );
-}
-
-void InputPanelState( void* data, WlTextInput* textInput, uint32_t state )
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->InputPanelState( seat, state );
-}
-
-void PreeditString( void* data, WlTextInput* textInput, uint32_t serial, const char* text, const char* commit )
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->PreeditString( seat, serial, text, commit );
-}
-
-void PreeditStyling( void* data, WlTextInput* textInput, uint32_t index, uint32_t length, uint32_t style)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->PreeditStyling( seat, index, length, style );
-}
-
-void PreeditCursor(void* data,
- WlTextInput* textInput,
- int32_t index)
-{
-
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->PreeditCursor( seat, index );
-}
-
-void CommitString(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- const char* text)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->CommitString( seat, serial, text );
-}
-
-void CursorPosition(void* data,
- WlTextInput* textInput,
- int32_t index,
- int32_t anchor)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->CursorPosition( seat, index, anchor );
-}
-
-void DeleteSurroundingText(void* data,
- WlTextInput* textInput,
- int32_t index,
- uint32_t length)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->DeleteSurroundingText( seat, index, length );
-}
-
-void Keysym(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- uint32_t time,
- uint32_t sym,
- uint32_t state,
- uint32_t modifiers)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->Keysym( seat, serial, time, sym, state, modifiers );
-}
-
-void Language(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- const char* language)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->Language( seat, serial, language );
-}
-
-void TextDirection(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- uint32_t direction)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->TextDirection( seat, serial, direction );
-}
-
-void SelectionRegion(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- int32_t start,
- int32_t end)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->SelectionRegion( seat, serial, start, end );
-}
-
-void PrivateCommand(void* data,
- WlTextInput* textInput,
- uint32_t serial,
- const char* command)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->PrivateCommand( seat, serial, command );
-}
-
-void InputPanelGeometry(void* data,
- WlTextInput* textInput,
- uint32_t x,
- uint32_t y,
- uint32_t width,
- uint32_t height)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->InputPanelGeometry( seat, x, y, width, height );
-}
-
-void InputPanelData( void* data,
- WlTextInput* textInput,
- uint32_t serial,
- const char* input_panel_data,
- uint32_t input_panel_data_length)
-{
- TextInputInterface* input = static_cast< TextInputInterface* >( data );
- Seat* seat = input->GetSeat( textInput );
-
- input->InputPanelData( seat, serial, input_panel_data, input_panel_data_length);
-}
-
-
-/**
- * If when running DALi on target a message like
- * listener function for opcode 16 of wl_text_input is NULL,
- * then it means the interface has been updated, and they've added an extra function
- * to the listener
- */
-const WlTextInputListener TextInputListener =
-{
- Enter,
- Leave,
- ModifiersMap,
- InputPanelState,
- PreeditString,
- PreeditStyling,
- PreeditCursor,
- CommitString,
- CursorPosition,
- DeleteSurroundingText,
- Keysym,
- Language,
- TextDirection,
- SelectionRegion,
- PrivateCommand,
- InputPanelGeometry,
- InputPanelData
-};
-
-} // unnamed namespace
-
-
-namespace Wayland
-{
-
-const WlTextInputListener* GetTextInputListener()
-{
- return &TextInputListener;
-}
-
-} // Wayland
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-#ifndef __DALI_WAYLAND_TEXT_INPUT_LISTENERS_H__
-#define __DALI_WAYLAND_TEXT_INPUT_LISTENERS_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wl-types.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace Wayland
-{
-/**
- * Function for getting Tizen Wayland TextInput listener object
- * The listen object contains C callbacks, which currently expect the user data-field
- * to be a DALi TextInputInterface pointer.
- */
-
-/**
- * @brief Listeners for input panel ( virtual keyboard ) events.
- * @return text input listener
- */
-const WlTextInputListener* GetTextInputListener();
-
-
-} // Wayland
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif //__DALI_WAYLAND_INPUT_LISTENERS_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "text-input-manager.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <key-impl.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXT_INPUT");
-#endif
-
-TextInputManager* gTextInputManager = NULL;
-
-
-struct ReturnKeyInfo
-{
- const uint32_t TizenReturnKey;
- const InputMethod::ActionButton ReturnKey;
-};
-
-const ReturnKeyInfo RETURN_KEY_TABLE[] =
-{
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_DEFAULT, InputMethod::ACTION_DEFAULT },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_DONE, InputMethod::ACTION_DONE },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_GO, InputMethod::ACTION_GO },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_JOIN, InputMethod::ACTION_JOIN },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_LOGIN, InputMethod::ACTION_LOGIN },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_NEXT, InputMethod::ACTION_NEXT },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_SEARCH, InputMethod::ACTION_SEARCH },
- { WL_TEXT_INPUT_RETURN_KEY_TYPE_SEND, InputMethod::ACTION_SEND }
-};
-
-const unsigned int RETURN_KEY_TABLE_COUNT = sizeof( RETURN_KEY_TABLE ) / sizeof( RETURN_KEY_TABLE[ 0 ] );
-
-int GetTizenReturnKeyType( InputMethod::ActionButton returnKey )
-{
- for( unsigned int i = 0; i < RETURN_KEY_TABLE_COUNT; i++ )
- {
- const ReturnKeyInfo& info = RETURN_KEY_TABLE[ i ];
- if( info.ReturnKey == returnKey )
- {
- return info.TizenReturnKey;
- }
- }
- DALI_LOG_ERROR("No mapping for InputMethod::ReturnKey %d \n", returnKey );
-
- return WL_TEXT_INPUT_RETURN_KEY_TYPE_DEFAULT;
-
-};
-
-} // unnamed namespace
-
-TextInputManager::TextInputManager()
-: mDisplay( NULL ),
- mLastActiveSeat( NULL ),
- mWindowEventInterface( NULL )
-{
- gTextInputManager = this;
-}
-
-void TextInputManager::AssignWindowEventInterface( WindowEventInterface* eventInterface )
-{
- mWindowEventInterface = eventInterface;
-}
-
-void TextInputManager::AssignDisplay( WlDisplay* display )
-{
- mDisplay = display;
-}
-
-void TextInputManager::AddSeat( Seat* seat )
-{
- SeatInfo info;
- info.mSeat = seat;
- mLastActiveSeat = seat;
-
- mSeats.push_back( info );
-}
-
-TextInputManager::~TextInputManager()
-{
- gTextInputManager = NULL;
-}
-
-TextInputManager& TextInputManager::Get()
-{
- return *gTextInputManager;
-}
-
-void TextInputManager::Enter( Seat* seat, WlSurface* surface )
-{
- // focus received typically in response to an activate request
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
- info.mFocused = true;
-}
-
-void TextInputManager::Leave( Seat* seat )
-{
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
-
- // Focus has been lost either in response
- // to a deactivate request or when the assigned surface lost focus or was destroyed.
- info.mFocused = false;
-}
-
-void TextInputManager::ModifiersMap( Seat* seat, WlArray *map )
-{
- // Map contains an array of 0-terminated modifiers names. The
- // position in the array is the index of the modifier as used in
- // the modifiers bitmask in the keysym event
- // workout if we need to use this
-}
-
-void TextInputManager::InputPanelState( Seat* seat, uint32_t state )
-{
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
-
- info.mInputPanelVisible = ( state == 1 );
-
- // is true, then the keyboard has just shown,
- // state == 1 for show, 0 for hidden
- mKeyboardStatusSignal.Emit( info.mInputPanelVisible );
-
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "TextInputManager::InputPanelState changed to %d \n", state );
-}
-
-void TextInputManager::PreeditString( Seat* seat, uint32_t serial, const char *text, const char *commit )
-{
- mLastActiveSeat = seat;
- mPreEditStringSignal.Emit( serial, text, commit );
-}
-
-void TextInputManager::PreeditStyling( Seat* seat, uint32_t index, uint32_t length, uint32_t style )
-{
- mLastActiveSeat = seat;
- mPreEditStylingSignal.Emit( index, length, style );
-}
-
-void TextInputManager::PreeditCursor( Seat* seat, int32_t index )
-{
- mLastActiveSeat = seat;
- mPreEditCursorSignal.Emit( index );
-}
-
-void TextInputManager::CommitString( Seat* seat, uint32_t serial, const char *text )
-{
- mLastActiveSeat = seat;
- mCommitStringSignal.Emit( serial, text );
-
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "TextInputManager::CommitString %s \n", text );
-}
-
-void TextInputManager::CursorPosition( Seat* seat, int32_t index, int32_t anchor )
-{
- mLastActiveSeat = seat;
- mCursorPositionSignal.Emit( index, anchor );
-}
-
-void TextInputManager::DeleteSurroundingText( Seat* seat, int32_t index, uint32_t length )
-{
- mLastActiveSeat = seat;
- mDeleteSurroundingTextSignal.Emit( index, length );
-}
-
-
-void TextInputManager::Keysym( Seat* seat,
- uint32_t serial,
- uint32_t time,
- uint32_t sym,
- uint32_t state,
- uint32_t modifiers)
-{
- mLastActiveSeat = seat;
-
- Dali::KeyEvent keyEvent = seat->GetDALiKeyEventFromSymbol( serial, time, sym, state, modifiers );
-
- // key.h which is shared between all platforms uses X keycodes
- // We convert from a Wayland keycode to a DALi key ( if it exists).
- // For examples Backspace in Wayland is the code 65288, we convert this to 22 = DALI_KEY_BACKSPACE
-
- int daliKeyCode = KeyLookup::GetDaliKeyCode( keyEvent.keyPressedName.c_str() );
- if( daliKeyCode != -1 )
- {
- // we have a match, the key will be backspace, shift etc.
- // we have to clear out the keyPressed string, otherwise the toolkit can end up displaying it.
- keyEvent.keyCode = daliKeyCode;
- keyEvent.keyPressed ="";
-
- }
-
- Integration::KeyEvent convertedEvent( keyEvent );
- mWindowEventInterface->KeyEvent( convertedEvent );
-}
-
-void TextInputManager::Language( Seat* seat, uint32_t serial, const char *language )
-{
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
- info.mLanguage = language;
- mKeyboardLanguageChangedSignal.Emit();
-}
-
-void TextInputManager::TextDirection( Seat* seat, uint32_t serial, uint32_t direction )
-{
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
-
- // text-input direction can be auto, left to right, or right to left
- // DALi only supports ltr or rtl
- if( direction == WL_TEXT_INPUT_TEXT_DIRECTION_RTL )
- {
- info.mTextDirection = Dali::VirtualKeyboard::RightToLeft;
- }
- else
- {
- info.mTextDirection = Dali::VirtualKeyboard::LeftToRight;
- }
-}
-
-void TextInputManager::SelectionRegion( Seat* seat, uint32_t serial, int32_t start, int32_t end )
-{
- mLastActiveSeat = seat;
- mSelectionRegionSignal.Emit( serial, start, end );
-}
-
-void TextInputManager::PrivateCommand( Seat* seat, uint32_t serial, const char *command )
-{
- mLastActiveSeat = seat;
- // not required
-}
-
-void TextInputManager::InputPanelGeometry( Seat* seat,
- uint32_t x,
- uint32_t y,
- uint32_t width,
- uint32_t height)
-{
- mLastActiveSeat = seat;
- SeatInfo& info = GetLastActiveSeat();
- Dali::Rect< int > newDimensions( x, y, width, height );
-
- if( info.mInputPanelDimensions != newDimensions )
- {
- info.mInputPanelDimensions = newDimensions;
- mKeyboardResizeSignal.Emit();
- }
-}
-
-void TextInputManager::InputPanelData( Seat* seat,
- uint32_t serial,
- const char* data,
- uint32_t dataLength )
-{
- mLastActiveSeat = seat;
- // unsure what this function in the text protocol is used for due to limited documentation
-}
-
-TextInputManager::SeatInfo& TextInputManager::GetLastActiveSeat()
-{
- SeatInfo* currentSeat = &mSeats[ 0 ];
-
- for( std::vector< SeatInfo >::iterator iter = mSeats.begin(); iter != mSeats.end(); ++iter )
- {
- if( ( *iter ).mSeat == mLastActiveSeat )
- {
- currentSeat = &( *iter );
- break;
- }
-
- }
- return *currentSeat;
-}
-
-Seat* TextInputManager::GetSeat( const WlTextInput* textInput)
-{
- for( std::vector< SeatInfo >::iterator iter = mSeats.begin(); iter != mSeats.end(); ++iter )
- {
- Seat* seat = ( *iter ).mSeat;
-
- if( seat->GetTextInputInterface() == textInput )
- {
- return seat;
- }
- }
- return NULL;
-}
-
-void TextInputManager::ShowInputPanel()
-{
- SeatInfo& info = GetLastActiveSeat();
- info.mInputPanelVisible = true;
- Seat* seat = info.mSeat;
-
- wl_text_input_show_input_panel( seat->GetTextInputInterface() );
-
- // imf normally does this...
- wl_text_input_activate( seat->GetTextInputInterface(), seat->GetSeatInterface(), seat->GetSurface() );
-
- wl_display_flush( mDisplay );
-}
-
-void TextInputManager::HideInputPanel()
-{
- SeatInfo& info = GetLastActiveSeat();
- info.mInputPanelVisible = false;
- Seat* seat = info.mSeat;
-
- wl_text_input_deactivate( seat->GetTextInputInterface(), seat->GetSeatInterface() );
-
- wl_text_input_hide_input_panel( seat->GetTextInputInterface() );
-
- wl_display_flush( mDisplay );
-}
-
-bool TextInputManager::IsInputPanelVisible()
-{
- SeatInfo& info = GetLastActiveSeat();
-
-
- return info.mInputPanelVisible;
-}
-
-void TextInputManager::SetReturnKeyType( const InputMethod::ActionButton type )
-{
- TextInputManager::SeatInfo& info = TextInputManager::Get().GetLastActiveSeat();
-
- uint32_t returnKey = GetTizenReturnKeyType( type );
-
- wl_text_input_set_return_key_type( info.mSeat->GetTextInputInterface(), returnKey );
-
- wl_display_flush( mDisplay );
-}
-
-void TextInputManager::Reset()
-{
- TextInputManager::SeatInfo& info = TextInputManager::Get().GetLastActiveSeat();
-
- wl_text_input_reset( info.mSeat->GetTextInputInterface() );
-
- wl_display_flush( mDisplay );
-}
-
-void TextInputManager::SetSurroundingText( std::string text, unsigned int cursor, unsigned int anchor )
-{
- // set surrounding text API is subject to change in wayland.
- wl_display_flush( mDisplay );
-}
-
-
-TextInputManager::PreEditStringSignalType& TextInputManager::PreEditStringSignal()
-{
- return mPreEditStringSignal;
-}
-
-
-TextInputManager::PreEditStylingSignalType& TextInputManager::PreEditStylingSignal()
-{
- return mPreEditStylingSignal;
-}
-TextInputManager::PreEditCursorSignalType& TextInputManager::PreEditCursorSignal()
-{
- return mPreEditCursorSignal;
-}
-
-TextInputManager::CommitStringSignalType& TextInputManager::CommitStringSignal()
-{
- return mCommitStringSignal;
-}
-
-TextInputManager::CursorPositionSignalType& TextInputManager::CursorPositionSignal()
-{
- return mCursorPositionSignal;
-}
-
-TextInputManager::DeleteSurroundingTextSignalType& TextInputManager::DeleteSurroundingTextSignal()
-{
- return mDeleteSurroundingTextSignal;
-}
-
-TextInputManager::SelectionRegionSignalType& TextInputManager::SelectionRegionSignal()
-{
- return mSelectionRegionSignal;
-}
-
-Dali::VirtualKeyboard::StatusSignalType& TextInputManager::StatusChangedSignal()
-{
- return mKeyboardStatusSignal;
-}
-
-Dali::VirtualKeyboard::VoidSignalType& TextInputManager::ResizedSignal()
-{
- return mKeyboardResizeSignal;
-}
-
-Dali::VirtualKeyboard::VoidSignalType& TextInputManager::LanguageChangedSignal()
-{
- return mKeyboardLanguageChangedSignal;
-}
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_WAYLAND_TEXT_INPUT_MANAGER_H__
-#define __DALI_WAYLAND_TEXT_INPUT_MANAGER_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <vector>
-
-// INTERNAL INCLUDES
-#include <input/text/text-input-interface.h>
-#include <input/seat.h>
-#include <virtual-keyboard.h>
-#include <wl-types.h>
-#include <base/interfaces/window-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-
-/**
- * Handles wayland text input interface which deals with the input panel (virtual keyboard ).
- *
- */
-class TextInputManager : private TextInputInterface
-{
-
-public:
-
- /**
- * @brief Constructor
- */
- TextInputManager();
-
- /**
- * @brief Destructor
- */
- ~TextInputManager();
-
- /**
- * @brief Assign the window event interface
- * Used to send key events to DALi
- * @param[in] eventInterface event interface
- */
- void AssignWindowEventInterface( WindowEventInterface* eventInterface );
-
- /**
- * @brief Assign the Wayland connection
- * @param[in] display Wayland display
- */
- void AssignDisplay( WlDisplay* display );
-
- /**
- * @brief Add a seat
- * @param seat seat pointer
- */
- void AddSeat( Seat* seat );
-
- /**
- * Get the global TextInputManager
- */
- static TextInputManager& Get();
-
-private: // TextInputInterface
-
- /**
- * @copydoc TextInputInterface::Enter
- */
- virtual void Enter( Seat* seat, WlSurface* surface );
-
- /**
- * @copydoc TextInputInterface::Leave
- */
- virtual void Leave( Seat* seat );
-
- /**
- * @copydoc TextInputInterface::ModifiersMap
- */
- virtual void ModifiersMap( Seat* seat, WlArray *map );
-
- /**
- * @copydoc TextInputInterface::InputPanelState
- */
- virtual void InputPanelState( Seat* seat, uint32_t state );
-
- /**
- * @copydoc TextInputInterface::PreeditString
- */
- virtual void PreeditString( Seat* seat, uint32_t serial, const char *text, const char *commit );
-
- /**
- * @copydoc TextInputInterface::PreeditStyling
- */
- virtual void PreeditStyling( Seat* seat, uint32_t index, uint32_t length, uint32_t style );
-
- /**
- * @copydoc TextInputInterface::PreeditCursor
- */
- virtual void PreeditCursor( Seat* seat, int32_t index );
-
- /**
- * @copydoc TextInputInterface::CommitString
- */
- virtual void CommitString( Seat* seat, uint32_t serial, const char *text );
-
- /**
- * @copydoc TextInputInterface::CursorPosition
- */
- virtual void CursorPosition( Seat* seat, int32_t index, int32_t anchor );
-
- /**
- * @copydoc TextInputInterface::DeleteSurroundingText
- */
- virtual void DeleteSurroundingText( Seat* seat, int32_t index, uint32_t length );
-
-
- /**
- * @copydoc TextInputInterface::Keysym
- */
- virtual void Keysym( Seat* seat,
- uint32_t serial,
- uint32_t time,
- uint32_t sym,
- uint32_t state,
- uint32_t modifiers);
-
- /**
- * @copydoc TextInputInterface::Language
- */
- virtual void Language( Seat* seat, uint32_t serial, const char *language );
-
- /**
- * @copydoc TextInputInterface::TextDirection
- */
- virtual void TextDirection( Seat* seat, uint32_t serial, uint32_t direction );
-
- /**
- * @copydoc TextInputInterface::SelectionRegion
- */
- virtual void SelectionRegion( Seat* seat, uint32_t serial, int32_t start, int32_t end );
-
- /**
- * @copydoc TextInputInterface::PrivateCommand
- */
- virtual void PrivateCommand( Seat* seat, uint32_t serial, const char *command );
-
- /**
- * @copydoc TextInputInterface::InputPanelGeometry
- */
- virtual void InputPanelGeometry( Seat* seat, uint32_t x, uint32_t y, uint32_t width, uint32_t height );
-
- /**
- * @copydoc TextInputInterface::InputPanelData
- */
- virtual void InputPanelData( Seat* seat,
- uint32_t serial,
- const char* data,
- uint32_t dataLength );
-
- /**
- * @copydoc TextInputInterface::GetSeat
- */
- virtual Seat* GetSeat( const WlTextInput* textInput );
-
-public:
-
- /**
- * @brief show the input panel (virtual keyboard)
- */
- void ShowInputPanel();
-
- /**
- * @brief hide the input panel
- */
- void HideInputPanel();
-
- /**
- * @brief see if the input panel is visible
- * @return true if panel is visible
- */
- bool IsInputPanelVisible();
-
- /**
- * @brief set the return key type
- * @param[in] type return key type
- */
- void SetReturnKeyType( const InputMethod::ActionButton type );
-
- /**
- * @brief reset inputs state
- * Should be called by an editor widget when the input state should be
- * reset, for example after the text was changed outside of the normal
- * input method flow.
- */
- void Reset();
-
- /**
- * @brief
- * Set the plain surrounding text around the input position. Text is
- * UTF-8 encoded. Cursor is the byte offset within the
- * surrounding text. Anchor is the byte offset of the
- * selection anchor within the surrounding text. If there is no selected
- * text anchor is the same as cursor.
- * @param[in] text the text
- * @param[in] cursor cursor position
- * @param[in] anchor anchor position
- */
- void SetSurroundingText( std::string text, unsigned int cursor, unsigned int anchor );
-
-
-
-public: // virtual keyboard signals
-
- /**
- * @copydoc Dali::VirtualKeyboard::StatusChangedSignal
- */
- Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal();
-
- /**
- * @copydoc Dali::VirtualKeyboard::ResizedSignal
- */
- Dali::VirtualKeyboard::VoidSignalType& ResizedSignal();
-
- /**
- * @copydoc Dali::VirtualKeyboard::LanguageChangedSignal
- */
- Dali::VirtualKeyboard::VoidSignalType& LanguageChangedSignal();
-
-public: ///< Input Panel Signals ( DALi currently doesn't use these, it only uses signals from IMF interface).
-
- typedef Signal< void ( unsigned int, const std::string, const std::string ) > PreEditStringSignalType;
- typedef Signal< void ( unsigned int, unsigned int length, unsigned int ) > PreEditStylingSignalType;
- typedef Signal< void ( int ) > PreEditCursorSignalType;
- typedef Signal< void ( unsigned int, const std::string ) > CommitStringSignalType;
- typedef Signal< void ( int , int ) > CursorPositionSignalType;
- typedef Signal< void ( int , unsigned int ) > DeleteSurroundingTextSignalType;
- typedef Signal< void ( unsigned int ,int, int ) > SelectionRegionSignalType;
-
- /**
- * @brief Notify when composing new text
- * Description from wayland-extension/protocol/text.xml:
- * Notify when a new composing text (pre-edit) should be set around the
- * current cursor position. Any previously set composing text should
- * be removed.
- *
- * The commit text can be used to replace the preedit text on reset (for example on unfocus).
- * The text input should also handle all preedit_style and preedit_cursor
- * events occurring directly before preedit_string.
- *
- * @code
- * void YourCallbackName( unsigned int serial, std::string text, std::string commit );
- * @endcode
- */
- PreEditStringSignalType& PreEditStringSignal();
-
- /**
- * @brief Pre-edit styling
- *
- * Description from wayland-extension/protocol/text.xml:
- * Set styling information on composing text. The style is applied for
- * length bytes from index relative to the beginning of the composing
- * text (as byte offset). Multiple styles can be applied to a composing
- * text by sending multiple preedit_styling events.
- *
- *
- * @code
- * void YourCallbackName( unsigned int index, unsigned int length, unsigned int style );
- * @endcode
- */
- PreEditStylingSignalType& PreEditStylingSignal();
-
- /**
- * @brief Notify pre-edit cursor position
- * Description from wayland-extension/protocol/text.xml:
- * Set the cursor position inside the composing text (as byte
- * offset) relative to the start of the composing text. When index is a
- * negative number no cursor is shown.
- *
- * @code
- * void YourCallbackName( int index );
- * @endcode
- */
- PreEditCursorSignalType& PreEditCursorSignal();
-
- /**
- * @brief Commit string text
- * From wayland-extension/protocol/text.xml:
- * Notify when text should be inserted into the editor widget. The text to
- * commit could be either just a single character after a key press or the
- * result of some composing (pre-edit). It could be also an empty text
- * when some text should be removed (see delete_surrounding_text) or when
- * the input cursor should be moved (see cursor_position).
- *
- * Any previously set composing text should be removed.
- *
- * @code
- * void YourCallbackName( const std::string text );
- * @endcode
- */
- CommitStringSignalType& CommitStringSignal();
-
- /**
- * @brief Cursor position signal
- * From wayland-extension/protocol/text.xml:
- * Notify when the cursor or anchor position should be modified.
- * This event should be handled as part of a following commit_string event.
- * @code
- * void YourCallbackName( int index, int anchor );
- * @endcode
- */
- CursorPositionSignalType& CursorPositionSignal();
-
- /**
- * @brief delete surrounding text
- * From wayland-extension/protocol/text.xml:
- * Notify when the text around the current cursor position should be deleted.
- * @code
- * Index is relative to the current cursor (in bytes).
- * Length is the length of deleted text (in bytes).
- *
- * void YourCallbackName( int index, unsigned int length );
- * @endcode
- * This event should be handled as part of a following commit_string event.
- */
- DeleteSurroundingTextSignalType& DeleteSurroundingTextSignal();
-
- /**
- * @brief text selection region
- * Notify when the input panels ask to select the characters
- * from the start cursor position to the end cursor position.
- * * @code
- * Index is relative to the current cursor (in bytes).
- * Length is the length of deleted text (in bytes).
- *
- * void YourCallbackName( unsigned int serial, int start, int end );
- * @endcode
- */
- SelectionRegionSignalType& SelectionRegionSignal();
-
-public:
-
- /**
- * POD to store text input data for each seat.
- */
- struct SeatInfo
- {
- SeatInfo()
- : mTextDirection( Dali::VirtualKeyboard::LeftToRight ),
- mSeat( NULL ),
- mInputPanelDimensions( 0,0,0,0 ),
- mReturnKeyType( InputMethod::ACTION_UNSPECIFIED ),
- mInputPanelVisible( false ),
- mFocused( false )
- {
-
- }
- Dali::VirtualKeyboard::TextDirection mTextDirection;
- Seat* mSeat;
- Dali::Rect<int> mInputPanelDimensions; ///< size of the input panel
- std::string mLanguage; ///< input panel language
- InputMethod::ActionButton mReturnKeyType; ///< return key
- bool mInputPanelVisible:1; ///< panel status
- bool mFocused:1;
- };
-
- /**
- * @brief get the last active seat
- * @return the last active seat
- */
- SeatInfo& GetLastActiveSeat();
-
-private:
-
- WlDisplay* mDisplay; ///< Wayland display, handles all the data sent from and to the compositor
- Seat* mLastActiveSeat; ///< Seat that was last used
- WindowEventInterface* mWindowEventInterface;
-
- std::vector< SeatInfo > mSeats; ///< keeps track of text input information for each seat
- Dali::VirtualKeyboard::StatusSignalType mKeyboardStatusSignal;
- Dali::VirtualKeyboard::VoidSignalType mKeyboardResizeSignal;
- Dali::VirtualKeyboard::VoidSignalType mKeyboardLanguageChangedSignal;
-
- // Input Panel (Virtual Keyboard) signals
- PreEditStringSignalType mPreEditStringSignal;
- PreEditStylingSignalType mPreEditStylingSignal;
- PreEditCursorSignalType mPreEditCursorSignal;
- CommitStringSignalType mCommitStringSignal;
- CursorPositionSignalType mCursorPositionSignal;
- DeleteSurroundingTextSignalType mDeleteSurroundingTextSignal;
- SelectionRegionSignalType mSelectionRegionSignal;
-
-};
-
-
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// HEADER
-#include <virtual-keyboard.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include "text-input-manager.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-#define TOKEN_STRING(x) #x
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIRTUAL_KEYBOARD");
-#endif
-}
-// Current DALi Virtual Keyboard devel API has no knowledge of Seats
-// so we use the most recently 'active' seat. If Tizen ever supports two input panels
-// at the same time, we need to modify DALi to be aware of it.
-namespace VirtualKeyboard
-{
-
-// Functions listed in order from virtual-keyboard.h
-
-void Show()
-{
- TextInputManager::Get().ShowInputPanel();
-}
-
-void Hide()
-{
- TextInputManager::Get().HideInputPanel();
-}
-
-bool IsVisible()
-{
- return TextInputManager::Get().IsInputPanelVisible();
-}
-
-
-void SetReturnKeyType( const InputMethod::ActionButton type )
-{
- TextInputManager::Get().SetReturnKeyType( type );
-}
-
-void ApplySettings( const Property::Map& settingsMap )
-{
- using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING.
-
- for( unsigned int i = 0, count = settingsMap.Count(); i < count; ++i )
- {
- std::string key = settingsMap.GetKey( i );
- Property::Value item = settingsMap.GetValue(i);
-
- if( key == TOKEN_STRING( ACTION_BUTTON ) )
- {
- if( item.GetType() == Property::INTEGER )
- {
- int value = item.Get< int >();
- SetReturnKeyType( static_cast<InputMethod::ActionButton>(value) );
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" );
- }
- }
-}
-
-
-InputMethod::ActionButton GetReturnKeyType()
-{
- TextInputManager::SeatInfo& info = TextInputManager::Get().GetLastActiveSeat();
- return info.mReturnKeyType;
-}
-
-void EnablePrediction(const bool enable)
-{
- // currently not part of Tizen text_input protocol
-}
-
-bool IsPredictionEnabled()
-{
- return false;
-}
-
-Dali::Rect< int > GetSizeAndPosition()
-{
- TextInputManager::SeatInfo& info = TextInputManager::Get().GetLastActiveSeat();
- return info.mInputPanelDimensions;
-}
-
-void RotateTo(int angle)
-{
- // not part of the wayland protocol
-}
-
-Dali::VirtualKeyboard::TextDirection GetTextDirection()
-{
- TextInputManager::SeatInfo& info = TextInputManager::Get().GetLastActiveSeat();
- return info.mTextDirection;
-}
-
-Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal()
-{
- return TextInputManager::Get().StatusChangedSignal();
-}
-
-Dali::VirtualKeyboard::VoidSignalType& ResizedSignal()
-{
- return TextInputManager::Get().ResizedSignal();
-}
-
-Dali::VirtualKeyboard::VoidSignalType& LanguageChangedSignal()
-{
- return TextInputManager::Get().LanguageChangedSignal();
-}
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "render-surface-wl.h"
-
-// EXTERNAL INCLUDES
-#include <stdio.h>
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-#include <cstring>
-#include <unistd.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-implementation.h>
-#include <trigger-event.h>
-#include <base/interfaces/window-event-interface.h>
-#include <wayland-manager.h>
-
-
-namespace Dali
-{
-
-namespace Wayland
-{
-
-RenderSurface::RenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: mRenderNotification(NULL),
- mColorDepth(isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24),
- mEglWindow(NULL)
-{
- mWindow.mPosition = positionSize;
- mWindow.mTitle = name;
- mWaylandManager = new Dali::Internal::Adaptor::WaylandManager;
- mWaylandManager->Initialise();
-}
-
-RenderSurface::~RenderSurface()
-{
- delete mWaylandManager;
-}
-
-void RenderSurface::CreateSurface()
-{
- mWaylandManager->CreateSurface( mWindow );
-}
-
-Window* RenderSurface::GetWindow()
-{
- return &mWindow;
-}
-
-
-void RenderSurface::AssignWindowEventInterface( Dali::Internal::Adaptor::WindowEventInterface* eventInterface)
-{
- mWaylandManager->AssignWindowEventInterface( eventInterface );
-}
-
-PositionSize RenderSurface::GetPositionSize() const
-{
- return mWindow.mPosition;
-}
-
-void RenderSurface::InitializeEgl( EglInterface& egl )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- if (!eglImpl.InitializeGles(static_cast<EGLNativeDisplayType>( mWaylandManager->mDisplay )))
- {
- DALI_LOG_ERROR("Failed to initialize GLES.\n");
- }
-
- eglImpl.ChooseConfig( true, mColorDepth );
-}
-
-void RenderSurface::CreateEglSurface( EglInterface& egl )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- CreateSurface();
-
- mEglWindow = wl_egl_window_create( mWaylandManager->GetSurface(), mWindow.mPosition.width, mWindow.mPosition.height);
-
- eglImpl.CreateSurfaceWindow( (EGLNativeWindowType)mEglWindow, mColorDepth ); // reinterpret_cast does not compile
-
-}
-
-void RenderSurface::DestroyEglSurface( EglInterface& eglIf )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
- eglImpl.DestroySurface();
- wl_egl_window_destroy( mEglWindow );
- mEglWindow = NULL;
-}
-
-bool RenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- return true;
-}
-
-void RenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
-}
-
-void RenderSurface::SetViewMode( ViewMode viewMode )
-{
-}
-
-void RenderSurface::StartRender()
-{
-}
-
-bool RenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
-{
- return true;
-}
-
-void RenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.SwapBuffers();
-}
-
-void RenderSurface::StopRender()
-{
-}
-
-void RenderSurface::ReleaseLock()
-{
-}
-void RenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
-{
-}
-
-RenderSurface::Type RenderSurface::GetSurfaceType()
-{
- return RenderSurface::WAYLAND_RENDER_SURFACE;
-}
-
-} // namespace Wayland
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_RENDER_SURFACE_WL_H__
-#define __DALI_RENDER_SURFACE_WL_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <wayland-manager.h>
-#include <wayland-egl.h>
-
-// INTERNAL INCLUDES
-#include <wayland-window.h>
-#include <render-surface.h>
-#include <egl-interface.h> // for color depth
-
-namespace Dali
-{
-
-class TriggerEventInterface;
-
-namespace Internal
-{
-namespace Adaptor
-{
-class WaylandManager;
-class WindowEventInterface;
-}
-}
-
-namespace Wayland
-{
-
-
-/**
- * Wayland render surface.
- */
-class RenderSurface : public Dali::RenderSurface
-{
-public:
-
- /**
- * @brief Constructor.
- *
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- RenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent = false);
-
- /**
- * @brief Destructor
- */
- virtual ~RenderSurface();
-
-protected:
-
-
- /**
- * @Create the surface
- */
- void CreateSurface();
-
-public:
-
- /**
- * @brief Get window handle
- *
- * @return the wayland window pointer
- */
- Window* GetWindow();
-
- /**
- * Assigns an event interface to the surface for getting
- * input events / window notifications
- */
- void AssignWindowEventInterface( Dali::Internal::Adaptor::WindowEventInterface* eventInterface );
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::GetPositionSize()
- */
- virtual PositionSize GetPositionSize() const;
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- virtual void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender();
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::ReleaseLock()
- */
- virtual void ReleaseLock();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization()
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
- /**
- * @copydoc Dali::RenderSurface::GetSurfaceType()
- */
- virtual RenderSurface::Type GetSurfaceType();
-
-protected: // Data
-
- Window mWindow;
- TriggerEventInterface* mRenderNotification; ///< Render notification trigger
- Dali::ColorDepth mColorDepth; ///< Color depth
- Dali::Internal::Adaptor::WaylandManager* mWaylandManager; ///< wayland manager
- wl_egl_window* mEglWindow;
-
-};
-
-} // namespace Wayland
-
-} // namespace Dali
-
-#endif // __DALI_RENDER_SURFACE_WL_H__
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-// CLASS HEADER
-#include "wayland-manager.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <base/interfaces/window-event-interface.h>
-#include <base/interfaces/performance-interface.h>
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-namespace
-{
-
-const int NO_EVENTS_ALREADY_IN_QUEUE = 0;
-
-
-void ShellSurfacePing( void* data, struct wl_shell_surface* shell_surface, uint32_t serial)
-{
- // The ping event comes from the compositor to checks if we're still alive.
- wl_shell_surface_pong(shell_surface, serial);
-}
-
-void ShellSurfaceConfigure( void* data, struct wl_shell_surface* shell_surface, uint32_t edges, int32_t width, int32_t height)
-{
-}
-
-const struct wl_shell_surface_listener ShellSurfaceListener =
-{
- ShellSurfacePing,
- ShellSurfaceConfigure,
-};
-
-
-void XdgShellPing( void* data, Dali::WlXdgShell* shell, uint32_t serial)
-{
- // The ping event comes from the compositor to checks if we're still alive.
- xdg_shell_pong( shell, serial);
-}
-
-struct xdg_shell_listener XdgShellListener=
-{
- XdgShellPing,
-};
-
-
-void RegistryGlobalCallback( void *data,
- struct wl_registry *wlRegistry,
- uint32_t name,
- const char *interface,
- uint32_t version)
-{
-
- WaylandManager* client = static_cast< WaylandManager* >( data );
-
- if( strcmp( interface, wl_compositor_interface.name ) == 0 )
- {
- client->mCompositor = static_cast< Dali::WlCompositor* >( wl_registry_bind( wlRegistry, name, &wl_compositor_interface, version ) );
- }
- else if( strcmp( interface, wl_seat_interface.name ) == 0 )
- {
- // register for seat callbacks and add a new seat to the input manager
- Dali::WlSeat* seatInterface = static_cast< Dali::WlSeat* >( wl_registry_bind( wlRegistry, name, &wl_seat_interface, version ) );
-
- client->mInputManager.AddSeatListener( seatInterface );
- }
- else if( strcmp( interface, wl_output_interface.name ) == 0 )
- {
- // get the interface and add the listener
- Dali::WlOutput* output = static_cast< Dali::WlOutput* >( wl_registry_bind( wlRegistry, name, &wl_output_interface, version ) );
- client->mCompositorOutput.AddListener( output );
- }
- else if( strcmp( interface, wl_shell_interface.name ) == 0 )
- {
- client->mShell = static_cast< Dali::WlShell* >( wl_registry_bind( wlRegistry, name, &wl_shell_interface, version ) );
- }
- else if( strcmp( interface, xdg_shell_interface.name ) == 0 )
- {
- client->mXdgShell = static_cast< struct xdg_shell* >( wl_registry_bind( wlRegistry, name, &xdg_shell_interface, version ) );
- // without this line Tizen 3 reports...
- // xdg_shell@7: error 0: Must call use_unstable_version first
- xdg_shell_use_unstable_version( client->mXdgShell, 5 );
- }
- else if( strcmp( interface, wl_text_input_manager_interface.name ) == 0 )
- {
- Dali::WlTextInputManager* inputManager = static_cast< Dali::WlTextInputManager* >( wl_registry_bind( wlRegistry, name, &wl_text_input_manager_interface, version ) );
-
- client->mInputManager.AddTextInputManager( inputManager );
- }
-
-
-}
-
-
-void RegistryGlobalCallbackRemove(void *data, struct wl_registry *registry, uint32_t id)
-{
- // occurs when a device is unplugged
-}
-
-const struct wl_registry_listener RegistryListener =
-{
- RegistryGlobalCallback,
- RegistryGlobalCallbackRemove,
-};
-
-} //unnamed namespace
-
-WaylandManager::WaylandManager()
-:mDisplay( NULL ),
- mShell( NULL ),
- mCompositor( NULL ),
- mDisplayFileDescriptor( 0 ),
- mFileDescriptorMonitor( NULL ),
- mXdgShell( NULL ),
- mSurface( NULL ),
- mShellSurface( NULL ),
- mXdgSurface( NULL )
-{
-}
-WaylandManager::~WaylandManager()
-{
- if( mXdgShell)
- {
- xdg_shell_destroy( mXdgShell );
- }
- if( mShell )
- {
- wl_shell_destroy( mShell );
- }
- if( mCompositor )
- {
- wl_compositor_destroy( mCompositor );
- }
- if( mDisplay )
- {
- wl_display_disconnect( mDisplay );
- }
-
- delete mFileDescriptorMonitor;
-}
-
-void WaylandManager::Initialise()
-{
- if( mDisplay )
- {
- return;
- }
- // Connect to a Wayland socket on the Wayland server/
- // NULL = use default display aka "wayland-0"
- // returns a new display context object
-
- mDisplay = wl_display_connect( NULL );
-
- DALI_ASSERT_ALWAYS( mDisplay && "wl_display_connect failed");
-
- // Monitor the display file descriptor used to communicate with Wayland server
- InstallFileDescriptorMonitor();
-
- mInputManager.AssignDisplay( mDisplay );
-
- // Get the interfaces to compositor / shell etc
- GetWaylandInterfaces();
-
-}
-void WaylandManager::ReadAndDispatchEvents()
-{
- // Wayland client uses a single file descriptor to communicate with the compositor.
- // Because DALi can have multiple client threads ( event thread for input, render thread for Tizen buffer management / TPL )
- // it has to use the Wayland client thread safe API to prevent a dead lock
-
- // prepare_read announces the calling thread's intention to read from the file descriptor
- // If there is already events queued up in the default queue, then dispatch those first
- while( wl_display_prepare_read( mDisplay ) != NO_EVENTS_ALREADY_IN_QUEUE )
- {
- // dispatch the event, e.g. a touch event or a clipboard event
- wl_display_dispatch_pending( mDisplay );
- }
-
- // At this point the default queue is empty.
- // We read data from the file descriptor in their respective queues
- // This is thread safe. No other threads will read from the fd and queue events during this operation.
- int ret = wl_display_read_events( mDisplay );
-
- if( ret == 0 )
- {
- // dispatch the events from the default queue
- wl_display_dispatch_pending( mDisplay );
- }
- else
- {
- DALI_LOG_ERROR("wl_display_read_events error\n");
- }
-
-}
-void WaylandManager::AssignWindowEventInterface( WindowEventInterface* eventInterface)
-{
- mInputManager.AssignWindowEventInterface( eventInterface );
-}
-void WaylandManager::GetWaylandInterfaces()
-{
- // get and listen to the registry
- WlRegistry* registry = wl_display_get_registry( mDisplay );
-
- wl_registry_add_listener( registry, &RegistryListener, this);
-
- // adaptor wants the DPI instantly, so we have wait for the data
- while( !mCompositorOutput.DataReady() )
- {
- // This is the first and last time we use wl_display_roundtrip as its not thread safe
- // however at this point we haven't started rendering it is safe.
- wl_display_flush( mDisplay );
- wl_display_roundtrip( mDisplay );
- }
- wl_registry_destroy( registry );
-
-}
-
-void WaylandManager::InstallFileDescriptorMonitor()
-{
- // get the file descriptor
- mDisplayFileDescriptor = wl_display_get_fd( mDisplay );
-
- // create the callback that gets triggered when a read / write event occurs
- CallbackBase* callback = MakeCallback( this, &WaylandManager::FileDescriptorCallback);
-
- // monitor read and write events
- int events = FileDescriptorMonitor::FD_READABLE;
-
- mFileDescriptorMonitor = new FileDescriptorMonitor( mDisplayFileDescriptor, callback, events );
-
-}
-
-void WaylandManager::FileDescriptorCallback( FileDescriptorMonitor::EventType eventTypeMask )
-{
- if( eventTypeMask & FileDescriptorMonitor::FD_READABLE )
- {
- // read and dispatch events
- ReadAndDispatchEvents();
- }
-}
-
-
-void WaylandManager::CreateSurface( Dali::Wayland::Window& window )
-{
- // Create the surface
- // A Wayland surface is a rectangular area that is displayed on the screen.
- // It has a location, size and pixel contents.
-
- mSurface = wl_compositor_create_surface( mCompositor );
-
- // the Input panel (Virtual keyboard ) needs to know which surface it should display on.
- mInputManager.AssignSurface( mSurface );
-
- DALI_ASSERT_ALWAYS( mSurface && "wl_compositor_create_surface failed" );
-
- // keep track of the surface id
- window.mSurfaceId = wl_proxy_get_id( reinterpret_cast<struct wl_proxy *>( mSurface ));
-
- // A surface in Wayland needs to be assigned a role.
- // This gives the surface the role of a shell surface.
- // It allows the surface to be treated like a toplevel, fullscreen or popup window.
- // which can be moved, resize or maximized and have associate metadata like title and class.
- // Try the xdg shell first. XDG is a designed to create a desktop shell with features like minimise etc.
- if( mXdgShell )
- {
- mXdgSurface = xdg_shell_get_xdg_surface( mXdgShell, mSurface );
-
- DALI_ASSERT_ALWAYS( mXdgSurface&& "xdg_shell_get_xdg_surface failed" );
-
- if( window.mTitle.length() )
- {
- xdg_surface_set_title( mXdgSurface, window.mTitle.c_str() );
- xdg_surface_set_app_id(mXdgSurface, window.mTitle.c_str() );
- }
- xdg_shell_add_listener( mXdgShell, &XdgShellListener, 0);
- }
- else
- {
- // try the generic Wayland Shell
- mShellSurface = wl_shell_get_shell_surface( mShell, mSurface );
- DALI_ASSERT_ALWAYS( mShellSurface && "wl_shell_get_shell_surface failed" );
-
- if( window.mTitle.length() )
- {
- wl_shell_surface_set_title( mShellSurface, window.mTitle.c_str() );
- }
-
- wl_shell_surface_set_toplevel( mShellSurface);
-
- wl_shell_surface_add_listener( mShellSurface , &ShellSurfaceListener, 0);
- }
-
- wl_display_flush( mDisplay );
-
-}
-
-WlSurface* WaylandManager::GetSurface()
-{
- return mSurface;
-}
-
-}
-}
-}
+++ /dev/null
-#ifndef __DALI_WAYLAND_MANAGER_H__
-#define __DALI_WAYLAND_MANAGER_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <wayland-extension/xdg-shell-client-protocol.h> // from wayland
-
-// INTERNAL INCLUDES
-#include <wl-types.h>
-#include <file-descriptor-monitor.h>
-#include "input-manager.h"
-#include "wayland-window.h"
-#include "compositor-output-region/compositor-output.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-
-
-class WindowEventInterface;
-class PerformanceInterface;
-
-/**
- * Client used to talk to Wayland server over a UNIX domain stream socket.
- *
- * Brief overview of Wayland:
- *
- * Transport mechanism = Socket
- * Display = handles all the data sent from and to the compositor
- * Display has a file descriptor that can be monitored for read / write events
- *
- * wl client function calls will place messages in a queue
- * Calling wl_display_flush() will flush the messages to the server
- *
- * Incoming data is handled in two steps: queueing and dispatching.
- * In the queue step, the data coming from the display fd is interpreted and
- * added to a queue. On the dispatch step, the handler for the incoming event is called.
- *
- * This class uses the Wayland thread safe API's because the TPL (Tizen Platform Layer) will
- * be communicating with the Wayland compositor at the same time in the DALi render thread.
- *
- *
- */
-class WaylandManager
-{
-
-public:
-
- /**
- * @brief Constructor
- */
- WaylandManager();
-
- /**
- * @brief Destructor
- */
- ~WaylandManager();
-
- /**
- * @brief Connect to Wayland server and setup internal data structures
- */
- void Initialise();
-
- /**
- * @brief Assign window event interface.
- * @param[in] eventInterface window event interface
- */
- void AssignWindowEventInterface( WindowEventInterface* eventInterface);
-
- /**
- * @brief create a surface for a window
- * @param[in] window window object
- */
- void CreateSurface( Dali::Wayland::Window& window );
-
- /**
- * @brief get the wayland surface
- * @return surface
- */
- WlSurface* GetSurface();
-
-private: // change to private
-
- /**
- * @brief Install file descriptor monitor
- */
- void InstallFileDescriptorMonitor();
-
- /**
- * @brief File descriptor callback function, triggered when wayland compositor
- * sends an event to the client (us)
- * @param[in] eventTypeMask
- */
- void FileDescriptorCallback( FileDescriptorMonitor::EventType eventTypeMask );
-
- /**
- * @brief Reads and dispatches any events from the Wayland compositor
- * We have a file descriptor monitor active to decide when to call this function
- */
- void ReadAndDispatchEvents();
-
- /**
- * @brief helper to get wayland interfaces
- */
- void GetWaylandInterfaces();
-
-public:
-
-
- InputManager mInputManager;
- CompositorOutput mCompositorOutput; ///< handles monitor information and DPI
- WlDisplay* mDisplay; ///< Wayland display, handles all the data sent from and to the compositor
- WlShell* mShell; ///< shell
- WlCompositor* mCompositor; ///< compositor
- int mDisplayFileDescriptor; ///< File descriptor used by wayland client socket
- FileDescriptorMonitor* mFileDescriptorMonitor; ///< File descriptor monitor
- WlXdgShell* mXdgShell; ///< XDG Shell
- WlSurface* mSurface; ///< Wayland surface
- WlShellSurface* mShellSurface; ///< Shell surface
- WlXdgShellSurface* mXdgSurface; ///< XDG Shell surface
-
-
-};
-} // Internal
-} // Adaptor
-} // Dali
-
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "wayland-window.h"
-
-namespace Dali
-{
-
-namespace Wayland
-{
-
-Window::Window()
-:mSurfaceId( 0 )
-{
-
-}
-
-Window::~Window()
-{
-}
-
-
-} // namespace Wayland
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_WAYLAND_WINDOW_H__
-#define __DALI_WAYLAND_WINDOW_H__
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/math/rect.h>
-#include <string>
-
-namespace Dali
-{
-
-typedef Dali::Rect<int> PositionSize;
-
-namespace Wayland
-{
-
-/**
- * @brief Ecapsulates data for a wayland window.
- */
-class Window
-{
- public:
-
- /**
- * @brief constructor
- */
- Window();
-
- /**
- * @brief destructor. Non-virtual not intended as a base class.
- */
- ~Window();
-
-private:
-
- // @brief Undefined copy constructor.
- Window( const Window& );
-
- // @brief Undefined assignment operator.
- Window& operator=( const Window& );
-
-public:
-
- std::string mTitle; ///< Window title
- PositionSize mPosition; ///< Position
- int mSurfaceId; ///< wayland surface id
-
-};
-
-
-} // namespace Wayland
-
-} // namespace Dali
-
-#endif // __DALI_WAYLAND_WINDOW_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "window-impl.h"
-
-// EXTERNAL HEADERS
-#include <dali/integration-api/core.h>
-#include <dali/integration-api/system-overlay.h>
-#include <dali/public-api/render-tasks/render-task.h>
-#include <dali/public-api/render-tasks/render-task-list.h>
-#include <orientation.h>
-
-// INTERNAL HEADERS
-#include "render-surface/render-surface-wl.h"
-#include <drag-and-drop-detector-impl.h>
-#include <window-visibility-observer.h>
-#include <orientation-impl.h>
-
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_WINDOW");
-#endif
-
-struct Window::EventHandler
-{
- // place holder
-};
-
-Window* Window::New( const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent )
-{
- Window* window = new Window();
- window->mIsTransparent = isTransparent;
- window->Initialize( positionSize, name, className );
- return window;
-}
-
-void Window::SetAdaptor(Dali::Adaptor& adaptor)
-{
- DALI_ASSERT_ALWAYS( !mStarted && "Adaptor already started" );
- mStarted = true;
-
- // Only create one overlay per window
- Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor);
- Integration::Core& core = adaptorImpl.GetCore();
- mOverlay = &core.GetSystemOverlay();
-
- Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
- taskList.CreateTask();
-
- mAdaptor = &adaptorImpl;
- mAdaptor->AddObserver( *this );
-
- // Can only create the detector when we know the Core has been instantiated.
- mDragAndDropDetector = DragAndDropDetector::New();
- mAdaptor->SetDragAndDropDetector( &GetImplementation( mDragAndDropDetector ) );
-
-
-}
-
-RenderSurface* Window::GetSurface()
-{
- return mSurface;
-}
-
-void Window::ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode )
-{
-
-}
-
-void Window::RotateIndicator(Dali::Window::WindowOrientation orientation)
-{
-}
-
-void Window::SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacityMode )
-{
-}
-
-void Window::SetClass(std::string name, std::string klass)
-{
-}
-
-Window::Window()
-: mSurface( NULL ),
- mIndicatorVisible( Dali::Window::VISIBLE ),
- mIndicatorIsShown( false ),
- mShowRotatedIndicatorOnClose( false ),
- mStarted( false ),
- mIsTransparent( false ),
- mWMRotationAppSet( false ),
- mIsFocusAcceptable( true ),
- mVisible( true ),
- mIconified( false ),
- mOpaqueState( false ),
- mResizeEnabled( true ),
- mIndicator( NULL ),
- mIndicatorOrientation( Dali::Window::PORTRAIT ),
- mNextIndicatorOrientation( Dali::Window::PORTRAIT ),
- mIndicatorOpacityMode( Dali::Window::OPAQUE ),
- mOverlay( NULL ),
- mAdaptor( NULL ),
- mType( Dali::Window::NORMAL ),
- mPreferredOrientation( Dali::Window::PORTRAIT ),
- mSupportedAuxiliaryHints(),
- mAuxiliaryHints(),
- mIndicatorVisibilityChangedSignal(),
- mFocusChangedSignal(),
- mResizedSignal(),
- mDeleteRequestSignal()
-{
- mEventHandler = NULL;
-}
-
-Window::~Window()
-{
- delete mEventHandler;
-
- if ( mAdaptor )
- {
- mAdaptor->RemoveObserver( *this );
- mAdaptor->SetDragAndDropDetector( NULL );
- mAdaptor = NULL;
- }
-
- delete mSurface;
-}
-
-void Window::Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className)
-{
- // create an Wayland window by default
- Any surface;
- Wayland::RenderSurface* windowSurface = new Wayland::RenderSurface( positionSize, surface, name, mIsTransparent );
-
- mSurface = windowSurface;
-
- mOrientation = Orientation::New(this);
-}
-
-void Window::DoShowIndicator( Dali::Window::WindowOrientation lastOrientation )
-{
-
-}
-
-void Window::DoRotateIndicator( Dali::Window::WindowOrientation orientation )
-{
-
-}
-
-void Window::SetIndicatorProperties( bool isShow, Dali::Window::WindowOrientation lastOrientation )
-{
-}
-
-void Window::IndicatorTypeChanged(IndicatorInterface::Type type)
-{
-}
-
-void Window::IndicatorClosed( IndicatorInterface* indicator )
-{
-
-}
-
-void Window::IndicatorVisibilityChanged(bool isVisible)
-{
-
-}
-
-void Window::SetIndicatorActorRotation()
-{
-
-}
-
-void Window::Raise()
-{
-}
-
-void Window::Lower()
-{
-}
-
-void Window::Activate()
-{
-}
-
-Dali::DragAndDropDetector Window::GetDragAndDropDetector() const
-{
- return mDragAndDropDetector;
-}
-
-Dali::Any Window::GetNativeHandle() const
-{
- Wayland::RenderSurface* surface = static_cast< Wayland::RenderSurface* >( mSurface );
-
- return surface->GetWindow();
-}
-
-void Window::OnStart()
-{
-}
-
-void Window::OnPause()
-{
-}
-
-void Window::OnResume()
-{
-}
-
-void Window::OnStop()
-{
-}
-
-void Window::OnDestroy()
-{
- mAdaptor = NULL;
-}
-
-void Window::AddAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- bool found = false;
-
- for( std::size_t i=0; i<mAvailableOrientations.size(); i++ )
- {
- if(mAvailableOrientations[i] == orientation)
- {
- found = true;
- break;
- }
- }
-
- if( ! found )
- {
- mAvailableOrientations.push_back(orientation);
- SetAvailableOrientations( mAvailableOrientations );
- }
-}
-
-void Window::RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- for( std::vector<Dali::Window::WindowOrientation>::iterator iter = mAvailableOrientations.begin();
- iter != mAvailableOrientations.end(); ++iter )
- {
- if( *iter == orientation )
- {
- mAvailableOrientations.erase( iter );
- break;
- }
- }
- SetAvailableOrientations( mAvailableOrientations );
-}
-
-void Window::SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations)
-{
- DALI_ASSERT_ALWAYS( mAvailableOrientations.size() <= 4 && "Incorrect number of available orientations" );
-}
-
-const std::vector<Dali::Window::WindowOrientation>& Window::GetAvailableOrientations()
-{
- return mAvailableOrientations;
-}
-
-void Window::SetPreferredOrientation(Dali::Window::WindowOrientation orientation)
-{
- mPreferredOrientation = orientation;
-}
-
-Dali::Window::WindowOrientation Window::GetPreferredOrientation()
-{
- return mPreferredOrientation;
-}
-
-void Window::SetAcceptFocus( bool accept )
-{
- mIsFocusAcceptable = accept;
-}
-
-bool Window::IsFocusAcceptable() const
-{
- return mIsFocusAcceptable;
-}
-
-void Window::Show()
-{
- mVisible = true;
-}
-
-void Window::Hide()
-{
- mVisible = false;
-}
-
-bool Window::IsVisible() const
-{
- return mVisible;
-}
-
-
-void Window::RotationDone( int orientation, int width, int height )
-{
-}
-
-void Window::SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode )
-{
- mIndicatorVisible = mode;
-}
-
-unsigned int Window::GetSupportedAuxiliaryHintCount() const
-{
- return 0;
-}
-
-std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
-{
- return std::string();
-}
-
-unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
-{
- return -1;
-}
-
-bool Window::RemoveAuxiliaryHint( unsigned int id )
-{
- return false;
-}
-
-bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
-{
- return false;
-}
-
-std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
-{
- return std::string();
-}
-
-unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
-{
- return -1;
-}
-
-void Window::SetInputRegion( const Rect< int >& inputRegion )
-{
-}
-
-void Window::SetType( Dali::Window::Type type )
-{
- mType = type;
-}
-
-Dali::Window::Type Window::GetType() const
-{
- return mType;
-}
-
-bool Window::SetNotificationLevel( Dali::Window::NotificationLevel::Type level )
-{
- return false;
-}
-
-Dali::Window::NotificationLevel::Type Window::GetNotificationLevel() const
-{
- return Dali::Window::NotificationLevel::NONE;
-}
-
-void Window::SetOpaqueState( bool opaque )
-{
- mOpaqueState = opaque;
-}
-
-bool Window::IsOpaqueState() const
-{
- return mOpaqueState;
-}
-
-bool Window::SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode)
-{
- return false;
-}
-
-Dali::Window::ScreenOffMode::Type Window::GetScreenOffMode() const
-{
- return Dali::Window::ScreenOffMode::TIMEOUT;
-}
-
-bool Window::SetBrightness( int brightness )
-{
- return false;
-}
-
-int Window::GetBrightness() const
-{
- return 0;
-}
-
-void Window::SetSize( Dali::Window::WindowSize size )
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.width != size.GetWidth() || positionSize.height != size.GetHeight() )
- {
- positionSize.width = size.GetWidth();
- positionSize.height = size.GetHeight();
-
- mSurface->MoveResize( positionSize );
-
- mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
-
- // Emit signal
- mResizedSignal.Emit( Dali::Window::WindowSize( positionSize.width, positionSize.height ) );
-
- mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- }
-}
-
-Dali::Window::WindowSize Window::GetSize() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowSize( positionSize.width, positionSize.height );
-}
-
-void Window::SetPosition( Dali::Window::WindowPosition position )
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.x != position.GetX() || positionSize.y != position.GetY() )
- {
- positionSize.x = position.GetX();
- positionSize.y = position.GetY();
-
- mSurface->MoveResize( positionSize );
- }
-}
-
-Dali::Window::WindowPosition Window::GetPosition() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowPosition( positionSize.x, positionSize.y );
-}
-
-void Window::SetTransparency( bool transparent )
-{
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-# wearable profile public files
-
-adaptor_internal_wearable_profile_src_files = \
- $(adaptor_wearable_dir)/watch-application-impl.cpp \
- $(adaptor_wearable_dir)/watch/watch-application.cpp \
- $(adaptor_wearable_dir)/watch/watch-time.cpp \
- $(adaptor_wearable_dir)/capture/capture.cpp
-
-adaptor_dali_wearable_header_file = \
- $(adaptor_wearable_dir)/dali-wearable.h
-
-public_dali_watch_header_files = \
- $(adaptor_wearable_dir)/watch/watch-application.h \
- $(adaptor_wearable_dir)/watch/watch-time.h
-
-public_dali_capture_header_files = \
- $(adaptor_wearable_dir)/capture/capture.h
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "watch-application-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-WatchApplicationPtr WatchApplication::New(
- int* argc,
- char **argv[],
- const std::string& stylesheet,
- Dali::WatchApplication::WINDOW_MODE windowMode)
-{
- WatchApplicationPtr watch ( new WatchApplication (argc, argv, stylesheet, windowMode ) );
- return watch;
-}
-
-WatchApplication::WatchApplication( int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode )
-: Application(argc, argv, stylesheet, windowMode, PositionSize(), Framework::WATCH)
-{
-}
-
-WatchApplication::~WatchApplication()
-{
-}
-
-void WatchApplication::OnInit()
-{
- Application::OnInit();
-
- Dali::Adaptor::Get().SetRenderRefreshRate( 2 ); // make 30 fps for watch applications
-
- mState = INITIALIZED;
-}
-
-void WatchApplication::OnTerminate()
-{
- Application::OnTerminate();
-
- mState = TERMINATED;
-}
-
-void WatchApplication::OnResume()
-{
- Application::OnResume();
-
- mState = RESUMED;
-}
-
-void WatchApplication::OnPause()
-{
- Application::OnPause();
-
- mState = PAUSED;
-}
-
-void WatchApplication::OnTimeTick(WatchTime& time)
-{
- Dali::WatchApplication watch(this);
- mTickSignal.Emit( watch, time );
-
- if(mState == PAUSED)
- {
- // This is a pre-resume scenario. All rendering engine of tizen SHOULD forcely update once at this time.
- Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() ).RequestUpdateOnce();
- }
-
- // A watch application will queue messages to update the UI in the signal emitted above
- // Process these immediately to avoid a blinking issue where the old time is briefly visible
- CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() );
- eventInterface.ProcessCoreEvents();
-}
-
-void WatchApplication::OnAmbientTick(WatchTime& time)
-{
- Dali::WatchApplication watch(this);
- mAmbientTickSignal.Emit( watch, time );
-
- // A watch application will queue messages to update the UI in the signal emitted above
- // Process these immediately to avoid a blinking issue where the old time is briefly visible
- CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() );
- eventInterface.ProcessCoreEvents();
-}
-
-void WatchApplication::OnAmbientChanged(bool ambient)
-{
- Dali::WatchApplication watch(this);
- mAmbientChangeSignal.Emit( watch, ambient );
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_WATCH_APPLICATION_H__
-#define __DALI_INTERNAL_WATCH_APPLICATION_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <wearable/watch/watch-application.h>
-#include <application-impl.h>
-
-namespace Dali
-{
-class Adaptor;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-class WatchApplication;
-typedef IntrusivePtr<WatchApplication> WatchApplicationPtr;
-
-enum WatchApplicationState
-{
- INITIALIZED,
- PAUSED,
- RESUMED = INITIALIZED,
- TERMINATED
-};
-
-/**
- * Implementation of the WatchApplication class.
- */
-class WatchApplication : public Application
-{
-public:
- typedef Dali::WatchApplication::WatchTimeSignal WatchTimeSignal;
- typedef Dali::WatchApplication::WatchBoolSignal WatchBoolSignal;
-
- /**
- * Create a new watch
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE
- */
- static WatchApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
-
- /**
- * Private Constructor
- * @param[in] argc A pointer to the number of arguments
- * @param[in] argv A pointer to the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE
- */
- WatchApplication( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
-
- /**
- * Destructor
- */
- virtual ~WatchApplication();
-
- /**
- * Called when the framework is initialised.
- */
- virtual void OnInit();
-
- /**
- * Called when the framework is terminated.
- */
- virtual void OnTerminate();
-
- /**
- * Called when the framework is paused.
- */
- virtual void OnPause();
-
- /**
- * Called when the framework resumes from a paused state.
- */
- virtual void OnResume();
-
- /**
- * Called every second
- */
- void OnTimeTick(WatchTime& time);
-
- /**
- * Called every second in ambient mode
- */
- void OnAmbientTick(WatchTime& time);
-
- /**
- * Called when the device enters or exits ambient mode
- */
- void OnAmbientChanged(bool ambient);
-
-private:
-
- // @brief Undefined copy constructor.
- WatchApplication( const WatchApplication& );
-
- // @brief Undefined assignment operator.
- WatchApplication& operator=( const WatchApplication& );
-
-public:
-
- // Signals
- WatchTimeSignal mTickSignal;
- WatchTimeSignal mAmbientTickSignal;
- WatchBoolSignal mAmbientChangeSignal;
-
-private:
- WatchApplicationState mState;
-};
-
-inline WatchApplication& GetImplementation(Dali::WatchApplication& watch)
-{
- DALI_ASSERT_ALWAYS(watch && "watch handle is empty");
-
- BaseObject& handle = watch.GetBaseObject();
-
- return static_cast<Internal::Adaptor::WatchApplication&>(handle);
-}
-
-inline const WatchApplication& GetImplementation(const Dali::WatchApplication& watch)
-{
- DALI_ASSERT_ALWAYS(watch && "Time handle is empty");
-
- const BaseObject& handle = watch.GetBaseObject();
-
- return static_cast<const Internal::Adaptor::WatchApplication&>(handle);
-}
-
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_WATCH_APPLICATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "watch-application.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <wearable/watch-application-impl.h>
-
-namespace Dali
-{
-
-WatchApplication WatchApplication::New()
-{
- return New( NULL, NULL );
-}
-
-WatchApplication WatchApplication::New( int* argc, char **argv[] )
-{
- Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, "", OPAQUE );
- return WatchApplication(internal.Get());
-}
-
-WatchApplication WatchApplication::New( int* argc, char **argv[], const std::string& stylesheet )
-{
- Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, stylesheet, OPAQUE );
- return WatchApplication(internal.Get());
-}
-
-WatchApplication::~WatchApplication()
-{
-}
-
-WatchApplication::WatchApplication()
-{
-}
-
-WatchApplication::WatchApplication(const WatchApplication& implementation)
-: Application(implementation)
-{
-}
-
-WatchApplication& WatchApplication::operator=(const WatchApplication& application)
-{
- if( *this != application )
- {
- BaseHandle::operator=( application );
- }
- return *this;
-}
-
-WatchApplication::WatchTimeSignal& WatchApplication::TimeTickSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).mTickSignal;
-}
-
-WatchApplication::WatchTimeSignal& WatchApplication::AmbientTickSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).mAmbientTickSignal;
-}
-
-WatchApplication::WatchBoolSignal& WatchApplication::AmbientChangedSignal()
-{
- return Internal::Adaptor::GetImplementation(*this).mAmbientChangeSignal;
-}
-
-WatchApplication::WatchApplication(Internal::Adaptor::WatchApplication* implementation)
-: Application(implementation)
-{
-}
-
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_WATCH_APPLICATION_H__
-#define __DALI_WATCH_APPLICATION_H__
-
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-#include <dali/public-api/object/base-handle.h>
-#include <dali/public-api/signals/callback.h>
-
-// INTERNAL INCLUDES
-#include <public-api/adaptor-framework/application.h>
-#include "watch-time.h"
-
-namespace Dali
-{
-/**
- * @addtogroup dali_adaptor_framework
- * @{
- */
-namespace Internal DALI_INTERNAL
-{
-namespace Adaptor
-{
-class WatchApplication;
-}
-}
-
-/**
- * @brief A WatchApplication class object should be created by every watch application
- * that wishes to use Dali.
- *
- * It provides a means for initialising the resources required by the Dali::Core.
- * Like Application class, the WatchApplication class manages Tizen watch application life cycle.
- *
- * The WatchApplication class emits additional signals which are availalble only in the watch application
- * (TimeTick, AmbientTick, AmbientChanged)
- *
- * This feature is supported in wearable applications only.
- *
- * WatchApplication should follow the example below:
- *
- * @code
- * class ExampleController: public ConnectionTracker
- * {
- * public:
- * ExampleController( WatchApplication& application )
- * : mApplication( application )
- * {
- * mApplication.InitSignal().Connect( this, &ExampleController::Create );
- * }
- *
- * void Create( Application& application )
- * {
- * // Create Dali components...
- * }
- * ...
- * private:
- * WatchApplication& mApplication;
- * };
- *
- * int DALI_EXPORT_API main (int argc, char **argv)
- * {
- * WatchApplication app = WatchApplication::New(&argc, &argv);
- * ExampleController example( app );
- * app.MainLoop();
- * }
- * @endcode
- *
- * If required, you can also connect class member functions to a signal:
- *
- * @code
- * MyApplication app;
- * app.ResumeSignal().Connect(&app, &MyApplication::Resume);
- * @endcode
- *
- * When the above options are found, they are stripped from argv, and argc is updated appropriately.
- * @SINCE_1_1.37
- */
-
-class DALI_IMPORT_API WatchApplication : public Application
-{
-public:
- typedef Signal< void (Application&, const WatchTime&) > WatchTimeSignal; ///< Watch pointer signal callback type @SINCE_1_1.37
- typedef Signal< void (Application&, bool) > WatchBoolSignal; ///< Watch bool signal callback type @SINCE_1_1.37
-
-public:
-
- /**
- * @brief This is the constructor for applications without an argument list.
- * @SINCE_1_1.37
- * @return A handle to the WatchApplication
- */
- static WatchApplication New();
-
- /**
- * @brief This is the constructor for applications.
- *
- * @SINCE_1_1.37
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer the the argument list
- * @return A handle to the WatchApplication
- */
- static WatchApplication New( int* argc, char **argv[] );
-
- /**
- * @brief This is the constructor for applications with a name
- *
- * @SINCE_1_1.37
- * @param[in,out] argc A pointer to the number of arguments
- * @param[in,out] argv A pointer the the argument list
- * @param[in] stylesheet The path to user defined theme file
- * @return A handle to the WatchApplication
- */
- static WatchApplication New( int* argc, char **argv[], const std::string& stylesheet );
-
- /**
- * @brief Construct an empty handle
- * @SINCE_1_1.37
- */
- WatchApplication();
-
- /**
- * @brief Copy Constructor
- * @SINCE_1_1.37
- * @param[in] implementation The WatchApplication implementation
- */
- WatchApplication( const WatchApplication& implementation );
-
- /**
- * @brief Assignment operator
- * @SINCE_1_1.37
- * @param[in] application Handle to an object
- * @return A reference to this
- */
- WatchApplication& operator=( const WatchApplication& application );
-
- /**
- * @brief Destructor
- *
- * This is non-virtual since derived Handle types must not contain data or virtual methods.
- * @SINCE_1_1.37
- */
- ~WatchApplication();
-
-public:
- /**
- * @brief This signal is emitted at every second
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(Application& application, const WatchTime& time);
- * @endcode
- * time(watch time handle) will not be available after returning this callback. It will be freed by the framework.
- * @SINCE_1_1.37
- * @return The signal to connect to
- */
- WatchTimeSignal& TimeTickSignal();
-
- /**
- * @brief This signal is emitted at each minute in ambient mode
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(Application& application, const WatchTime& time);
- * @endcode
- * time(watch time handle) will not be available after returning this callback. It will be freed by the framework.
- * @SINCE_1_1.37
- * @remarks http://tizen.org/privilege/alarm.set privilege is needed to receive ambient ticks at each minute.
- * The AmbientTickSignal() will be ignored if your app doesn't have the privilege
- * @return The signal to connect to
- */
- WatchTimeSignal& AmbientTickSignal();
-
- /**
- * @brief This signal is emitted when the device enters or exits ambient mode
- * A callback of the following type may be connected:
- * @code
- * void YourCallbackName(Application& application, bool ambient);
- * @endcode
- * ambient_mode If true the device enters the ambient mode, otherwise false
- * @SINCE_1_1.37
- * @return The signal to connect to
- */
- WatchBoolSignal& AmbientChangedSignal();
-
-public: // Not intended for application developers
- /// @cond internal
- /**
- * @brief Internal constructor
- * @SINCE_1_1.37
- */
- explicit DALI_INTERNAL WatchApplication(Internal::Adaptor::WatchApplication* implementation);
- /// @endcond
-};
-
-/**
- * @}
- */
-} // namespace Dali
-
-#endif // __DALI_WATCH_APPLICATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <wearable/watch/watch-time.h>
-
-// EXTERNAL INCLUDES
-#ifdef APPCORE_WATCH_AVAILABLE
-#include <watch_app.h>
-#include <watch_app_extension.h>
-#endif
-
-namespace Dali
-{
-
-struct WatchTime::Impl
-{
- Impl(void *time_handle)
- : mTimeHandle(time_handle)
- {
- }
-
- void *mTimeHandle;
-};
-
-WatchTime::WatchTime(void *time_handle)
-{
- mImpl = new Impl(time_handle);
-}
-
-WatchTime::~WatchTime()
-{
- if( mImpl )
- {
- delete mImpl;
- mImpl = NULL;
- }
-}
-
-#ifdef APPCORE_WATCH_AVAILABLE
-
-WatchTime::WatchTime()
-{
- watch_time_h watch_time = {0,};
-
- watch_time_get_current_time(&watch_time);
- mImpl = new Impl(watch_time);
-}
-
-int WatchTime::GetHour() const
-{
- int hour;
-
- watch_time_get_hour(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &hour);
- return hour;
-}
-
-int WatchTime::GetHour24() const
-{
- int hour24;
-
- watch_time_get_hour24(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &hour24);
- return hour24;
-}
-
-int WatchTime::GetMinute() const
-{
- int minute;
-
- watch_time_get_minute(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &minute);
- return minute;
-}
-
-int WatchTime::GetSecond() const
-{
- int second;
-
- watch_time_get_second(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &second);
- return second;
-}
-
-int WatchTime::GetMillisecond() const
-{
- int millisecond;
-
- watch_time_get_millisecond(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &millisecond);
- return millisecond;
-}
-
-int WatchTime::GetYear() const
-{
- int year;
-
- watch_time_get_year(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &year);
- return year;
-}
-
-int WatchTime::GetMonth() const
-{
- int month;
-
- watch_time_get_month(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &month);
- return month;
-}
-
-int WatchTime::GetDay() const
-{
- int day;
-
- watch_time_get_day(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &day);
- return day;
-}
-
-int WatchTime::GetDayOfWeek() const
-{
- int dayOfWeek;
-
- watch_time_get_day_of_week(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &dayOfWeek);
- return dayOfWeek;
-}
-
-struct tm WatchTime::GetUtcTime() const
-{
- struct tm UtcTime;
-
- watch_time_get_utc_time(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &UtcTime);
- return UtcTime;
-}
-
-time_t WatchTime::GetUtcTimeStamp() const
-{
- time_t UtcTimeStamp;
-
- watch_time_get_utc_timestamp(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &UtcTimeStamp);
- return UtcTimeStamp;
-}
-
-const char* WatchTime::GetTimeZone() const
-{
- char* timeZone;
-
- watch_time_get_time_zone(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &timeZone);
- return timeZone;
-}
-
-bool WatchTime::GetDaylightSavingTimeStatus() const
-{
- bool daylight;
-
- watch_time_get_daylight_time_status(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &daylight);
- return daylight;
-}
-
-#else
-WatchTime::WatchTime()
- :mImpl(NULL)
-{
-}
-
-int WatchTime::GetHour() const
-{
- return 0;
-}
-
-int WatchTime::GetHour24() const
-{
- return 0;
-}
-
-int WatchTime::GetMinute() const
-{
- return 0;
-}
-
-int WatchTime::GetSecond() const
-{
- return 0;
-}
-
-int WatchTime::GetMillisecond() const
-{
- return 0;
-}
-
-int WatchTime::GetYear() const
-{
- return 0;
-}
-
-int WatchTime::GetMonth() const
-{
- return 0;
-}
-
-int WatchTime::GetDay() const
-{
- return 0;
-}
-
-int WatchTime::GetDayOfWeek() const
-{
- return 0;
-}
-
-struct tm WatchTime::GetUtcTime() const
-{
- time_t zero = time(0);
- return *localtime(&zero);
-}
-
-time_t WatchTime::GetUtcTimeStamp() const
-{
- return 0;
-}
-
-const char* WatchTime::GetTimeZone() const
-{
- return 0;
-}
-
-bool WatchTime::GetDaylightSavingTimeStatus() const
-{
- return 0;
-}
-
-#endif
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "clipboard-impl.h"
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-#include <dali/public-api/object/any.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor-impl.h>
-#include <ecore-x-window-interface.h>
-#include <singleton-service-impl.h>
-#include <clipboard-event-notifier-impl.h>
-
-namespace //unnamed namespace
-{
-const char* const CBHM_WINDOW = "CBHM_XWIN";
-const char* const CBHM_MSG = "CBHM_MSG";
-const char* const CBHM_ITEM = "CBHM_ITEM";
-const char* const CBHM_cCOUNT = "CBHM_cCOUNT";
-const char* const CBHM_ERROR = "CBHM_ERROR";
-const char* const SET_ITEM = "SET_ITEM";
-const char* const SHOW = "show0";
-const char* const HIDE = "cbhm_hide";
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Clipboard
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-struct Clipboard::Impl
-{
- Impl( Ecore_X_Window ecoreXwin )
- {
- mApplicationWindow = ecoreXwin;
- }
-
- Ecore_X_Window mApplicationWindow;
-};
-
-Clipboard::Clipboard(Impl* impl)
-: mImpl( impl )
-{
-}
-
-Clipboard::~Clipboard()
-{
- delete mImpl;
-}
-
-Dali::Clipboard Clipboard::Get()
-{
- Dali::Clipboard clipboard;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) );
- if(handle)
- {
- // If so, downcast the handle
- clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) );
- }
- else
- {
- Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
- Any nativewindow = adaptorImpl.GetNativeWindowHandle();
-
- // The Ecore_X_Window needs to use the Clipboard.
- // Only when the render surface is window, we can get the Ecore_X_Window.
- Ecore_X_Window ecoreXwin( AnyCast<Ecore_X_Window>(nativewindow) );
- if (ecoreXwin)
- {
- // If we fail to get Ecore_X_Window, we can't use the Clipboard correctly.
- // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
- // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
- Clipboard::Impl* impl( new Clipboard::Impl( ecoreXwin ) );
- clipboard = Dali::Clipboard( new Clipboard( impl ) );
- service.Register( typeid( clipboard ), clipboard );
- }
- }
- }
-
- return clipboard;
-}
-bool Clipboard::SetItem(const std::string &itemData )
-{
- Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
- Ecore_X_Atom atomCbhmItem = ecore_x_atom_get( CBHM_ITEM );
- Ecore_X_Atom dataType = ECORE_X_ATOM_STRING;
-
- // Set item (property) to send
- ecore_x_window_prop_property_set( cbhmWin, atomCbhmItem, dataType, 8, const_cast<char*>( itemData.c_str() ), itemData.length() + 1 );
- ecore_x_sync();
-
- // Trigger sending of item (property)
- Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
- ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SET_ITEM );
- return true;
-}
-
-/*
- * Request clipboard service to retrieve an item
- */
-void Clipboard::RequestItem()
-{
- int index = 0;
- char sendBuf[20];
- snprintf( sendBuf, 20, "%s%d", CBHM_ITEM, index );
- Ecore_X_Atom xAtomCbhmItem = ecore_x_atom_get( sendBuf );
- Ecore_X_Atom xAtomItemType = 0;
-
- std::string clipboardString( ECore::WindowInterface::GetWindowProperty(xAtomCbhmItem, &xAtomItemType, index ) );
-
- // Only return the text string if the Atom type is text (Do not return a text string/URL for images).
- if( !clipboardString.empty() &&
- ( xAtomItemType == ECORE_X_ATOM_TEXT || xAtomItemType == ECORE_X_ATOM_COMPOUND_TEXT || xAtomItemType == ECORE_X_ATOM_STRING || xAtomItemType == ECORE_X_ATOM_UTF8_STRING ) )
- {
- Ecore_X_Atom xAtomCbhmError = ecore_x_atom_get( CBHM_ERROR );
- if ( xAtomItemType != xAtomCbhmError )
- {
- // Call ClipboardEventNotifier to notify event observe of retrieved string
- Dali::ClipboardEventNotifier clipboardEventNotifier(ClipboardEventNotifier::Get());
- if ( clipboardEventNotifier )
- {
- ClipboardEventNotifier& notifierImpl( ClipboardEventNotifier::GetImplementation( clipboardEventNotifier ) );
-
- notifierImpl.SetContent( clipboardString );
- notifierImpl.EmitContentSelectedSignal();
- }
- }
- }
-}
-
-/*
- * Get number of items in clipboard
- */
-unsigned int Clipboard::NumberOfItems()
-{
- Ecore_X_Atom xAtomCbhmCountGet = ecore_x_atom_get( CBHM_cCOUNT );
-
- std::string ret( ECore::WindowInterface::GetWindowProperty( xAtomCbhmCountGet, NULL, 0 ) );
- int count = 0;
-
- if ( !ret.empty() )
- {
- count = atoi( ret.c_str() );
- }
-
- return count;
-}
-
-/**
- * Show clipboard window
- * Function to send message to show the Clipboard (cbhm) as no direct API available
- * Reference elementary/src/modules/ctxpopup_copypasteUI/cbhm_helper.c
- */
-void Clipboard::ShowClipboard()
-{
- // Claim the ownership of the SECONDARY selection.
- ecore_x_selection_secondary_set(mImpl->mApplicationWindow, "", 1);
- Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
-
- // Launch the clipboard window
- Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
- ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SHOW );
-}
-
-void Clipboard::HideClipboard(bool skipFirstHide)
-{
- Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
- // Launch the clipboard window
- Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
- ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, HIDE );
-
- // release the ownership of SECONDARY selection
- ecore_x_selection_secondary_clear();
-}
-
-bool Clipboard::IsVisible() const
-{
- return false;
-}
-
-char* Clipboard::ExcuteBuffered( bool type, void *event )
-{
- return NULL;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "display-connection-impl.h"
-
-// EXTERNAL_HEADERS
-#include <Ecore_X.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL HEADERS
-#include <pixmap-render-surface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-DisplayConnection* DisplayConnection::New()
-{
- DisplayConnection* pDisplayConnection(new DisplayConnection());
-
- return pDisplayConnection;
-}
-
-DisplayConnection::DisplayConnection()
-: mDisplay(NULL)
-{
-}
-
-DisplayConnection::~DisplayConnection()
-{
- if(mDisplay)
- {
- XCloseDisplay(mDisplay);
- }
-}
-
-Any DisplayConnection::GetDisplay()
-{
- return Any(mDisplay);
-}
-
-void DisplayConnection::ConsumeEvents()
-{
- // check events so that we can flush the queue and avoid any potential memory leaks in X
- // looping if events remain
- int events(0);
- do
- {
- // Check if there are any events in the queue
- events = XEventsQueued(mDisplay, QueuedAfterFlush);
-
- if (events > 0)
- {
- // Just flush event to prevent memory leak from event queue as the events get built up in
- // memory but are only deleted when we retrieve them
- XEvent ev;
- XNextEvent(mDisplay, &ev);
- }
- }
- while (events > 0);
-}
-
-bool DisplayConnection::InitializeEgl(EglInterface& egl)
-{
- EglImplementation& eglImpl = static_cast<EglImplementation&>(egl);
-
- if (!eglImpl.InitializeGles(reinterpret_cast<EGLNativeDisplayType>(mDisplay)))
- {
- DALI_LOG_ERROR("Failed to initialize GLES.\n");
- return false;
- }
-
- return true;
-}
-
-void DisplayConnection::SetSurfaceType( RenderSurface::Type type )
-{
- if( type == RenderSurface::ECORE_RENDER_SURFACE )
- {
- // Because of DDK issue, we need to use separated x display instead of ecore default display
- mDisplay = XOpenDisplay(0);
- }
-}
-
-void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
-{
- // calculate DPI
- float xres, yres;
-
- // 1 inch = 25.4 millimeters
- xres = ecore_x_dpi_get();
- yres = ecore_x_dpi_get();
-
- dpiHorizontal = int(xres + 0.5f); // rounding
- dpiVertical = int(yres + 0.5f);
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_X_DIPLAY_CONNECTION_H__
-#define __DALI_INTERNAL_ECORE_X_DIPLAY_CONNECTION_H__
-
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-#include <ecore-x-types.h>
-
-// INTERNAL INCLUDES
-#include <base/display-connection.h>
-#include <dali/public-api/object/base-object.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-class RenderSurface;
-class DisplayConnection;
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * DisplayConnection implementation
- */
-class DisplayConnection : public Dali::BaseObject
-{
-public:
-
- /**
- * @brief Default constructor
- */
- DisplayConnection();
-
- /**
- * @brief Create an initialized DisplayConnection.
- *
- * @return A handle to a newly allocated DisplayConnection resource.
- */
- static DisplayConnection* New();
-
-public:
-
- /**
- * @copydoc Dali::DisplayConnection::GetDisplay
- */
- Any GetDisplay();
-
- /**
- * @copydoc Dali::DisplayConnection::GetDpi
- */
- static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
-
- /**
- * @copydoc Dali::DisplayConnection::ConsumeEvents
- */
- void ConsumeEvents();
-
- /**
- * @copydoc Dali::DisplayConnection::InitializeEgl
- */
- bool InitializeEgl(EglInterface& egl);
-
- void SetSurfaceType( RenderSurface::Type type );
-
-public:
-
- /**
- * Destructor
- */
- virtual ~DisplayConnection();
-
-protected:
-
- // Undefined
- DisplayConnection(const DisplayConnection&);
-
- // Undefined
- DisplayConnection& operator=(const DisplayConnection& rhs);
-
-private:
- XDisplay* mDisplay; ///< X-display for rendering
-};
-
-} // namespace Adaptor
-
-} // namespace internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ECORE_X_DIPLAY_CONNECTION_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <events/event-handler.h>
-
-// EXTERNAL INCLUDES
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Ecore_Input.h>
-#include <Ecore_X.h>
-
-#include <X11/Xlib.h>
-#include <X11/extensions/XInput2.h>
-#include <X11/extensions/XI2.h>
-
-#include <cstring>
-
-#include <sys/time.h>
-
-#ifndef DALI_PROFILE_UBUNTU
-#include <vconf.h>
-#include <vconf-keys.h>
-#endif // DALI_PROFILE_UBUNTU
-
-#ifdef DALI_ELDBUS_AVAILABLE
-#include <Eldbus.h>
-#endif // DALI_ELDBUS_AVAILABLE
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/events/touch-point.h>
-#include <dali/public-api/events/key-event.h>
-#include <dali/public-api/events/wheel-event.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/events/key-event-integ.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <dali/integration-api/events/hover-event-integ.h>
-#include <dali/integration-api/events/wheel-event-integ.h>
-
-// INTERNAL INCLUDES
-#include <events/gesture-manager.h>
-#include <window-render-surface.h>
-#include <clipboard-impl.h>
-#include <key-impl.h>
-#include <physical-keyboard-impl.h>
-#include <style-monitor-impl.h>
-#include <base/core-event-interface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-#if defined(DEBUG_ENABLED)
-namespace
-{
-Integration::Log::Filter* gTouchEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_TOUCH");
-Integration::Log::Filter* gClientMessageLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_CLIENT_MESSAGE");
-Integration::Log::Filter* gDragAndDropLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DND");
-Integration::Log::Filter* gImfLogging = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_IMF");
-Integration::Log::Filter* gSelectionEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_SELECTION");
-} // unnamed namespace
-#endif
-
-
-namespace
-{
-
-const char * DETENT_DEVICE_NAME = "tizen_detent";
-const std::string DEFAULT_DEVICE_NAME = "";
-const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE;
-const Device::Subclass::Type DEFAULT_DEVICE_SUBCLASS = Device::Subclass::NONE;
-
-// DBUS accessibility
-#define A11Y_BUS "org.a11y.Bus"
-#define A11Y_INTERFACE "org.a11y.Bus"
-#define A11Y_PATH "/org/a11y/bus"
-#define A11Y_GET_ADDRESS "GetAddress"
-#define BUS "com.samsung.EModule"
-#define INTERFACE "com.samsung.GestureNavigation"
-#define PATH "/com/samsung/GestureNavigation"
-#define SIGNAL "GestureDetected"
-
-#ifndef DALI_PROFILE_UBUNTU
-const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced.
-#endif // DALI_PROFILE_UBUNTU
-
-const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 );
-
-#ifndef DALI_PROFILE_UBUNTU
-const char * CLIPBOARD_ATOM = "CBHM_MSG";
-const char * CLIPBOARD_SET_OWNER_MESSAGE = "SET_OWNER";
-#endif // DALI_PROFILE_UBUNTU
-
-/// The atoms required by Ecore for Drag & Drop behaviour.
-Ecore_X_Atom DRAG_AND_DROP_ATOMS[] =
-{
- ECORE_X_ATOM_XDND_ACTION_COPY,
-};
-
-/// The types that we support.
-const char * DRAG_AND_DROP_TYPES[] =
-{
- ECORE_X_SELECTION_TARGET_UTF8_STRING,
-};
-
-const unsigned int DRAG_AND_DROP_ATOMS_NUMBER = sizeof( DRAG_AND_DROP_ATOMS ) / sizeof( Ecore_X_Atom );
-const unsigned int DRAG_AND_DROP_TYPES_NUMBER = sizeof( DRAG_AND_DROP_TYPES ) / sizeof( const char * );
-
-const unsigned int BYTES_PER_CHARACTER_FOR_ATTRIBUTES = 3;
-
-#ifdef DALI_ELDBUS_AVAILABLE
-// DBus gesture string matching lists.
-// TODO: This needs moving to its own module.
-const char * ElDBusAccessibilityFingerCountStrings[] =
-{
- "OneFinger",
- "TwoFingers",
- "ThreeFingers"
-};
-const unsigned int FingerCountStringsTotal = sizeof( ElDBusAccessibilityFingerCountStrings ) / sizeof( ElDBusAccessibilityFingerCountStrings[0] );
-enum GestureType
-{
- GESTURE_TYPE_NONE,
- GESTURE_TYPE_HOVER,
- GESTURE_TYPE_SINGLE_TAP,
- GESTURE_TYPE_DOUBLE_TAP,
- GESTURE_TYPE_TRIPLE_TAP
-};
-struct GestureTypeTable
-{
- const char* name;
- const GestureType type;
-};
-GestureTypeTable ElDBusAccessibilityFullEventTypeStrings[] =
-{
- { "Hover", GESTURE_TYPE_HOVER },
- { "SingleTap", GESTURE_TYPE_SINGLE_TAP },
- { "DoubleTap", GESTURE_TYPE_DOUBLE_TAP },
- { "TripleTap", GESTURE_TYPE_TRIPLE_TAP }
-};
-const unsigned int FullEventTypeStringsTotal = sizeof( ElDBusAccessibilityFullEventTypeStrings ) / sizeof( ElDBusAccessibilityFullEventTypeStrings[0] );
-enum SubGestureType
-{
- SUB_GESTURE_TYPE_NONE,
- SUB_GESTURE_TYPE_FLICK
-};
-struct SubGestureTypeTable
-{
- const char* name;
- const SubGestureType type;
-};
-SubGestureTypeTable ElDBusAccessibilityDirectionalEventTypeStrings[] =
-{
- { "Flick", SUB_GESTURE_TYPE_FLICK }
-};
-const unsigned int DirectionalEventTypeStringsTotal = sizeof( ElDBusAccessibilityDirectionalEventTypeStrings ) / sizeof( ElDBusAccessibilityDirectionalEventTypeStrings[0] );
-enum GestureDirection
-{
- GESTURE_DIRECTION_NONE,
- GESTURE_DIRECTION_UP,
- GESTURE_DIRECTION_DOWN,
- GESTURE_DIRECTION_LEFT,
- GESTURE_DIRECTION_RIGHT,
- GESTURE_DIRECTION_UP_RETURN,
- GESTURE_DIRECTION_DOWN_RETURN,
- GESTURE_DIRECTION_LEFT_RETURN,
- GESTURE_DIRECTION_RIGHT_RETURN
-};
-struct GestureDirectionTable
-{
- const char* name;
- const GestureDirection direction;
-};
-GestureDirectionTable ElDBusAccessibilityDirectionStrings[] =
-{
- { "Up", GESTURE_DIRECTION_UP },
- { "Down", GESTURE_DIRECTION_DOWN },
- { "Left", GESTURE_DIRECTION_LEFT },
- { "Right", GESTURE_DIRECTION_RIGHT },
- { "UpReturn", GESTURE_DIRECTION_UP_RETURN },
- { "DownReturn", GESTURE_DIRECTION_DOWN_RETURN },
- { "LeftReturn", GESTURE_DIRECTION_LEFT_RETURN },
- { "RightReturn", GESTURE_DIRECTION_RIGHT_RETURN }
-};
-const unsigned int DirectionStringsTotal = sizeof( ElDBusAccessibilityDirectionStrings ) / sizeof( ElDBusAccessibilityDirectionStrings[0] );
-#endif // DALI_ELDBUS_AVAILABLE
-
-/**
- * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h.
- * This function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Modifiers enums.
- * @param[in] ecoreModifier the Ecore_Event_Modifier input.
- * @return the Ecore_IMF_Keyboard_Modifiers output.
- */
-Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier)
-{
- int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE.
-
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN;
- }
-
- if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR )
- {
- modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR;
- }
-
- return static_cast<Ecore_IMF_Keyboard_Modifiers>( modifier );
-}
-
-
-// Copied from x server
-static unsigned int GetCurrentMilliSeconds(void)
-{
- struct timeval tv;
-
- struct timespec tp;
- static clockid_t clockid;
-
- if (!clockid)
- {
-#ifdef CLOCK_MONOTONIC_COARSE
- if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 &&
- (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0)
- {
- clockid = CLOCK_MONOTONIC_COARSE;
- }
- else
-#endif
- if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
- {
- clockid = CLOCK_MONOTONIC;
- }
- else
- {
- clockid = ~0L;
- }
- }
- if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
- {
- return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
- }
-
- gettimeofday(&tv, NULL);
- return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
-}
-
-} // unnamed namespace
-
-// Impl to hide EFL implementation.
-struct EventHandler::Impl
-{
- // Construction & Destruction
-
- /**
- * Constructor
- */
- Impl( EventHandler* handler, Ecore_X_Window window )
- : mHandler( handler ),
- mEcoreEventHandler(),
- mWindow( window ),
- mXiDeviceId( 0 )
-#ifdef DALI_ELDBUS_AVAILABLE
- , mSessionConnection( NULL ),
- mA11yConnection( NULL )
-#endif
- {
- // Only register for touch and key events if we have a window
- if ( window != 0 )
- {
- // Register Touch events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_OUT, EcoreEventMouseButtonUp, handler ) ); // process mouse out event like up event
-
- // Register Mouse wheel events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, handler ) );
-
- // Register Key events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, handler ) );
-
- // Register Focus events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_IN, EcoreEventWindowFocusIn, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_OUT, EcoreEventWindowFocusOut, handler ) );
-
- // Register Window damage events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DAMAGE, EcoreEventWindowDamaged, handler ) );
-
- // Enable Drag & Drop and register DnD events
- ecore_x_dnd_aware_set( window, EINA_TRUE );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_ENTER, EcoreEventDndEnter, handler) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_POSITION, EcoreEventDndPosition, handler) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_LEAVE, EcoreEventDndLeave, handler) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_DROP, EcoreEventDndDrop, handler) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_FINISHED, EcoreEventDndFinished, handler) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_STATUS, EcoreEventDndStatus, handler) );
-
- // Register Client message events - accessibility etc.
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, handler ) );
-
- // Register Selection event - clipboard selection, Drag & Drop selection etc.
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_CLEAR, EcoreEventSelectionClear, handler ) );
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_NOTIFY, EcoreEventSelectionNotify, handler ) );
-
- // Initialize Xi2 system
- Display* display = static_cast< Display* >(ecore_x_display_get());
- Ecore_X_Window rootWindow = ecore_x_window_root_first_get();
- int opcode = 0, event = 0, error = 0;
- int major = XI_2_Major;
- int minor = XI_2_Minor;
- int deviceCount = 0;
- XIEventMask xiEventMask;
-
- // Check if X input extension available
- if( XQueryExtension( display, "XInputExtension", &opcode, &event, &error ) )
- {
- // We support version 2.0
- if( XIQueryVersion( display, &major, &minor ) != BadRequest )
- {
- xiEventMask.deviceid = XIAllDevices;
-
- // Check device id
- bool match = false;
- XIDeviceInfo* deviceInfo = NULL;
- deviceInfo = XIQueryDevice( display, XIAllDevices, &deviceCount );
-
- for( int i = 0; i < deviceCount; i++ )
- {
- if( !strncmp( deviceInfo[i].name, DETENT_DEVICE_NAME, strlen( DETENT_DEVICE_NAME ) ) )
- {
- xiEventMask.deviceid = deviceInfo[i].deviceid;
- match = true;
- break;
- }
- }
-
- if( match )
- {
- mXiDeviceId = xiEventMask.deviceid;
-
- // SelectXi2Event
- Dali::Vector< unsigned char > mask;
- std::size_t xiMaskLen = XIMaskLen( XI_LASTEVENT );
- mask.Reserve( xiMaskLen );
- xiEventMask.mask = mask.Begin();
-
- XISetMask( xiEventMask.mask, XI_RawMotion );
-
- xiEventMask.mask_len = xiMaskLen * sizeof( unsigned char );
-
- int ret = XISelectEvents( display, rootWindow, &xiEventMask, 1 );
- if( ret == 0 )
- {
- // Register custom wheel events
- mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_GENERIC, EcoreEventCustomWheel, handler ) );
- }
- else
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to Select Events\n" );
- }
- }
-
- if( deviceInfo != NULL )
- {
- XIFreeDeviceInfo( deviceInfo );
- }
- }
- else
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to query XI Version\n" );
- }
- }
- else
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to query XInputExtension\n" );
- }
-
-#ifndef DALI_PROFILE_UBUNTU
- // Register Vconf notify - font name, font size and style
- vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, handler );
- vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, handler );
-#endif // DALI_PROFILE_UBUNTU
-
-#ifdef DALI_ELDBUS_AVAILABLE
-
- // Initialize ElDBus.
- DALI_LOG_INFO( gImfLogging, Debug::General, "Starting DBus Initialization\n" );
- eldbus_init();
-
- mSessionConnection = eldbus_connection_get( ELDBUS_CONNECTION_TYPE_SESSION );
-
- Eldbus_Object *a11yObject = eldbus_object_get( mSessionConnection, A11Y_BUS, A11Y_PATH );
- Eldbus_Proxy *elDBusManager = eldbus_proxy_get( a11yObject, A11Y_INTERFACE );
-
- // Pass in handler in the cb_data field so we can access the accessibility adaptor within the callback.
- eldbus_proxy_call( elDBusManager, A11Y_GET_ADDRESS, EcoreElDBusInitialisation, handler, -1, "" );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "Finished DBus Initialization\n" );
-
-#endif // DALI_ELDBUS_AVAILABLE
- }
- }
-
- /**
- * Destructor
- */
- ~Impl()
- {
-#ifndef DALI_PROFILE_UBUNTU
- vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged );
- vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged );
-#endif // DALI_PROFILE_UBUNTU
-
- for( std::vector<Ecore_Event_Handler*>::iterator iter = mEcoreEventHandler.begin(), endIter = mEcoreEventHandler.end(); iter != endIter; ++iter )
- {
- ecore_event_handler_del( *iter );
- }
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Close down ElDBus
- if( mA11yConnection )
- {
- eldbus_connection_unref( mA11yConnection );
- }
-
- if( mSessionConnection )
- {
- eldbus_connection_unref( mSessionConnection );
- }
-
- eldbus_shutdown();
-#endif // DALI_ELDBUS_AVAILABLE
- }
-
- // Static methods
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Touch Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a touch down is received.
- */
- static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == handler->mImpl->mWindow )
- {
- PointState::Type state ( PointState::DOWN );
-
- // Check if the buttons field is set and ensure it's the primary touch button.
- // If this event was triggered by buttons other than the primary button (used for touch), then
- // just send an interrupted event to Core.
- if ( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) )
- {
- state = PointState::INTERRUPTED;
- }
-
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( state );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a touch up is received.
- */
- static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == handler->mImpl->mWindow )
- {
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( PointState::UP );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a touch motion is received.
- */
- static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Move *touchEvent( (Ecore_Event_Mouse_Move*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( touchEvent->window == handler->mImpl->mWindow )
- {
- Integration::Point point;
- point.SetDeviceId( touchEvent->multi.device );
- point.SetState( PointState::MOTION );
- point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
- point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
- point.SetPressure( touchEvent->multi.pressure );
- point.SetAngle( Degree( touchEvent->multi.angle ) );
- handler->SendEvent( point, touchEvent->timestamp );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Wheel Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a mouse wheel is received.
- */
- static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event )
- {
- Ecore_Event_Mouse_Wheel *mouseWheelEvent( (Ecore_Event_Mouse_Wheel*)event );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT Ecore_Event_Mouse_Wheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z );
-
- EventHandler* handler( (EventHandler*)data );
- if ( mouseWheelEvent->window == handler->mImpl->mWindow )
- {
- WheelEvent wheelEvent( WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp );
- handler->SendWheelEvent( wheelEvent );
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a custom wheel is received.
- */
- static Eina_Bool EcoreEventCustomWheel( void* data, int type, void* event )
- {
- Ecore_X_Event_Generic *genericEvent( (Ecore_X_Event_Generic*)event );
- EventHandler* handler( (EventHandler*)data );
-
- switch( genericEvent->evtype )
- {
- case XI_RawMotion:
- {
- XIRawEvent* xiRawEvent = static_cast< XIRawEvent* >( genericEvent->data );
- unsigned int timeStamp = 0;
-
- if( xiRawEvent->deviceid != handler->mImpl->mXiDeviceId )
- {
- return ECORE_CALLBACK_PASS_ON;
- }
-
- // X(0): rotate: NOT USED
- // Y(1): timestamp
- // Z(2): direction
-
- double* value = xiRawEvent->raw_values;
-
- if( XIMaskIsSet( xiRawEvent->valuators.mask, 1) )
- {
- timeStamp = static_cast< unsigned int >( *(value + 1) );
- }
-
- if( XIMaskIsSet( xiRawEvent->valuators.mask, 2) )
- {
- // if z == 1, clockwise
- // otherwise counter-clockwise
- int z = static_cast< int >( *(value + 2) );
-
- // In DALi, positive value means clockwise, and negative value means counter-clockwise
- if( z == 0 )
- {
- z = -1;
- }
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventCustomWheel: z: %d\n", z );
-
- WheelEvent wheelEvent( WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2(0.0f, 0.0f), z, timeStamp );
- handler->SendWheelEvent( wheelEvent );
- }
- break;
- }
- default:
- {
- break;
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Key Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a key down is received.
- */
- static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyDown \n" );
-
- EventHandler* handler( (EventHandler*)data );
- Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
- bool eventHandled( false );
-
- // If a device key then skip ecore_imf_context_filter_event.
- if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
- {
- Ecore_IMF_Context* imfContext = NULL;
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
- }
-
- if ( imfContext )
- {
- // We're consuming key down event so we have to pass to IMF so that it can parse it as well.
- Ecore_IMF_Event_Key_Down ecoreKeyDownEvent;
- ecoreKeyDownEvent.keyname = keyEvent->keyname;
- ecoreKeyDownEvent.key = keyEvent->key;
- ecoreKeyDownEvent.string = keyEvent->string;
- ecoreKeyDownEvent.compose = keyEvent->compose;
- ecoreKeyDownEvent.timestamp = keyEvent->timestamp;
- ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
- ecoreKeyDownEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
-#ifdef ECORE_IMF_1_13
- ecoreKeyDownEvent.dev_name = "";
- ecoreKeyDownEvent.dev_class = ECORE_IMF_DEVICE_CLASS_KEYBOARD;
- ecoreKeyDownEvent.dev_subclass = ECORE_IMF_DEVICE_SUBCLASS_NONE;
-#endif // ECORE_IMF_1_13
-
- eventHandled = ecore_imf_context_filter_event( imfContext,
- ECORE_IMF_EVENT_KEY_DOWN,
- (Ecore_IMF_Event *) &ecoreKeyDownEvent );
-
- // If the event has not been handled by IMF then check if we should reset our IMF context
- if( !eventHandled )
- {
- if ( !strcmp( keyEvent->keyname, "Escape" ) ||
- !strcmp( keyEvent->keyname, "Return" ) ||
- !strcmp( keyEvent->keyname, "KP_Enter" ) )
- {
- ecore_imf_context_reset( imfContext );
- }
- }
- }
- }
-
- // If the event wasn't handled then we should send a key event.
- if ( !eventHandled )
- {
- if ( keyEvent->window == handler->mImpl->mWindow )
- {
- std::string keyName( keyEvent->keyname );
- std::string keyString( "" );
- int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
- int modifier( keyEvent->modifiers );
- unsigned long time = keyEvent->timestamp;
-
- // Ensure key event string is not NULL as keys like SHIFT have a null string.
- if ( keyEvent->string )
- {
- keyString = keyEvent->string;
- }
-
- Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Down, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS );
- handler->SendEvent( keyEvent );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a key up is received.
- */
- static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyUp \n" );
-
- EventHandler* handler( (EventHandler*)data );
- Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
- bool eventHandled( false );
-
- // Device keys like Menu, home, back button must skip ecore_imf_context_filter_event.
- if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
- {
- Ecore_IMF_Context* imfContext = NULL;
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
- }
-
- if ( imfContext )
- {
- // We're consuming key up event so we have to pass to IMF so that it can parse it as well.
- Ecore_IMF_Event_Key_Up ecoreKeyUpEvent;
- ecoreKeyUpEvent.keyname = keyEvent->keyname;
- ecoreKeyUpEvent.key = keyEvent->key;
- ecoreKeyUpEvent.string = keyEvent->string;
- ecoreKeyUpEvent.compose = keyEvent->compose;
- ecoreKeyUpEvent.timestamp = keyEvent->timestamp;
- ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
- ecoreKeyUpEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
-#ifdef ECORE_IMF_1_13
- ecoreKeyUpEvent.dev_name = "";
-#endif // ECORE_IMF_1_13
-
- eventHandled = ecore_imf_context_filter_event( imfContext,
- ECORE_IMF_EVENT_KEY_UP,
- (Ecore_IMF_Event *) &ecoreKeyUpEvent );
- }
- }
-
- // If the event wasn't handled then we should send a key event.
- if ( !eventHandled )
- {
- if ( keyEvent->window == handler->mImpl->mWindow )
- {
- std::string keyName( keyEvent->keyname );
- std::string keyString( "" );
- int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
- int modifier( keyEvent->modifiers );
- unsigned long time( keyEvent->timestamp );
-
- // Ensure key event string is not NULL as keys like SHIFT have a null string.
- if ( keyEvent->string )
- {
- keyString = keyEvent->string;
- }
-
- Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Up, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS );
-
- handler->SendEvent( keyEvent );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Window Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when the window gains focus.
- */
- static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
- {
- Ecore_X_Event_Window_Focus_In* focusInEvent( (Ecore_X_Event_Window_Focus_In*)event );
- EventHandler* handler( (EventHandler*)data );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusIn \n" );
-
- // If the window gains focus and we hid the keyboard then show it again.
- if ( focusInEvent->win == handler->mImpl->mWindow )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventWindowFocusIn - >>WindowFocusGained \n" );
-
- if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
- {
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
- if( imfManagerImpl.RestoreAfterFocusLost() )
- {
- imfManagerImpl.Activate();
- }
- }
- }
- // No need to connect callbacks as KeyboardStatusChanged will be called.
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window loses focus.
- */
- static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
- {
- Ecore_X_Event_Window_Focus_Out* focusOutEvent( (Ecore_X_Event_Window_Focus_Out*)event );
- EventHandler* handler( (EventHandler*)data );
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusOut \n" );
-
- // If the window loses focus then hide the keyboard.
- if ( focusOutEvent->win == handler->mImpl->mWindow )
- {
- if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
- {
- Dali::ImfManager imfManager( ImfManager::Get() );
- if ( imfManager )
- {
- ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
- if( imfManagerImpl.RestoreAfterFocusLost() )
- {
- imfManagerImpl.Deactivate();
- }
- }
- }
-
- // Clipboard don't support that whether clipboard is shown or not. Hide clipboard.
- Dali::Clipboard clipboard = Clipboard::Get();
- clipboard.HideClipboard();
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window is damaged.
- */
- static Eina_Bool EcoreEventWindowDamaged(void *data, int type, void *event)
- {
- Ecore_X_Event_Window_Damage* windowDamagedEvent( (Ecore_X_Event_Window_Damage*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if( windowDamagedEvent->win == handler->mImpl->mWindow )
- {
- DamageArea area;
- area.x = windowDamagedEvent->x;
- area.y = windowDamagedEvent->y;
- area.width = windowDamagedEvent->w;
- area.height = windowDamagedEvent->h;
-
- handler->SendEvent( area );
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the window properties are changed.
- * We are only interested in the font change.
- */
-
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Drag & Drop Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Called when a dragged item enters our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndEnter( void* data, int type, void* event )
- {
- DALI_LOG_INFO( gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndEnter\n" );
-
- Ecore_X_Event_Xdnd_Enter* enterEvent( (Ecore_X_Event_Xdnd_Enter*) event );
- EventHandler* handler( (EventHandler*)data );
- Ecore_X_Window window ( handler->mImpl->mWindow );
-
- if ( enterEvent->win == window )
- {
- DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
-
- // Check whether the Drag & Drop detector has Drag & Drop behaviour enabled before we accept.
- if ( dndDetector && dndDetector->IsEnabled() )
- {
- // Tell Ecore that we want to enable drop in the entire window.
- Ecore_X_Rectangle rect;
- rect.x = rect.y = 0;
- ecore_x_window_geometry_get( window, NULL, NULL, (int*)&rect.width, (int*)&rect.height );
-
- // Tell Ecore that we are able to process a drop.
- ecore_x_dnd_send_status( EINA_TRUE, EINA_FALSE, rect, ECORE_X_ATOM_XDND_DROP );
-
- // Register the required atoms and types.
- ecore_x_dnd_actions_set( window, DRAG_AND_DROP_ATOMS, DRAG_AND_DROP_ATOMS_NUMBER );
- ecore_x_dnd_types_set( window, DRAG_AND_DROP_TYPES, DRAG_AND_DROP_TYPES_NUMBER );
-
- // Request to get the content from Ecore.
- ecore_x_selection_xdnd_request( window, ECORE_X_SELECTION_TARGET_UTF8_STRING );
-
- DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndEnter: Requesting Drag & Drop\n" );
-
- // Clear the previous content
- dndDetector->ClearContent();
-
- // Emit the entered signal
- dndDetector->EmitEnteredSignal();
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved within our window.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndPosition( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndPosition\n" );
-
- Ecore_X_Event_Xdnd_Position* positionEvent( (Ecore_X_Event_Xdnd_Position*) event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( positionEvent->win == handler->mImpl->mWindow )
- {
- DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
-
- // If we have a detector then update its latest position.
- if ( dndDetector )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::General, "EcoreEventDndPosition: position ( %d x %d )\n", positionEvent->position.x, positionEvent->position.y );
- dndDetector->SetPosition( Vector2( positionEvent->position.x, positionEvent->position.y ));
- dndDetector->EmitMovedSignal();
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item leaves our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndLeave( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndLeave\n" );
-
- Ecore_X_Event_Xdnd_Leave* leaveEvent( (Ecore_X_Event_Xdnd_Leave*) event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( leaveEvent->win == handler->mImpl->mWindow )
- {
- DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
-
- // If we have a detector then clear its content and emit the exited-signal. Also tell Ecore that we have finished.
- if ( dndDetector )
- {
- dndDetector->ClearContent();
- dndDetector->EmitExitedSignal();
-
- ecore_x_dnd_send_finished();
-
- DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndLeave: Finished\n" );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the dragged item is dropped within our window's bounds.
- * This is when items are dragged INTO our window.
- */
- static Eina_Bool EcoreEventDndDrop( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndDrop\n" );
-
- Ecore_X_Event_Xdnd_Drop* dropEvent ( (Ecore_X_Event_Xdnd_Drop*) event);
- EventHandler* handler( (EventHandler*)data );
-
- if ( dropEvent->win == handler->mImpl->mWindow )
- {
- DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
-
- // Something has been dropped, inform the detector (if we have one) and tell Ecore that we have finished.
- if ( dndDetector )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::General, "EcoreEventDndDrop: position ( %d x %d )\n", dropEvent->position.x, dropEvent->position.y );
-
- dndDetector->SetPosition( Vector2( dropEvent->position.x, dropEvent->position.y ) );
- dndDetector->EmitDroppedSignal();
- ecore_x_dnd_send_finished();
-
- DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndDrop: Finished\n" );
- }
- }
-
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved from our window and the target window has done processing it.
- * This is when items are dragged FROM our window.
- */
- static Eina_Bool EcoreEventDndFinished( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndFinished\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when a dragged item is moved from our window and the target window has sent us a status.
- * This is when items are dragged FROM our window.
- */
- static Eina_Bool EcoreEventDndStatus( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndStatus\n" );
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the client messages (i.e. the accessibility events) are received.
- */
- static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
- {
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Event_Client_Message* clientMessageEvent( (Ecore_X_Event_Client_Message*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if (clientMessageEvent->message_type == ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL)
- {
- if ( ( (unsigned int)clientMessageEvent->data.l[0] == handler->mImpl->mWindow ) && handler->mAccessibilityAdaptor )
- {
- AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
-
- if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_SCROLL)
- {
- // 2 finger touch & move, 2 finger flick
-
- // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
- // x : e->data.l[3]
- // y : e->data.l[4]
- TouchPoint::State state(TouchPoint::Down);
-
- if ((unsigned int)clientMessageEvent->data.l[2] == 0)
- {
- state = TouchPoint::Down; // mouse down
- }
- else if ((unsigned int)clientMessageEvent->data.l[2] == 1)
- {
- state = TouchPoint::Motion; // mouse move
- }
- else if ((unsigned int)clientMessageEvent->data.l[2] == 2)
- {
- state = TouchPoint::Up; // mouse up
- }
- else
- {
- state = TouchPoint::Interrupted; // error
- }
-
- DALI_LOG_INFO(gClientMessageLogFilter, Debug::General,
- "[%s:%d] [%d] %d, %d\n", __FUNCTION__, __LINE__,
- (unsigned int)clientMessageEvent->data.l[2],
- (unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4]);
-
- // Send touch event to accessibility adaptor.
- TouchPoint point( 0, state, (float)clientMessageEvent->data.l[3], (float)clientMessageEvent->data.l[4] );
-
- // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
- accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_MOUSE)
- {
- // 1 finger double tap and hold
-
- // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
- // x : e->data.l[3]
- // y : e->data.l[4]
- TouchPoint::State state(TouchPoint::Down);
-
- if ((unsigned int)clientMessageEvent->data.l[2] == 0)
- {
- state = TouchPoint::Down; // mouse down
- }
- else if ((unsigned int)clientMessageEvent->data.l[2] == 1)
- {
- state = TouchPoint::Motion; // mouse move
- }
- else if ((unsigned int)clientMessageEvent->data.l[2] == 2)
- {
- state = TouchPoint::Up; // mouse up
- }
- else
- {
- state = TouchPoint::Interrupted; // error
- }
-
- DALI_LOG_INFO(gClientMessageLogFilter, Debug::General,
- "[%s:%d] [%d] %d, %d\n", __FUNCTION__, __LINE__,
- (unsigned int)clientMessageEvent->data.l[2],
- (unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4]);
-
- // Send touch event to accessibility adaptor.
- TouchPoint point( 0, state, (float)clientMessageEvent->data.l[3], (float)clientMessageEvent->data.l[4] );
-
- // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
- accessibilityAdaptor->HandleActionTouchEvent( point, GetCurrentMilliSeconds() );
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_BACK)
- {
- // 2 finger circle draw, do back
- accessibilityAdaptor->HandleActionBackEvent();
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_NEXT)
- {
- // one finger flick down
- // focus next object
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionNextEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_PREV)
- {
- // one finger flick up
- // focus previous object
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionPreviousEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_ACTIVATE)
- {
- // one finger double tap
- // same as one finger tap in normal mode (i.e. execute focused actor)
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionActivateEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ)
- {
- // one finger tap
- // focus & read an actor at ( e->data.l[2], e->data.l[3] ) position according to finger
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionReadEvent((unsigned int)clientMessageEvent->data.l[2], (unsigned int)clientMessageEvent->data.l[3], true /* allow read again*/);
- }
- }
-#if defined(DALI_PROFILE_MOBILE)
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_OVER)
- {
- // one finger tap & move
- // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
- // x : e->data.l[3]
- // y : e->data.l[4]
- // focus & read an actor at (x, y) position according to finger
- if(accessibilityAdaptor && (unsigned int)clientMessageEvent->data.l[2] == 1 /*only work for move event*/)
- {
- accessibilityAdaptor->HandleActionReadEvent((unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4], false /* not allow read again*/);
- }
- }
-#endif
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ_NEXT)
- {
- // one finger flick right
- // focus next object
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionReadNextEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ_PREV)
- {
- // one finger flick left
- // focus previous object
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionReadPreviousEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_UP)
- {
- // double down and move (right, up)
- // change slider value
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionUpEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_DOWN)
- {
- // double down and move (left, down)
- // change slider value
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionDownEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_ENABLE)
- {
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionEnableEvent();
- }
- }
- else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_DISABLE)
- {
- if(accessibilityAdaptor)
- {
- accessibilityAdaptor->HandleActionDisableEvent();
- }
- }
- // TODO: some more actions could be added later
- }
- }
- else if(clientMessageEvent->message_type == ecore_x_atom_get(CLIPBOARD_ATOM))
- {
- std::string message(clientMessageEvent->data.b);
- if( message == CLIPBOARD_SET_OWNER_MESSAGE)
- {
- // Claim the ownership of the SECONDARY selection.
- ecore_x_selection_secondary_set(handler->mImpl->mWindow, "", 1);
-
- // Show the clipboard window
- Dali::Clipboard clipboard = Dali::Clipboard::Get();
- clipboard.ShowClipboard();
- }
- }
- else if( clientMessageEvent->message_type == ECORE_X_ATOM_E_WINDOW_ROTATION_CHANGE_PREPARE )
- {
- RotationEvent rotationEvent;
- rotationEvent.angle = static_cast<int>(clientMessageEvent->data.l[1]);
- rotationEvent.winResize = static_cast<int>(clientMessageEvent->data.l[2]);
- rotationEvent.width = static_cast<int>(clientMessageEvent->data.l[3]);
- rotationEvent.height = static_cast<int>(clientMessageEvent->data.l[4]);
- handler->SendRotationPrepareEvent( rotationEvent );
- }
- else if( clientMessageEvent->message_type == ECORE_X_ATOM_E_WINDOW_ROTATION_CHANGE_REQUEST )
- {
- handler->SendRotationRequestEvent();
- }
-
-#endif // DALI_PROFILE_UBUNTU
- return ECORE_CALLBACK_PASS_ON;
- }
-
-
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // ElDBus Accessibility Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
-
-#ifdef DALI_ELDBUS_AVAILABLE
- // Callback for Ecore ElDBus accessibility events.
- static void OnEcoreElDBusAccessibilityNotification( void *context EINA_UNUSED, const Eldbus_Message *message )
- {
- EventHandler* handler = static_cast< EventHandler* >( context );
- // Ignore any accessibility events when paused.
- if( handler->mPaused )
- {
- return;
- }
-
- if ( !handler->mAccessibilityAdaptor )
- {
- DALI_LOG_ERROR( "Invalid accessibility adaptor\n" );
- return;
- }
-
- AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
- if ( !accessibilityAdaptor )
- {
- DALI_LOG_ERROR( "Cannot access accessibility adaptor\n" );
- return;
- }
-
- const char *gestureName;
- int xS, yS, xE, yE;
- unsigned int state;
-
- // The string defines the arg-list's respective types.
- if( !eldbus_message_arguments_get( message, "siiiiu", &gestureName, &xS, &yS, &xE, &yE, &state ) )
- {
- DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" );
- }
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Name: %s Args: %d,%d,%d,%d State: %d\n", gestureName, xS, yS, xE, yE );
-
- unsigned int fingers = 0;
- char* stringPosition = ( char* )gestureName;
-
- // Check how many fingers the gesture uses.
- for( unsigned int i = 0; i < FingerCountStringsTotal; ++i )
- {
- unsigned int matchLength = strlen( ElDBusAccessibilityFingerCountStrings[ i ] );
- if( strncmp( gestureName, ElDBusAccessibilityFingerCountStrings[ i ], matchLength ) == 0 )
- {
- fingers = i + 1;
- stringPosition += matchLength;
- break;
- }
- }
-
- if( fingers == 0 )
- {
- // Error: invalid gesture.
- return;
- }
-
- GestureType gestureType = GESTURE_TYPE_NONE;
- SubGestureType subGestureType = SUB_GESTURE_TYPE_NONE;
- GestureDirection direction = GESTURE_DIRECTION_NONE;
-
- // Check for full gesture type names first.
- for( unsigned int i = 0; i < FullEventTypeStringsTotal; ++i )
- {
- unsigned int matchLength = strlen( ElDBusAccessibilityFullEventTypeStrings[ i ].name );
- if( strncmp( stringPosition, ElDBusAccessibilityFullEventTypeStrings[ i ].name, matchLength ) == 0 )
- {
- gestureType = ElDBusAccessibilityFullEventTypeStrings[ i ].type;
- break;
- }
- }
-
- // If we didn't find a full gesture, check for sub gesture type names.
- if( gestureType == GESTURE_TYPE_NONE )
- {
- // No full gesture name found, look for partial types.
- for( unsigned int i = 0; i < DirectionalEventTypeStringsTotal; ++i )
- {
- unsigned int matchLength = strlen( ElDBusAccessibilityDirectionalEventTypeStrings[ i ].name );
- if( strncmp( stringPosition, ElDBusAccessibilityDirectionalEventTypeStrings[ i ].name, matchLength ) == 0 )
- {
- subGestureType = ElDBusAccessibilityDirectionalEventTypeStrings[ i ].type;
- stringPosition += matchLength;
- break;
- }
- }
-
- if( subGestureType == SUB_GESTURE_TYPE_NONE )
- {
- // ERROR: Gesture not recognised.
- return;
- }
-
- // If the gesture was a sub type, get it's respective direction.
- for( unsigned int i = 0; i < DirectionStringsTotal; ++i )
- {
- unsigned int matchLength = strlen( ElDBusAccessibilityDirectionStrings[ i ].name );
- if( strncmp( stringPosition, ElDBusAccessibilityDirectionStrings[ i ].name, matchLength ) == 0 )
- {
- direction = ElDBusAccessibilityDirectionStrings[ i ].direction;
- stringPosition += matchLength;
- break;
- }
- }
-
- if( direction == GESTURE_DIRECTION_NONE )
- {
- // ERROR: Gesture not recognised.
- return;
- }
- }
-
- // Action the detected gesture here.
- if( gestureType != GESTURE_TYPE_NONE )
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Fingers: %d Gesture type: %d\n", fingers, gestureType );
- }
- else
- {
- DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Fingers: %d Gesture sub type: %d Gesture direction: %d\n",
- fingers, subGestureType, direction );
- }
-
- // Create a touch point object.
- TouchPoint::State touchPointState( TouchPoint::Down );
- if ( state == 0 )
- {
- touchPointState = TouchPoint::Down; // Mouse down.
- }
- else if ( state == 1 )
- {
- touchPointState = TouchPoint::Motion; // Mouse move.
- }
- else if ( state == 2 )
- {
- touchPointState = TouchPoint::Up; // Mouse up.
- }
- else
- {
- touchPointState = TouchPoint::Interrupted; // Error.
- }
-
- // Send touch event to accessibility adaptor.
- TouchPoint point( 0, touchPointState, (float)xS, (float)yS );
-
- // Perform actions based on received gestures.
- // Note: This is seperated from the reading so we can (in future)
- // have other input readers without changing the below code.
- switch( fingers )
- {
- case 1:
- {
- if( gestureType == GESTURE_TYPE_SINGLE_TAP || ( gestureType == GESTURE_TYPE_HOVER && touchPointState == TouchPoint::Motion ) )
- {
- // Focus, read out.
- accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
- }
- else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
- {
- if( false ) // TODO: how to detect double tap + hold?
- {
- // Move or drag icon / view more options for selected items.
- // accessibilityAdaptor->HandleActionTouchEvent( point, GetCurrentMilliSeconds() );
- }
- else
- {
- // Activate selected item / active edit mode.
- accessibilityAdaptor->HandleActionActivateEvent();
- }
- }
- else if( gestureType == GESTURE_TYPE_TRIPLE_TAP )
- {
- // Zoom
- accessibilityAdaptor->HandleActionZoomEvent();
- }
- else if( subGestureType == SUB_GESTURE_TYPE_FLICK )
- {
- if( direction == GESTURE_DIRECTION_LEFT )
- {
- // Move to previous item.
- accessibilityAdaptor->HandleActionReadPreviousEvent();
- }
- else if( direction == GESTURE_DIRECTION_RIGHT )
- {
- // Move to next item.
- accessibilityAdaptor->HandleActionReadNextEvent();
- }
- else if( direction == GESTURE_DIRECTION_UP )
- {
- // Move to next item.
- accessibilityAdaptor->HandleActionPreviousEvent();
- }
- else if( direction == GESTURE_DIRECTION_DOWN )
- {
- // Move to next item.
- accessibilityAdaptor->HandleActionNextEvent();
- }
- else if( direction == GESTURE_DIRECTION_LEFT_RETURN )
- {
- // Scroll up to the previous page
- accessibilityAdaptor->HandleActionPageUpEvent();
- }
- else if( direction == GESTURE_DIRECTION_RIGHT_RETURN )
- {
- // Scroll down to the next page
- accessibilityAdaptor->HandleActionPageDownEvent();
- }
- else if( direction == GESTURE_DIRECTION_UP_RETURN )
- {
- // Move to the first item on screen
- accessibilityAdaptor->HandleActionMoveToFirstEvent();
- }
- else if( direction == GESTURE_DIRECTION_DOWN_RETURN )
- {
- // Move to the last item on screen
- accessibilityAdaptor->HandleActionMoveToLastEvent();
- }
- }
- break;
- }
-
- case 2:
- {
- if( gestureType == GESTURE_TYPE_HOVER )
- {
- // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
- accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
- }
- else if( gestureType == GESTURE_TYPE_SINGLE_TAP )
- {
- // Pause/Resume current speech
- accessibilityAdaptor->HandleActionReadPauseResumeEvent();
- }
- else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
- {
- // Start/Stop current action
- accessibilityAdaptor->HandleActionStartStopEvent();
- }
- else if( gestureType == GESTURE_TYPE_TRIPLE_TAP )
- {
- // Read information from indicator
- accessibilityAdaptor->HandleActionReadIndicatorInformationEvent();
- }
- else if( subGestureType == SUB_GESTURE_TYPE_FLICK )
- {
- if( direction == GESTURE_DIRECTION_LEFT )
- {
- // Scroll left to the previous page
- accessibilityAdaptor->HandleActionPageLeftEvent();
- }
- else if( direction == GESTURE_DIRECTION_RIGHT )
- {
- // Scroll right to the next page
- accessibilityAdaptor->HandleActionPageRightEvent();
- }
- else if( direction == GESTURE_DIRECTION_UP )
- {
- // Scroll up the list.
- accessibilityAdaptor->HandleActionScrollUpEvent();
- }
- else if( direction == GESTURE_DIRECTION_DOWN )
- {
- // Scroll down the list.
- accessibilityAdaptor->HandleActionScrollDownEvent();
- }
- }
- break;
- }
-
- case 3:
- {
- if( gestureType == GESTURE_TYPE_SINGLE_TAP )
- {
- // Read from top item on screen continuously.
- accessibilityAdaptor->HandleActionReadFromTopEvent();
- }
- else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
- {
- // Read from next item continuously.
- accessibilityAdaptor->HandleActionReadFromNextEvent();
- }
- break;
- }
- }
- }
-
- // Callback for to set up Ecore ElDBus for accessibility callbacks.
- static void EcoreElDBusInitialisation( void *handle, const Eldbus_Message *message, Eldbus_Pending *pending EINA_UNUSED )
- {
- Eldbus_Object *object;
- Eldbus_Proxy *manager;
- const char *a11yBusAddress = NULL;
- EventHandler* handler = static_cast< EventHandler* >( handle );
-
- // The string defines the arg-list's respective types.
- if( !eldbus_message_arguments_get( message, "s", &a11yBusAddress ) )
- {
- DALI_LOG_ERROR( "EcoreElDBusInitialisation: Error getting arguments\n" );
- }
-
- DALI_LOG_INFO( gImfLogging, Debug::General, "Ecore ElDBus Accessibility address: %s\n", a11yBusAddress );
-
- handler->mImpl->mA11yConnection = eldbus_address_connection_get( a11yBusAddress );
-
- object = eldbus_object_get( handler->mImpl->mA11yConnection, BUS, PATH );
- manager = eldbus_proxy_get( object, INTERFACE );
-
- // Pass the callback data through to the signal handler.
- eldbus_proxy_signal_handler_add( manager, SIGNAL, OnEcoreElDBusAccessibilityNotification, handle );
- }
-#endif // DALI_ELDBUS_AVAILABLE
-
- /**
- * Called when the source window notifies us the content in clipboard is selected.
- */
- static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionClear\n" );
- Ecore_X_Event_Selection_Clear* selectionClearEvent( (Ecore_X_Event_Selection_Clear*) event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( selectionClearEvent->win == handler->mImpl->mWindow )
- {
- if ( selectionClearEvent->selection == ECORE_X_SELECTION_SECONDARY )
- {
- // Request to get the content from Ecore.
- ecore_x_selection_secondary_request(selectionClearEvent->win, ECORE_X_SELECTION_TARGET_TEXT);
- }
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
- /**
- * Called when the source window sends us about the selected content.
- * For example, when dragged items are dragged INTO our window or when items are selected in the clipboard.
- */
- static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event )
- {
- DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionNotify\n" );
-
- Ecore_X_Event_Selection_Notify* selectionNotifyEvent( (Ecore_X_Event_Selection_Notify*) event );
- EventHandler* handler( (EventHandler*)data );
-
- if ( selectionNotifyEvent->win == handler->mImpl->mWindow )
- {
- Ecore_X_Selection_Data* selectionData( (Ecore_X_Selection_Data*) selectionNotifyEvent->data );
- if ( selectionData->data )
- {
- if ( selectionNotifyEvent->selection == ECORE_X_SELECTION_XDND )
- {
- DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
-
- // We have got the content that is to be dropped, inform the DndListener (if we have one).
- if ( dndDetector )
- {
- std::string content( (char*) selectionData->data, selectionData->length );
- dndDetector->SetContent( content );
-
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d):\n" , selectionData->length );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "%s\n", selectionData->data );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
- }
- }
- else if ( selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY )
- {
- // We have got the selected content, inform the clipboard event listener (if we have one).
- if ( handler->mClipboardEventNotifier )
- {
- ClipboardEventNotifier& clipboardEventNotifier( ClipboardEventNotifier::GetImplementation( handler->mClipboardEventNotifier ) );
- std::string content( (char*) selectionData->data, selectionData->length );
- clipboardEventNotifier.SetContent( content );
- clipboardEventNotifier.EmitContentSelectedSignal();
- }
-
- // Claim the ownership of the SECONDARY selection.
- ecore_x_selection_secondary_set(handler->mImpl->mWindow, "", 1);
-
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d):\n" , selectionData->length );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "%s\n", selectionData->data );
- DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
- }
- }
- }
- return ECORE_CALLBACK_PASS_ON;
- }
-
-
-#ifndef DALI_PROFILE_UBUNTU
- /////////////////////////////////////////////////////////////////////////////////////////////////
- // Font Callbacks
- /////////////////////////////////////////////////////////////////////////////////////////////////
- /**
- * Called when a font name is changed.
- */
- static void VconfNotifyFontNameChanged( keynode_t* node, void* data )
- {
- EventHandler* handler = static_cast<EventHandler*>( data );
- handler->SendEvent( StyleChange::DEFAULT_FONT_CHANGE );
- }
-
- /**
- * Called when a font size is changed.
- */
- static void VconfNotifyFontSizeChanged( keynode_t* node, void* data )
- {
- DALI_LOG_INFO(gTouchEventLogFilter, Debug::Verbose, "VconfNotifyFontSizeChanged\n" );
- EventHandler* handler = static_cast<EventHandler*>( data );
- handler->SendEvent( StyleChange::DEFAULT_FONT_SIZE_CHANGE );
- }
-#endif // DALI_PROFILE_UBUNTU
-
- // Data
- EventHandler* mHandler;
- std::vector<Ecore_Event_Handler*> mEcoreEventHandler;
- Ecore_X_Window mWindow;
- int mXiDeviceId;
-
-#ifdef DALI_ELDBUS_AVAILABLE
- Eldbus_Connection* mSessionConnection;
- Eldbus_Connection* mA11yConnection;
-#endif
-};
-
-EventHandler::EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector )
-: mCoreEventInterface( coreEventInterface ),
- mGestureManager( gestureManager ),
- mStyleMonitor( StyleMonitor::Get() ),
- mDamageObserver( damageObserver ),
- mRotationObserver( NULL ),
- mDragAndDropDetector( dndDetector ),
- mAccessibilityAdaptor( AccessibilityAdaptor::Get() ),
- mClipboardEventNotifier( ClipboardEventNotifier::Get() ),
- mClipboard( Clipboard::Get() ),
- mImpl( NULL ),
- mPaused( false )
-{
- Ecore_X_Window window = 0;
-
- // this code only works with the EcoreX11 RenderSurface so need to downcast
- ECore::WindowRenderSurface* ecoreSurface = dynamic_cast< ECore::WindowRenderSurface* >( surface );
- if( ecoreSurface )
- {
- // enable multi touch
- window = ecoreSurface->GetXWindow();
- }
-
- mImpl = new Impl(this, window);
-}
-
-EventHandler::~EventHandler()
-{
- delete mImpl;
-
- mGestureManager.Stop();
-}
-
-void EventHandler::SendEvent(Integration::Point& point, unsigned long timeStamp)
-{
- if(timeStamp < 1)
- {
- timeStamp = GetCurrentMilliSeconds();
- }
-
- Integration::TouchEvent touchEvent;
- Integration::HoverEvent hoverEvent;
- Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent(point, timeStamp, touchEvent, hoverEvent);
- if(type != Integration::TouchEventCombiner::DispatchNone )
- {
- DALI_LOG_INFO(gTouchEventLogFilter, Debug::General, "%d: Device %d: Button state %d (%.2f, %.2f)\n", timeStamp, point.GetDeviceId(), point.GetState(), point.GetScreenPosition().x, point.GetScreenPosition().y);
-
- // First the touch and/or hover event & related gesture events are queued
- if(type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( touchEvent );
- mGestureManager.SendEvent(touchEvent);
- }
-
- if(type == Integration::TouchEventCombiner::DispatchHover || type == Integration::TouchEventCombiner::DispatchBoth)
- {
- mCoreEventInterface.QueueCoreEvent( hoverEvent );
- }
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
- }
-}
-
-void EventHandler::SendEvent(Integration::KeyEvent& keyEvent)
-{
- Dali::PhysicalKeyboard physicalKeyboard = PhysicalKeyboard::Get();
- if ( physicalKeyboard )
- {
- if ( ! KeyLookup::IsDeviceButton( keyEvent.keyName.c_str() ) )
- {
- GetImplementation( physicalKeyboard ).KeyReceived( keyEvent.time > 1 );
- }
- }
-
- // Send to KeyEvent Core.
- mCoreEventInterface.QueueCoreEvent( keyEvent );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendWheelEvent( WheelEvent& wheelEvent )
-{
- // Create WheelEvent and send to Core.
- Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >(wheelEvent.type), wheelEvent.direction, wheelEvent.modifiers, wheelEvent.point, wheelEvent.z, wheelEvent.timeStamp );
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::SendEvent( StyleChange::Type styleChange )
-{
- DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" );
- GetImplementation( mStyleMonitor ).StyleChanged(styleChange);
-}
-
-void EventHandler::SendEvent( const DamageArea& area )
-{
- mDamageObserver.OnDamaged( area );
-}
-
-void EventHandler::SendRotationPrepareEvent( const RotationEvent& event )
-{
- if( mRotationObserver != NULL )
- {
- mRotationObserver->OnRotationPrepare( event );
- }
-}
-
-void EventHandler::SendRotationRequestEvent( )
-{
- if( mRotationObserver != NULL )
- {
- mRotationObserver->OnRotationRequest( );
- }
-}
-
-void EventHandler::FeedTouchPoint( TouchPoint& point, int timeStamp)
-{
- Integration::Point convertedPoint( point );
-
- SendEvent(convertedPoint, timeStamp);
-}
-
-void EventHandler::FeedWheelEvent( WheelEvent& wheelEvent )
-{
- SendWheelEvent( wheelEvent );
-}
-
-void EventHandler::FeedKeyEvent( KeyEvent& event )
-{
- Integration::KeyEvent convertedEvent( event );
- SendEvent( convertedEvent );
-}
-
-void EventHandler::FeedEvent( Integration::Event& event )
-{
- mCoreEventInterface.QueueCoreEvent( event );
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Reset()
-{
- mCombiner.Reset();
-
- // Any touch listeners should be told of the interruption.
- Integration::TouchEvent event;
- Integration::Point point;
- point.SetState( PointState::INTERRUPTED );
- event.AddPoint( point );
-
- // First the touch event & related gesture events are queued
- mCoreEventInterface.QueueCoreEvent( event );
- mGestureManager.SendEvent( event );
-
- // Next the events are processed with a single call into Core
- mCoreEventInterface.ProcessCoreEvents();
-}
-
-void EventHandler::Pause()
-{
- mPaused = true;
- Reset();
-}
-
-void EventHandler::Resume()
-{
- mPaused = false;
- Reset();
-}
-
-void EventHandler::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
-{
- mDragAndDropDetector = detector;
-}
-
-void EventHandler::SetRotationObserver( RotationObserver* observer )
-{
- mRotationObserver = observer;
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <pixmap-render-surface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-DALI_EXPORT_API PixmapRenderSurface* CreatePixmapSurface(
- PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-{
- return new PixmapRenderSurface(positionSize, surface, name, isTransparent);
-}
-
-
-} // namespace ECore
-
-} // namespace Dali
-
-
-
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-x-render-surface.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-#include <X11/extensions/Xfixes.h> // for damage notify
-#include <X11/extensions/Xdamage.h> // for damage notify
-
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <ecore-x-types.h>
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_ECORE_X_RENDER_SURFACE");
-#endif
-
-namespace ECore
-{
-
-EcoreXRenderSurface::EcoreXRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: mPosition(positionSize),
- mTitle(name),
- mRenderNotification(NULL),
- mColorDepth(isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24),
- mOwnSurface(false)
-{
-}
-
-void EcoreXRenderSurface::Init( Any surface )
-{
- // see if there is a surface in Any surface
- unsigned int surfaceId = GetSurfaceId( surface );
-
- // if the surface is empty, create a new one.
- if ( surfaceId == 0 )
- {
- // we own the surface about to created
- mOwnSurface = true;
- CreateXRenderable();
- }
- else
- {
- // XLib should already be initialized so no point in calling XInitThreads
- UseExistingRenderable( surfaceId );
- }
-}
-
-EcoreXRenderSurface::~EcoreXRenderSurface()
-{
-}
-
-void EcoreXRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification)
-{
- mRenderNotification = renderNotification;
-}
-
-Ecore_X_Window EcoreXRenderSurface::GetXWindow()
-{
- return 0;
-}
-
-Ecore_X_Drawable EcoreXRenderSurface::GetDrawable()
-{
- return 0;
-}
-
-PositionSize EcoreXRenderSurface::GetPositionSize() const
-{
- return mPosition;
-}
-
-void EcoreXRenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
- // nothing to do in base class
-}
-
-void EcoreXRenderSurface::SetViewMode( ViewMode viewMode )
-{
-}
-
-unsigned int EcoreXRenderSurface::GetSurfaceId( Any surface ) const
-{
- unsigned int surfaceId = 0;
-
- if ( surface.Empty() == false )
- {
- // check we have a valid type
- DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (XWindow) ) ||
- (surface.GetType() == typeid (Ecore_X_Window) ) )
- && "Surface type is invalid" );
-
- if ( surface.GetType() == typeid (Ecore_X_Window) )
- {
- surfaceId = AnyCast<Ecore_X_Window>( surface );
- }
- else
- {
- surfaceId = AnyCast<XWindow>( surface );
- }
- }
- return surfaceId;
-}
-
-RenderSurface::Type EcoreXRenderSurface::GetSurfaceType()
-{
- return RenderSurface::ECORE_RENDER_SURFACE;
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "ecore-x-window-interface.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <ecore-x-types.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace ECore
-{
-
-namespace WindowInterface
-{
-// CONSTANTS
-const char* const CBHM_WINDOW = "CBHM_XWIN";
-
-Ecore_X_Window GetWindow()
-{
- Ecore_X_Atom xAtomCbhm = ecore_x_atom_get( CBHM_WINDOW );
-
- Ecore_X_Window xCbhmWin = 0;
- unsigned char *buf = NULL;
- int num = 0;
-// XA_WINDOW is a macro with C cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
- int ret = ecore_x_window_prop_property_get( 0, xAtomCbhm, XA_WINDOW, 0, &buf, &num );
-#pragma GCC diagnostic pop
-
- if ( ret && num )
- {
- memcpy( &xCbhmWin, buf, sizeof( Ecore_X_Window ) );
- }
- if ( buf )
- {
- free( buf );
- }
-
- return xCbhmWin;
-}
-
-std::string GetWindowProperty( Ecore_X_Atom property, Ecore_X_Atom *xDataType, unsigned int num )
-{
- std::string data("");
-
- if ( !property )
- {
- return data;
- }
-
- ecore_x_sync();
-
- long unsigned int numRet = 0, bytes = 0;
- int ret = 0, sizeRet;
- unsigned int i;
- unsigned char *propRet;
- Ecore_X_Atom typeRet;
-
- // X11 Function to get window property
- ret = XGetWindowProperty( static_cast<Display*>(ecore_x_display_get()), // Display* X Server Connection
- GetWindow(), // Window window in question
- property, // Atom name of property
- num, // long offset where required data is stored
- LONG_MAX, // long length of data to retrieve
- False, // Bool flag to delete data
- ecore_x_window_prop_any_type(), // Atom atom id associated to property type
- reinterpret_cast< Atom * >( &typeRet ), // Atom actual_type_return, atom id property type
- &sizeRet, // int* format of property
- &numRet, // unsigned long* number of items being returned in prop_return
- &bytes, // unsigned long* remaining bytes if partial retrieval
- &propRet ); // unsigned char** return data
- if ( ret != Success )
- {
- return data;
- }
-
- if ( !numRet )
- {
- XFree( propRet );
- return data;
- }
-
- numRet--; // As propRet in XGetWindowProperty gets an extra 0 added for compatibility reasons.
-
- switch ( sizeRet ) // Format returned by XGetWindowProperty int, short, long
- {
- case 8:
- {
- for ( i = 0; i < numRet; i++ )
- {
- data += propRet[i];
- }
- }
- break;
-
- case 16:
- {
- for ( i = 0; i < numRet; i++ )
- {
- data += ( propRet )[i];
- }
- }
- break;
-
- case 32:
- {
- for ( i = 0; i < numRet; i++ )
- {
- data += ( propRet )[i];
- }
- }
- break;
- }
-
- XFree( propRet );
-
- if ( xDataType )
- {
- *xDataType = typeRet;
- }
-
- return data;
- }
-
-void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate,
- long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char *msg )
-{
- XClientMessageEvent message;
- memset(&message, 0, sizeof( message ) );
- message.type = ClientMessage;
- message.display = static_cast<Display*>( display );
- message.message_type = messageType;
- message.format = messageFormat;
- message.window = window;
- snprintf(message.data.b, 20, "%s", msg);
-
- XSendEvent( static_cast<Display*>( display ), window, propagate, eventMask, reinterpret_cast< XEvent* >( &message ) );
-}
-
-
-} // namespace WindowInterface
-
-
-} // namespace ECore
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-# x11
-
-_adaptor_x11_internal_src_files = \
- $(adaptor_x11_dir)/clipboard-impl-x.cpp \
- $(adaptor_x11_dir)/display-connection-impl-x.cpp \
- $(adaptor_x11_dir)/imf-manager-impl-x.cpp \
- $(adaptor_x11_dir)/native-image-source-impl-x.cpp \
- $(adaptor_x11_dir)/virtual-keyboard-impl-x.cpp \
- $(adaptor_x11_dir)/window-impl-x.cpp \
- $(adaptor_x11_dir)/pixmap-render-surface-x.cpp \
- $(adaptor_x11_dir)/ecore-x-render-surface.cpp \
- $(adaptor_x11_dir)/window-render-surface-x.cpp \
- $(adaptor_x11_dir)/ecore-x-window-interface.cpp
-
-adaptor_ecore_x_event_handler_internal_src_files = \
- $(adaptor_x11_dir)/ecore-x-event-handler.cpp
-
-adaptor_uv_x_event_handler_internal_src_files = \
- $(adaptor_x11_dir)/x-event-handler.cpp \
- $(adaptor_x11_dir)/x-events/x-event-manager.cpp \
- $(adaptor_x11_dir)/x-events/x-input2.cpp \
- $(adaptor_x11_dir)/x-events/x-input2-device.cpp \
- $(adaptor_x11_dir)/x-events/debug/x-input2-debug.cpp
-
-adaptor_x11_ubuntu_internal_src_files = \
- $(_adaptor_x11_internal_src_files)
-
-adaptor_x11_tizen_internal_src_files = \
- $(_adaptor_x11_internal_src_files) \
- $(adaptor_x11_dir)/framework-x.cpp \
- $(adaptor_x11_dir)/key-mapping-x.cpp \
- $(adaptor_x11_dir)/window-extensions.cpp \
- $(adaptor_x11_dir)/key-grab-x.cpp
-
-adaptor_x11_tv_internal_src_files = \
- $(_adaptor_x11_internal_src_files) \
- $(adaptor_x11_dir)/framework-x.cpp
-
-adaptor_x11_internal_default_profile_src_files = \
- $(adaptor_x11_dir)/ecore-x-render-surface-factory.cpp \
- $(adaptor_x11_dir)/system-settings-x.cpp
-
-devel_api_adaptor_tizen_x11_header_files = \
- $(adaptor_x11_dir)/window-extensions.h
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "framework.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xlib.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-void Framework::InitThreads()
-{
- XInitThreads();
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <imf-manager-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/events/key-event.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor.h>
-#include <window-render-surface.h>
-#include <adaptor-impl.h>
-#include <locale-utils.h>
-#include <singleton-service-impl.h>
-#include <virtual-keyboard-impl.h>
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include "ecore-virtual-keyboard.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
-#endif
-
-// Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
-size_t Utf8SequenceLength(const unsigned char leadByte)
-{
- size_t length = 0;
-
- if ((leadByte & 0x80) == 0 ) //ASCII character (lead bit zero)
- {
- length = 1;
- }
- else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
- {
- length = 2;
- }
- else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
- {
- length = 3;
- }
- else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
- {
- length = 4;
- }
-
- return length;
-}
-
-// Static function calls used by ecore 'c' style callback registration
-void Commit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->CommitReceived( data, imfContext, event_info );
- }
-}
-
-void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->PreEditChanged( data, imfContext, event_info );
- }
-}
-
-Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- return imfManager->RetrieveSurrounding( data, imfContext, text, cursorPosition );
- }
- else
- {
- return false;
- }
-}
-
-/**
- * Called when an IMF delete surrounding event is received.
- * Here we tell the application that it should delete a certain range.
- */
-void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
-{
- if ( data )
- {
- ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
- imfManager->DeleteSurrounding( data, imfContext, event_info );
- }
-}
-
-} // unnamed namespace
-
-bool ImfManager::IsAvailable()
-{
- bool available( false );
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- available = service.GetSingleton( typeid( Dali::ImfManager ) );
- }
-
- return available;
-}
-
-Dali::ImfManager ImfManager::Get()
-{
- Dali::ImfManager manager;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
- if( handle )
- {
- // If so, downcast the handle
- manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
- }
- else if ( Adaptor::IsAvailable() )
- {
- // Create instance and register singleton only if the adaptor is available
-
- Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
- Any nativeWindow = adaptorImpl.GetNativeWindowHandle();
-
- // The Ecore_X_Window needs to use the ImfManager.
- // Only when the render surface is window, we can get the Ecore_X_Window.
- Ecore_X_Window ecoreXwin( AnyCast<Ecore_X_Window>(nativeWindow) );
- if (ecoreXwin)
- {
- // If we fail to get Ecore_X_Window, we can't use the ImfManager correctly.
- // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
- // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
-
- manager = Dali::ImfManager( new ImfManager( ecoreXwin ) );
- service.Register( typeid( manager ), manager );
- }
- else
- {
- DALI_LOG_ERROR("Failed to get native window handle\n");
- }
- }
- }
-
- return manager;
-}
-
-ImfManager::ImfManager( Ecore_X_Window ecoreXwin )
-: mIMFContext(),
- mIMFCursorPosition( 0 ),
- mSurroundingText(),
- mRestoreAfterFocusLost( false ),
- mIdleCallbackConnected( false )
-{
- ecore_imf_init();
- CreateContext( ecoreXwin );
-
- ConnectCallbacks();
- VirtualKeyboard::ConnectCallbacks( mIMFContext );
-}
-
-ImfManager::~ImfManager()
-{
- VirtualKeyboard::DisconnectCallbacks( mIMFContext );
- DisconnectCallbacks();
-
- DeleteContext();
- ecore_imf_shutdown();
-}
-
-void ImfManager::CreateContext( Ecore_X_Window ecoreXwin )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CreateContext\n" );
-
- const char *contextId = ecore_imf_context_default_id_get();
- if( contextId )
- {
- mIMFContext = ecore_imf_context_add( contextId );
-
- if( mIMFContext )
- {
- if( ecoreXwin )
- {
- ecore_imf_context_client_window_set( mIMFContext, reinterpret_cast<void*>( ecoreXwin ) );
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "IMF Unable to get IMF Context\n");
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "IMF Unable to get IMF Context\n");
- }
-}
-
-void ImfManager::DeleteContext()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteContext\n" );
-
- if ( mIMFContext )
- {
- ecore_imf_context_del( mIMFContext );
- mIMFContext = NULL;
- }
-}
-
-// Callbacks for predicitive text support.
-void ImfManager::ConnectCallbacks()
-{
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ConnectCallbacks\n" );
-
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this );
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this );
- ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this );
-
- ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this);
- }
-}
-
-void ImfManager::DisconnectCallbacks()
-{
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DisconnectCallbacks\n" );
-
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit );
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit );
- ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding );
-
- // We do not need to unset the retrieve surrounding callback.
- }
-}
-
-void ImfManager::Activate()
-{
- // Reset mIdleCallbackConnected
- mIdleCallbackConnected = false;
-
- if ( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Activate\n" );
-
- ecore_imf_context_focus_in( mIMFContext );
-
- // emit keyboard activated signal
- Dali::ImfManager handle( this );
- mActivatedSignal.Emit( handle );
- }
-}
-
-void ImfManager::Deactivate()
-{
- if( mIMFContext )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Deactivate\n" );
-
- Reset();
- ecore_imf_context_focus_out( mIMFContext );
- }
-
- // Reset mIdleCallbackConnected
- mIdleCallbackConnected = false;
-}
-
-void ImfManager::Reset()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Reset\n" );
-
- if ( mIMFContext )
- {
- ecore_imf_context_reset( mIMFContext );
- }
-}
-
-Ecore_IMF_Context* ImfManager::GetContext()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetContext\n" );
-
- return mIMFContext;
-}
-
-bool ImfManager::RestoreAfterFocusLost() const
-{
- return mRestoreAfterFocusLost;
-}
-
-void ImfManager::SetRestoreAfterFocusLost( bool toggle )
-{
- mRestoreAfterFocusLost = toggle;
-}
-
-/**
- * Called when an IMF Pre-Edit changed event is received.
- * We are still predicting what the user is typing. The latest string is what the IMF module thinks
- * the user wants to type.
- */
-void ImfManager::PreEditChanged( void*, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged\n" );
-
- char* preEditString( NULL );
- int cursorPosition( 0 );
- Eina_List* attrs = NULL;
- Eina_List* l = NULL;
-
- Ecore_IMF_Preedit_Attr* attr;
-
- // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string.
- // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string.
- ecore_imf_context_preedit_string_with_attributes_get( imfContext, &preEditString, &attrs, &cursorPosition );
-
- if ( attrs )
- {
- // iterate through the list of attributes getting the type, start and end position.
- for ( l = attrs, (attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ))
- {
-#ifdef DALI_PROFILE_UBUNTU
- if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB3 ) // (Ecore_IMF)
-#else // DALI_PROFILE_UBUNTU
- if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB4 ) // (Ecore_IMF)
-#endif // DALI_PROFILE_UBUNTU
- {
- // check first byte so know how many bytes a character is represented by as keyboard returns cursor position in bytes. Which is different for some languages.
-
- size_t visualCharacterIndex = 0;
- size_t byteIndex = 0;
-
- // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
- const char leadByte = preEditString[byteIndex];
- while( leadByte != '\0' )
- {
- // attr->end_index is provided as a byte position not character and we need to know the character position.
- const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character.
- if ( byteIndex == attr->end_index )
- {
- cursorPosition = visualCharacterIndex;
- break;
- // end loop as found cursor position that matches byte position
- }
- else
- {
- byteIndex += currentSequenceLength; // jump to next character
- visualCharacterIndex++; // increment character count so we know our position for when we get a match
- }
-
- DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( preEditString ));
- }
- }
- }
- }
-
- if ( Dali::Adaptor::IsAvailable() )
- {
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::PREEDIT, preEditString, cursorPosition, 0 );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if( callbackData.update )
- {
- mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
-
- NotifyCursorPosition();
- }
-
- if( callbackData.preeditResetRequired )
- {
- Reset();
- }
- }
- free( preEditString );
-}
-
-void ImfManager::CommitReceived( void*, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitReceived\n" );
-
- if ( Dali::Adaptor::IsAvailable() )
- {
- const std::string keyString( static_cast<char*>( event_info ) );
-
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::COMMIT, keyString, 0, 0 );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
-
- if( callbackData.update )
- {
- mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
-
- NotifyCursorPosition();
- }
- }
-}
-
-/**
- * Called when an IMF retrieve surround event is received.
- * Here the IMF module wishes to know the string we are working with and where within the string the cursor is
- * We need to signal the application to tell us this information.
- */
-Eina_Bool ImfManager::RetrieveSurrounding( void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::RetrieveSurrounding\n" );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::GETSURROUNDING, std::string(), 0, 0 );
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
-
- if( callbackData.update )
- {
- if( text )
- {
- // The memory allocated by strdup() can be freed by ecore_imf_context_surrounding_get() internally.
- *text = strdup( callbackData.currentText.c_str() );
- }
-
- if( cursorPosition )
- {
- mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
- *cursorPosition = mIMFCursorPosition;
- }
- }
-
- return EINA_TRUE;
-}
-
-/**
- * Called when an IMF delete surrounding event is received.
- * Here we tell the application that it should delete a certain range.
- */
-void ImfManager::DeleteSurrounding( void* data, Ecore_IMF_Context* imfContext, void* event_info )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurrounding\n" );
-
- if( Dali::Adaptor::IsAvailable() )
- {
- Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast<Ecore_IMF_Event_Delete_Surrounding*>( event_info );
-
- Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::DELETESURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars );
- Dali::ImfManager handle( this );
- Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
-
- if( callbackData.update )
- {
- mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
-
- NotifyCursorPosition();
- }
- }
-}
-
-void ImfManager::NotifyCursorPosition()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition );
- }
-}
-
-void ImfManager::SetCursorPosition( unsigned int cursorPosition )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetCursorPosition\n" );
-
- mIMFCursorPosition = static_cast<int>( cursorPosition );
-}
-
-unsigned int ImfManager::GetCursorPosition() const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetCursorPosition\n" );
-
- return static_cast<unsigned int>( mIMFCursorPosition );
-}
-
-void ImfManager::SetSurroundingText( const std::string& text )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetSurroundingText\n" );
-
- mSurroundingText = text;
-}
-
-const std::string& ImfManager::GetSurroundingText() const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetSurroundingText\n" );
-
- return mSurroundingText;
-}
-
-void ImfManager::NotifyTextInputMultiLine( bool multiLine )
-{
-}
-
-Dali::ImfManager::TextDirection ImfManager::GetTextDirection()
-{
- Dali::ImfManager::TextDirection direction ( Dali::ImfManager::LeftToRight );
-
- if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
- {
- if ( mIMFContext )
- {
- char* locale( NULL );
- ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale );
-
- if ( locale )
- {
- direction = static_cast< Dali::ImfManager::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
- free( locale );
- }
- }
- }
- return direction;
-}
-
-Rect<int> ImfManager::GetInputMethodArea()
-{
- int xPos, yPos, width, height;
-
- width = height = xPos = yPos = 0;
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height );
- }
- else
- {
- DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
- }
-
- return Rect<int>(xPos,yPos,width,height);
-}
-
-void ImfManager::ApplyOptions( const InputMethodOptions& options )
-{
- using namespace Dali::InputMethod::Category;
-
- int index;
-
- if (mIMFContext == NULL)
- {
- DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n");
- return;
- }
-
- if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) )
- {
- }
- if ( mOptions.CompareAndSet(AUTO_CAPITALISE, options, index) )
- {
- }
- if ( mOptions.CompareAndSet(ACTION_BUTTON_TITLE, options, index) )
- {
- }
- if ( mOptions.CompareAndSet(VARIATION, options, index) )
- {
- }
-}
-
-void ImfManager::SetInputPanelData( const std::string& data )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetInputPanelData\n" );
-
- if( mIMFContext )
- {
- int length = data.length();
- ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length );
- }
-}
-
-void ImfManager::GetInputPanelData( std::string& data )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelData\n" );
-
- if( mIMFContext )
- {
- int length = 4096; // The max length is 4096 bytes
- Dali::Vector< char > buffer;
- buffer.Resize( length );
- ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length );
- data = std::string( buffer.Begin(), buffer.End() );
- }
-}
-
-Dali::ImfManager::State ImfManager::GetInputPanelState()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelState\n" );
-
- if( mIMFContext )
- {
- int value;
- value = ecore_imf_context_input_panel_state_get( mIMFContext );
-
- switch (value)
- {
- case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
- {
- return Dali::ImfManager::SHOW;
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
- {
- return Dali::ImfManager::HIDE;
- break;
- }
-
- case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
- {
- return Dali::ImfManager::WILL_SHOW;
- break;
- }
-
- default:
- {
- return Dali::ImfManager::DEFAULT;
- }
- }
- }
- return Dali::ImfManager::DEFAULT;
-}
-
-void ImfManager::SetReturnKeyState( bool visible )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetReturnKeyState\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible );
- }
-}
-
-void ImfManager::AutoEnableInputPanel( bool enabled )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::AutoEnableInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled );
- }
-}
-
-void ImfManager::ShowInputPanel()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ShowInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_show( mIMFContext );
- }
-}
-
-void ImfManager::HideInputPanel()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::HideInputPanel\n" );
-
- if( mIMFContext )
- {
- ecore_imf_context_input_panel_hide( mIMFContext );
- }
-}
-
-Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
-{
- return Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD;
-}
-
-std::string ImfManager::GetInputPanelLocale()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelLocale\n" );
-
- std::string locale = "";
-
- if( mIMFContext )
- {
- char* value = NULL;
- ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value );
-
- if( value )
- {
- std::string valueCopy( value );
- locale = valueCopy;
-
- // The locale string retrieved must be freed with free().
- free( value );
- }
- }
- return locale;
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <key-grab.h>
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-#include <utilX.h>
-
-// INTERNAL INCLUDES
-#include <window.h>
-#include <key-impl.h>
-#include <ecore-x-types.h>
-
-namespace Dali
-{
-
-namespace KeyGrab
-{
-
-bool GrabKeyTopmost( Window window, Dali::KEY daliKey )
-{
- return GrabKey( window, daliKey, TOPMOST);
-}
-
-bool UngrabKeyTopmost( Window window, Dali::KEY daliKey )
-{
- return UngrabKey( window, daliKey );
-}
-
-bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode )
-{
- int xGrabMode;
- if( grabMode == TOPMOST )
- {
- xGrabMode = TOP_POSITION_GRAB;
- }
- else if( grabMode == SHARED )
- {
- xGrabMode = SHARED_GRAB;
- }
- else if( grabMode == OVERRIDE_EXCLUSIVE )
- {
- xGrabMode = OR_EXCLUSIVE_GRAB;
- }
- else if( grabMode == EXCLUSIVE )
- {
- xGrabMode = EXCLUSIVE_GRAB;
- }
- else
- {
- return false;
- }
-
- int ret = utilx_grab_key ( static_cast<Display*>( ecore_x_display_get() ),
- static_cast<XWindow>( AnyCast<Ecore_X_Window>( window.GetNativeHandle() ) ),
- Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ), xGrabMode );
- return ret==0;
-}
-
-bool UngrabKey( Window window, Dali::KEY daliKey )
-{
- int ret = utilx_ungrab_key ( static_cast<Display*>( ecore_x_display_get() ),
- static_cast<XWindow>( AnyCast<Ecore_X_Window>( window.GetNativeHandle() ) ),
- Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ) );
- return ret==0;
-}
-
-} // namespace KeyGrab
-
-} // namespace Dali
-
-
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "key-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace KeyLookup
-{
-
-// matches a DALI_KEY enum, to a key name
-KeyLookup KeyLookupTable[]=
-{
- // more than one key name can be assigned to a single dali-key code
- // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
-
- { "Escape", DALI_KEY_ESCAPE, false },
- { "Menu", DALI_KEY_MENU, false },
-
- // Now literal strings are used as key names instead of defined symbols in utilX,
- // since these definition in utilX.h is deprecated
- { "XF86Camera", DALI_KEY_CAMERA, false },
- { "XF86Camera_Full", DALI_KEY_CONFIG, false },
- { "XF86PowerOff", DALI_KEY_POWER, true },
- { "XF86Standby", DALI_KEY_PAUSE, false },
- { "Cancel", DALI_KEY_CANCEL, false },
- { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
- { "XF86AudioStop", DALI_KEY_STOP_CD, false },
- { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
- { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
- { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
- { "XF86AudioRewind", DALI_KEY_REWIND, false },
- { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
- { "XF86AudioMedia", DALI_KEY_MEDIA, false },
- { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
- { "XF86AudioMute", DALI_KEY_MUTE, false },
- { "XF86Menu", DALI_KEY_MENU, true },
- { "XF86Home", DALI_KEY_HOME, true },
- { "XF86Back", DALI_KEY_BACK, true },
- { "XF86Send", DALI_KEY_MENU, true },
- { "XF86Phone", DALI_KEY_HOME, true },
- { "XF86Stop", DALI_KEY_BACK, true },
- { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
- { "XF86WWW", DALI_KEY_WEBPAGE, false },
- { "XF86Mail", DALI_KEY_MAIL, false },
- { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
- { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
- { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
- { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
- { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
- { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
- { "XF86Apps", DALI_KEY_APPS, false },
- { "XF86Search", DALI_KEY_SEARCH, false },
- { "XF86Voice", DALI_KEY_VOICE, false },
- { "Hangul", DALI_KEY_LANGUAGE, false },
- { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
- { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
-
- { "BackSpace", DALI_KEY_BACKSPACE, false },
- { "Left", DALI_KEY_CURSOR_LEFT, false },
- { "Right", DALI_KEY_CURSOR_RIGHT, false },
- { "left", DALI_KEY_CURSOR_LEFT, false }, // To be removed after the key name is fixed in the platform
- { "right", DALI_KEY_CURSOR_RIGHT, false }, // To be removed after the key name is fixed in the platform
- { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
- { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
- { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
- { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
- { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
- { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
-};
-
-const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
-
-} // namespace KeyLookup
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "native-image-source-impl.h"
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-#include <X11/Xutil.h>
-#include <X11/Xlib.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <gl/egl-image-extensions.h>
-#include <gl/egl-factory.h>
-#include <adaptor-impl.h>
-#include <bitmap-saver.h>
-#include <render-surface.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-using Dali::Integration::PixelBuffer;
-
-// Pieces needed to save compressed images (temporary location while plumbing):
-namespace
-{
-
- /**
- * Free an allocated XImage on destruction.
- */
- struct XImageJanitor
- {
- XImageJanitor( XImage* const pXImage ) : mXImage( pXImage )
- {
- DALI_ASSERT_DEBUG(pXImage != 0 && "Null pointer to XImage.");
- }
-
- ~XImageJanitor()
- {
- if( mXImage )
- {
- if( !XDestroyImage(mXImage) )
- {
- DALI_LOG_ERROR("XImage deallocation failure");
- }
- }
- }
- XImage* const mXImage;
- private:
- XImageJanitor( const XImageJanitor& rhs );
- XImageJanitor& operator = ( const XImageJanitor& rhs );
- };
-}
-
-NativeImageSource* NativeImageSource::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
-{
- NativeImageSource* image = new NativeImageSource( width, height, depth, nativeImageSource );
- DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." );
-
- // 2nd phase construction
- if(image) //< Defensive in case we ever compile without exceptions.
- {
- image->Initialize();
- }
-
- return image;
-}
-
-NativeImageSource::NativeImageSource( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
-: mWidth( width ),
- mHeight( height ),
- mOwnPixmap( true ),
- mPixmap( 0 ),
- mBlendingRequired( false ),
- mColorDepth( depth ),
- mEglImageKHR( NULL ),
- mEglImageExtensions( NULL )
-{
- DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );
- EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();
- mEglImageExtensions = eglFactory.GetImageExtensions();
- DALI_ASSERT_DEBUG( mEglImageExtensions );
-
- // assign the pixmap
- mPixmap = GetPixmapFromAny(nativeImageSource);
-}
-
-void NativeImageSource::Initialize()
-{
- // if pixmap has been created outside of X11 Image we can return
- if (mPixmap)
- {
- // we don't own the pixmap
- mOwnPixmap = false;
-
- // find out the pixmap width / height and color depth
- GetPixmapDetails();
- return;
- }
-
- // get the pixel depth
- int depth = GetPixelDepth(mColorDepth);
-
- // set whether blending is required according to pixel format based on the depth
- /* default pixel format is RGB888
- If depth = 8, Pixel::A8;
- If depth = 16, Pixel::RGB565;
- If depth = 32, Pixel::RGBA8888 */
- mBlendingRequired = ( depth == 32 || depth == 8 );
-
- mPixmap = ecore_x_pixmap_new( 0, mWidth, mHeight, depth );
- ecore_x_sync();
-}
-
-NativeImageSource::~NativeImageSource()
-{
- if (mOwnPixmap && mPixmap)
- {
- ecore_x_pixmap_free(mPixmap);
- }
-}
-
-Any NativeImageSource::GetNativeImageSource() const
-{
- // return ecore x11 type
- return Any(mPixmap);
-}
-
-bool NativeImageSource::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
-{
- DALI_ASSERT_DEBUG(sizeof(unsigned) == 4);
- bool success = false;
- width = mWidth;
- height = mHeight;
-
- // Open a display connection
- Display* displayConnection = XOpenDisplay( 0 );
-
- XImageJanitor xImageJanitor( XGetImage( displayConnection,
- mPixmap,
- 0, 0, // x,y of subregion to extract.
- width, height, // of suregion to extract.
- 0xFFFFFFFF,
- ZPixmap ) );
- XImage* const pXImage = xImageJanitor.mXImage;
- DALI_ASSERT_DEBUG(pXImage && "XImage (from pixmap) could not be retrieved from the server");
- if(!pXImage)
- {
- DALI_LOG_ERROR("Could not retrieve Ximage.\n");
- }
- else
- {
- switch(pXImage->depth)
- {
- // Note, depth is a logical value. On target the framebuffer is still 32bpp
- // (see pXImage->bits_per_pixel) so we go through XGetPixel() and swizzle.
- // Note, this could be the default, fallback case for all depths if *pXImage
- // didn't have blank RGB masks (X bug), but we have to hardcode the masks and
- // shifts instead.
- case 24:
- {
- pixelFormat = Pixel::RGB888;
- pixbuf.resize(width*height*3);
- unsigned char* bufPtr = &pixbuf[0];
-
- for(unsigned y = height-1; y < height; --y)
- {
- for(unsigned x = 0; x < width; ++x, bufPtr+=3)
- {
- const unsigned pixel = XGetPixel(pXImage,x,y);
-
- // store as RGB
- const unsigned blue = pixel & 0xFFU;
- const unsigned green = (pixel >> 8) & 0xFFU;
- const unsigned red = (pixel >> 16) & 0xFFU;
-
- *bufPtr = red;
- *(bufPtr+1) = green;
- *(bufPtr+2) = blue;
- }
- }
- success = true;
- break;
- }
- case 32:
- {
- if(pXImage->data)
- {
- // Sweep through the image, doing a vertical flip, but handling each scanline as
- // an inlined intrinsic/builtin memcpy (should be fast):
- pixbuf.resize(width*height*4);
- unsigned * bufPtr = reinterpret_cast<unsigned *>(&pixbuf[0]);
- const unsigned xDataLineSkip = pXImage->bytes_per_line;
- const size_t copy_count = static_cast< size_t >( width ) * 4;
- pixelFormat = Pixel::BGRA8888;
-
- for(unsigned y = height-1; y < height; --y, bufPtr += width)
- {
- const char * const in = pXImage->data + xDataLineSkip * y;
-
- // Copy a whole scanline at a time:
- DALI_ASSERT_DEBUG( size_t( bufPtr ) >= size_t( &pixbuf[0] ));
- DALI_ASSERT_DEBUG( reinterpret_cast<size_t>( bufPtr ) + copy_count <= reinterpret_cast<size_t>( &pixbuf[pixbuf.size()] ) );
- DALI_ASSERT_DEBUG( in >= pXImage->data );
- DALI_ASSERT_DEBUG( in + copy_count <= pXImage->data + xDataLineSkip * height );
- __builtin_memcpy( bufPtr, in, copy_count );
- }
- success = true;
- }
- else
- {
- DALI_LOG_ERROR("XImage has null data pointer.\n");
- }
- break;
- }
- // Make a case for 16 bit modes especially to remember that the only reason we don't support them is a bug in X:
- case 16:
- {
- DALI_ASSERT_DEBUG(pXImage->red_mask && pXImage->green_mask && pXImage->blue_mask && "No image masks mean 16 bit modes are not possible.");
- ///! If the above assert doesn't fail in a debug build, the X bug may have been fixed, so revisit this function.
- ///! No break, fall through to the general unsupported format warning below.
- }
- default:
- {
- DALI_LOG_WARNING("Pixmap has unsupported bit-depth for getting pixels: %u\n", pXImage->depth);
- }
- }
- }
- if(!success)
- {
- DALI_LOG_ERROR("Failed to get pixels from NativeImageSource.\n");
- pixbuf.resize(0);
- width = 0;
- height = 0;
- }
-
- // Close the display connection
- XCloseDisplay( displayConnection );
-
- return success;
-}
-
-bool NativeImageSource::EncodeToFile(const std::string& filename) const
-{
- std::vector< unsigned char > pixbuf;
- unsigned int width(0), height(0);
- Pixel::Format pixelFormat;
-
- if(GetPixels(pixbuf, width, height, pixelFormat))
- {
- return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);
- }
- return false;
-}
-
-void NativeImageSource::SetSource( Any source )
-{
- mPixmap = GetPixmapFromAny( source );
-
- if (mPixmap)
- {
- // we don't own the pixmap
- mOwnPixmap = false;
-
- // find out the pixmap width / height and color depth
- GetPixmapDetails();
- }
-}
-
-bool NativeImageSource::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
-{
- return true;
-}
-
-bool NativeImageSource::GlExtensionCreate()
-{
- // if the image existed previously delete it.
- if (mEglImageKHR != NULL)
- {
- GlExtensionDestroy();
- }
-
- // casting from an unsigned int to a void *, which should then be cast back
- // to an unsigned int in the driver.
- EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer > (mPixmap);
-
- mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );
-
- return mEglImageKHR != NULL;
-}
-
-void NativeImageSource::GlExtensionDestroy()
-{
- mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
-
- mEglImageKHR = NULL;
-}
-
-unsigned int NativeImageSource::TargetTexture()
-{
- mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
-
- return 0;
-}
-
-void NativeImageSource::PrepareTexture()
-{
-}
-
-int NativeImageSource::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const
-{
- switch (depth)
- {
- case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
- {
- // Get the default screen depth
- return ecore_x_default_depth_get(ecore_x_display_get(), ecore_x_default_screen_get());
- }
- case Dali::NativeImageSource::COLOR_DEPTH_8:
- {
- return 8;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_16:
- {
- return 16;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_24:
- {
- return 24;
- }
- case Dali::NativeImageSource::COLOR_DEPTH_32:
- {
- return 32;
- }
- default:
- {
- DALI_ASSERT_DEBUG(0 && "unknown color enum");
- return 0;
- }
- }
-}
-
-Ecore_X_Pixmap NativeImageSource::GetPixmapFromAny(Any pixmap) const
-{
- if (pixmap.Empty())
- {
- return 0;
- }
-
- // see if it is of type x11 pixmap
- if (pixmap.GetType() == typeid (Pixmap))
- {
- // get the x pixmap type
- Pixmap xpixmap = AnyCast<Pixmap>(pixmap);
-
- // cast it to a ecore pixmap type
- return static_cast<Ecore_X_Pixmap>(xpixmap);
- }
- else
- {
- return AnyCast<Ecore_X_Pixmap>(pixmap);
- }
-}
-
-void NativeImageSource::GetPixmapDetails()
-{
- int x, y;
-
- // get the width, height and depth
- ecore_x_pixmap_geometry_get( mPixmap, &x, &y, reinterpret_cast< int* >( &mWidth ), reinterpret_cast< int* >( &mHeight ) );
-
- // set whether blending is required according to pixel format based on the depth
- /* default pixel format is RGB888
- If depth = 8, Pixel::A8;
- If depth = 16, Pixel::RGB565;
- If depth = 32, Pixel::RGBA8888 */
- int depth = ecore_x_pixmap_depth_get(mPixmap);
- mBlendingRequired = ( depth == 32 || depth == 8 );
-}
-
-} // namespace Adaptor
-
-} // namespace internal
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
-#define __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <Ecore_X.h>
-
-// INTERNAL INCLUDES
-#include <native-image-source.h>
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-class EglImageExtensions;
-
-/**
- * Dali internal NativeImageSource.
- */
-class NativeImageSource
-{
-public:
-
- /**
- * Create a new NativeImageSource internally.
- * Depending on hardware the width and height may have to be a power of two.
- * @param[in] width The width of the image.
- * @param[in] height The height of the image.
- * @param[in] depth color depth of the image.
- * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
- * @return A smart-pointer to a newly allocated image.
- */
- static NativeImageSource* New(unsigned int width,
- unsigned int height,
- Dali::NativeImageSource::ColorDepth depth,
- Any nativeImageSource);
- /**
- * @copydoc Dali::NativeImageSource::GetNativeImageSource()
- */
- Any GetNativeImageSource() const;
-
- /**
- * @copydoc Dali::NativeImageSource::GetPixels()
- */
- bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const;
-
- /**
- * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
- */
- bool EncodeToFile(const std::string& filename) const;
-
- /**
- * @copydoc Dali::NativeImageSource::SetSource( Any source )
- */
- void SetSource( Any source );
-
- /**
- * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
- */
- bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth );
-
- /**
- * destructor
- */
- ~NativeImageSource();
-
- /**
- * @copydoc Dali::NativeImageSource::GlExtensionCreate()
- */
- bool GlExtensionCreate();
-
- /**
- * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
- */
- void GlExtensionDestroy();
-
- /**
- * @copydoc Dali::NativeImageSource::TargetTexture()
- */
- unsigned int TargetTexture();
-
- /**
- * @copydoc Dali::NativeImageSource::PrepareTexture()
- */
- void PrepareTexture();
-
- /**
- * @copydoc Dali::NativeImageSource::GetWidth()
- */
- unsigned int GetWidth() const
- {
- return mWidth;
- }
-
- /**
- * @copydoc Dali::NativeImageSource::GetHeight()
- */
- unsigned int GetHeight() const
- {
- return mHeight;
- }
-
- /**
- * @copydoc Dali::NativeImageSource::RequiresBlending()
- */
- bool RequiresBlending() const
- {
- return mBlendingRequired;
- }
-
- /**
- * @copydoc Dali::NativeImageInterface::GetExtension()
- */
- NativeImageInterface::Extension* GetNativeImageInterfaceExtension()
- {
- return NULL;
- }
-
-private:
-
- /**
- * Private constructor; @see NativeImageSource::New()
- * @param[in] width The width of the image.
- * @param[in] height The height of the image.
- * @param[in] colour depth of the image.
- * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
- */
- NativeImageSource(unsigned int width,
- unsigned int height,
- Dali::NativeImageSource::ColorDepth depth,
- Any nativeImageSource);
-
- /**
- * 2nd phase construction.
- */
- void Initialize();
-
- /**
- * Uses X11 to get the default depth.
- * @param depth the PixelImage depth enum
- * @return default x11 pixel depth
- */
- int GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const;
-
- /**
- * Gets the pixmap from the Any parameter
- * @param pixmap contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
- * @return pixmap x11 pixmap
- */
- Ecore_X_Pixmap GetPixmapFromAny(Any pixmap) const;
-
- /**
- * Given an existing pixmap, the function uses X to find out
- * the width, heigth and depth of that pixmap.
- */
- void GetPixmapDetails();
-
-private:
-
- unsigned int mWidth; ///< image width
- unsigned int mHeight; ///< image heights
- bool mOwnPixmap; ///< Whether we created pixmap or not
- Ecore_X_Pixmap mPixmap; ///< From Xlib
- bool mBlendingRequired; ///< Whether blending is required
- Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image
- void* mEglImageKHR; ///< From EGL extension
- EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions
-};
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "pixmap-render-surface.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-#include <X11/extensions/Xfixes.h> // for damage notify
-#include <X11/extensions/Xdamage.h> // for damage notify
-
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/threading/mutex.h>
-#include <dali/devel-api/threading/conditional-wait.h>
-
-// INTERNAL INCLUDES
-
-#include <integration-api/thread-synchronization-interface.h>
-#include <ecore-x-types.h>
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-#include <base/display-connection.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gRenderSurfaceLogFilter;
-#endif
-
-namespace ECore
-{
-
-namespace
-{
-static const int INITIAL_PRODUCE_BUFFER_INDEX = 0;
-static const int INITIAL_CONSUME_BUFFER_INDEX = 1;
-static const int BUFFER_COUNT = 2;
-}
-
-struct PixmapRenderSurface::Impl
-{
- Impl()
- : mProduceBufferIndex( INITIAL_PRODUCE_BUFFER_INDEX ),
- mConsumeBufferIndex( INITIAL_CONSUME_BUFFER_INDEX ),
- mThreadSynchronization(NULL)
- {
- for (int i = 0; i != BUFFER_COUNT; ++i)
- {
- mX11Pixmaps[i] = 0;
- mEglSurfaces[i] = 0;
- }
- }
-
- int mProduceBufferIndex;
- int mConsumeBufferIndex;
- XPixmap mX11Pixmaps[BUFFER_COUNT]; ///< X-Pixmap
- EGLSurface mEglSurfaces[BUFFER_COUNT];
- ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization
- ConditionalWait mPixmapCondition; ///< condition to share pixmap
-};
-
-PixmapRenderSurface::PixmapRenderSurface(Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- bool isTransparent)
-: EcoreXRenderSurface( positionSize, surface, name, isTransparent ),
- mImpl( new Impl )
-{
- Init( surface );
-}
-
-PixmapRenderSurface::~PixmapRenderSurface()
-{
- // release the surface if we own one
- if( mOwnSurface )
- {
- for (int i = 0; i < BUFFER_COUNT; ++i)
- {
- Ecore_X_Pixmap pixmap = mImpl->mX11Pixmaps[i];
-
- // if we did create the pixmap, delete the pixmap
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::General, "Own pixmap (%x) freed\n", pixmap );
- ecore_x_pixmap_free( pixmap );
- }
- }
-
- delete mImpl;
-}
-
-Ecore_X_Drawable PixmapRenderSurface::GetDrawable()
-{
- Ecore_X_Pixmap pixmap = 0;
- {
- ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
- pixmap = mImpl->mX11Pixmaps[mImpl->mConsumeBufferIndex];
- }
-
- return Ecore_X_Drawable( pixmap );
-}
-
-Any PixmapRenderSurface::GetSurface()
-{
- Ecore_X_Pixmap pixmap = 0;
- {
- ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
- pixmap = mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex];
- }
-
- return Any( pixmap );
-}
-
-void PixmapRenderSurface::InitializeEgl( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- eglImpl.ChooseConfig(false, mColorDepth);
-}
-
-void PixmapRenderSurface::CreateEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- for (int i = 0; i < BUFFER_COUNT; ++i)
- {
- // create the EGL surface
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
- mImpl->mEglSurfaces[i] = eglImpl.CreateSurfacePixmap( EGLNativePixmapType( pixmap ), mColorDepth ); // reinterpret_cast does not compile
- }
-}
-
-void PixmapRenderSurface::DestroyEglSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- for (int i = 0; i < BUFFER_COUNT; ++i)
- {
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
- eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[i] );
- eglImpl.DestroySurface();
- }
-}
-
-bool PixmapRenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- bool contextLost = false;
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- for (int i = 0; i < BUFFER_COUNT; ++i)
- {
- // a new surface for the new pixmap
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
- contextLost = eglImpl.ReplaceSurfacePixmap( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[i] ); // reinterpret_cast does not compile
- }
-
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
- eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[mImpl->mProduceBufferIndex] );
-
- return contextLost;
-}
-
-void PixmapRenderSurface::StartRender()
-{
-}
-
-bool PixmapRenderSurface::PreRender( EglInterface& egl, Integration::GlAbstraction&, bool )
-{
- // Nothing to do for pixmaps
- return true;
-}
-
-void PixmapRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- // flush gl instruction queue
- glAbstraction.Flush();
-
- if( mImpl->mThreadSynchronization )
- {
- mImpl->mThreadSynchronization->PostRenderStarted();
- }
-
- {
- ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
- mImpl->mConsumeBufferIndex = __sync_fetch_and_xor( &mImpl->mProduceBufferIndex, 1 ); // Swap buffer indexes.
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
- eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[mImpl->mProduceBufferIndex] );
- }
-
- // create damage for client applications which wish to know the update timing
- if( mRenderNotification )
- {
- // use notification trigger
- // Tell the event-thread to render the pixmap
- mRenderNotification->Trigger();
- }
- else
- {
- // as a fallback, send damage event.
- Ecore_X_Drawable drawable = Ecore_X_Drawable( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
-
- if( drawable )
- {
- XRectangle rect;
- XserverRegion region;
-
- rect.x = 0;
- rect.y = 0;
- rect.width = mPosition.width;
- rect.height = mPosition.height;
-
- XDisplay* display = AnyCast<XDisplay*>(displayConnection->GetDisplay());
-
- // make a fixes region as updated area
- region = XFixesCreateRegion( display, &rect, 1 );
- // add damage event to updated drawable
- Drawable xdrawable( drawable ); // ecore type is unsigned int whereas in 64bit linux Drawable is long unsigned int
- XDamageAdd( display, xdrawable, region );
- XFixesDestroyRegion( display, region );
-
- XFlush( display );
- }
- }
-
- if( mImpl->mThreadSynchronization )
- {
- mImpl->mThreadSynchronization->PostRenderWaitForCompletion();
- }
-}
-
-void PixmapRenderSurface::StopRender()
-{
- ReleaseLock();
-}
-
-void PixmapRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
-{
- mImpl->mThreadSynchronization = &threadSynchronization;
-}
-
-void PixmapRenderSurface::CreateXRenderable()
-{
- // check we're creating one with a valid size
- DALI_ASSERT_ALWAYS( mPosition.width > 0 && mPosition.height > 0 && "Pixmap size is invalid" );
-
- for (int i = 0; i < BUFFER_COUNT; ++i)
- {
- // create the pixmap
- mImpl->mX11Pixmaps[i] = ecore_x_pixmap_new(0, mPosition.width, mPosition.height, mColorDepth);
-
- // clear the pixmap
- unsigned int foreground;
- Ecore_X_GC gc;
- foreground = 0;
- gc = ecore_x_gc_new( mImpl->mX11Pixmaps[i],
- ECORE_X_GC_VALUE_MASK_FOREGROUND,
- &foreground );
-
- DALI_ASSERT_ALWAYS( gc && "CreateXRenderable(): failed to get gc" );
-
- ecore_x_drawable_rectangle_fill( mImpl->mX11Pixmaps[i], gc, 0, 0, mPosition.width, mPosition.height );
-
- DALI_ASSERT_ALWAYS( mImpl->mX11Pixmaps[i] && "Failed to create X pixmap" );
-
- // we SHOULD guarantee the xpixmap/x11 window was created in x server.
- ecore_x_sync();
-
- ecore_x_gc_free(gc);
- }
-}
-
-void PixmapRenderSurface::UseExistingRenderable( unsigned int surfaceId )
-{
-}
-
-void PixmapRenderSurface::ReleaseLock()
-{
- if( mImpl->mThreadSynchronization )
- {
- mImpl->mThreadSynchronization->PostRenderComplete();
- }
-}
-
-RenderSurface::Type PixmapRenderSurface::GetSurfaceType()
-{
- return RenderSurface::ECORE_RENDER_SURFACE;
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#ifndef DALI_PROFILE_UBUNTU
-#include <system_settings.h>
-#endif // DALI_PROFILE_UBUNTU
-#include <Elementary.h>
-
-// INTERNAL INCLUDES
-#include "system-settings.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-int GetElmAccessActionOver()
-{
-#ifndef DALI_PROFILE_UBUNTU
- // ELM_ACCESS_ACTION_OVER not available in common profile
- return ELM_ACCESS_ACTION_LAST;
-#else // DALI_PROFILE_UBUNTU
- return 0;
-#endif // DALI_PROFILE_UBUNTU
-}
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "virtual-keyboard-impl.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xlib.h>
-#include <Ecore_X.h>
-#include <algorithm>
-
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-#include <adaptor.h>
-#include <locale-utils.h>
-#include <imf-manager-impl.h>
-
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-namespace VirtualKeyboard
-{
-
-Dali::InputMethod::ActionButton gActionButtonFunction = Dali::InputMethod::ACTION_DEFAULT;
-
-Ecore_IMF_Input_Panel_Return_Key_Type actionButtonMapping(Dali::InputMethod::ActionButton actionButton )
-{
- switch( actionButton )
- {
- case InputMethod::ACTION_DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE;
- case InputMethod::ACTION_GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO;
- case InputMethod::ACTION_JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN;
- case InputMethod::ACTION_LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN;
- case InputMethod::ACTION_NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT;
- case InputMethod::ACTION_PREVIOUS: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH;
- case InputMethod::ACTION_SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND;
- case InputMethod::ACTION_SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_UNSPECIFIED: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- case InputMethod::ACTION_NONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
- }
-}
-
-void RotateTo(int angle)
-{
- // Get focus window used by Keyboard and rotate it
- Display* display = XOpenDisplay(0);
- if (display)
- {
- ::Window focusWindow;
- int revert;
- // Get Focus window
- XGetInputFocus(display, &focusWindow, &revert);
-
- ecore_x_window_prop_property_set( focusWindow,
- ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE,
- ECORE_X_ATOM_CARDINAL, 32, &angle, 1 );
- XCloseDisplay(display);
- }
-}
-
-void SetReturnKeyType( const InputMethod::ActionButton type )
-{
- Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when setting values
- Ecore_IMF_Context* imfContext = ImfManager::GetImplementation( imfManager ).GetContext();
-
- if( imfContext )
- {
- gActionButtonFunction = type;
- ecore_imf_context_input_panel_return_key_type_set( imfContext, actionButtonMapping( type ) );
- }
-}
-
-Dali::InputMethod::ActionButton GetReturnKeyType()
-{
- return gActionButtonFunction;
-}
-
-} // namespace VirtualKeyboard
-
-} // namespace Adaptor
-
-} // namespace Internal
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <window-extensions.h>
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/object/any.h>
-#include <dali/public-api/common/vector-wrapper.h>
-#include <string>
-#include <sstream>
-#include <Ecore.h>
-#include <Ecore_X.h>
-
-// INTERNAL INCLUDES
-#include <window.h>
-
-namespace
-{
-typedef std::vector< std::string > HintContainer;
-
-const char* HINT_EFFECT_NAME = "wm.comp.win.effect.enable";
-const char* HINT_ENABLE_POSTFIX = ":1";
-const char* HINT_DISABLE_POSTFIX = ":0";
-
-void Tokenize(const std::string& str, HintContainer& hints, const std::string& delimiters = ",")
-{
- std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
- std::string::size_type pos = str.find_first_of(delimiters, lastPos);
-
- while (std::string::npos != pos || std::string::npos != lastPos)
- {
- hints.push_back(str.substr(lastPos, pos - lastPos));
- lastPos = str.find_first_not_of(delimiters, pos);
- pos = str.find_first_of(delimiters, lastPos);
- }
-}
-
-void GetAppliedHints( Dali::Window window, HintContainer& hints )
-{
- Dali::Any nativeWindow = window.GetNativeHandle();
- if ( !nativeWindow.Empty() )
- {
- Ecore_X_Window ecoreWindow;
- nativeWindow.Get( ecoreWindow );
-
- unsigned char* data = NULL;
- int n = 0;
- int res = ecore_x_window_prop_property_get( ecoreWindow, ECORE_X_ATOM_E_WINDOW_AUX_HINT_SUPPORTED_LIST,
- ECORE_X_ATOM_STRING, 0, &data, &n );
-
- if ((res == 8) && (n > 0))
- {
- std::stringstream ss;
- ss << data;
- Tokenize(ss.str(), hints);
- }
-
- free(data);
- }
-}
-
-}
-
-namespace Dali
-{
-
-namespace WindowExtensions
-{
-
-void EnableEffect( Window window, bool enable )
-{
- Any nativeWindow = window.GetNativeHandle();
-
- DALI_ASSERT_ALWAYS( !nativeWindow.Empty() && "Empty window!!!" );
-
- HintContainer hints;
- GetAppliedHints( window, hints );
-
- std::stringstream ss;
- ss << hints.size() << ":" << HINT_EFFECT_NAME << (enable ? HINT_ENABLE_POSTFIX : HINT_DISABLE_POSTFIX);
-
- // Applied the window effect to the current window.
- Ecore_X_Window ecoreWindow;
- nativeWindow.Get(ecoreWindow);
- ecore_x_window_prop_property_set( ecoreWindow, ECORE_X_ATOM_E_WINDOW_AUX_HINT,
- ECORE_X_ATOM_STRING, 8,
- ss.str().c_str(), ss.str().size() + 1 );
-}
-
-bool IsEffectEnabled( Window window )
-{
- Any nativeWindow = window.GetNativeHandle();
-
- DALI_ASSERT_ALWAYS( !nativeWindow.Empty() && "Empty window!!!" );
-
- HintContainer hints;
- GetAppliedHints( window, hints );
-
- HintContainer::iterator iter = std::find( hints.begin(), hints.end(), HINT_EFFECT_NAME );
-
- return iter != hints.end();
-}
-
-} // namespace WindowExtensions
-
-} // namespace Dali
-
-
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "window-impl.h"
-
-// EXTERNAL HEADERS
-// Ecore is littered with C style cast
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <Ecore.h>
-#include <Ecore_X.h>
-
-#include <dali/integration-api/core.h>
-#include <dali/integration-api/system-overlay.h>
-#include <dali/public-api/render-tasks/render-task.h>
-#include <dali/public-api/render-tasks/render-task-list.h>
-
-// INTERNAL HEADERS
-#include <window-render-surface.h>
-#include <drag-and-drop-detector-impl.h>
-#include <ecore-indicator-impl.h>
-#include <window-visibility-observer.h>
-#include <orientation.h>
-#include <orientation-impl.h>
-
-namespace
-{
-const float INDICATOR_ANIMATION_DURATION( 0.18f ); // 180 milli seconds
-const float INDICATOR_SHOW_Y_POSITION( 0.0f );
-const float INDICATOR_HIDE_Y_POSITION( -52.0f );
-}
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_WINDOW");
-#endif
-
-/**
- * TODO: Abstract Window class out and move this into a window implementation for Ecore
- */
-struct Window::EventHandler
-{
- /**
- * Constructor
- * @param[in] window A pointer to the window class.
- */
- EventHandler( Window* window )
- : mWindow( window ),
- mWindowPropertyHandler( NULL ),
- mClientMessagehandler( NULL ),
- mWindowDeleteRequestHandler( NULL ),
- mEcoreWindow( 0 )
- {
- // store ecore window handle
- ECore::WindowRenderSurface* x11Window( dynamic_cast< ECore::WindowRenderSurface * >( mWindow->mSurface ) );
- if( x11Window )
- {
- mEcoreWindow = x11Window->GetXWindow();
- }
- DALI_ASSERT_ALWAYS( mEcoreWindow != 0 && "There is no ecore x window");
-
-#ifndef DALI_PROFILE_UBUNTU
- // set property on window to get deiconify approve client message
- unsigned int tmp = 1;
- ecore_x_window_prop_card32_set(mEcoreWindow,
- ECORE_X_ATOM_E_DEICONIFY_APPROVE,
- &tmp, 1);
-#endif // DALI_PROFILE_UBUNTU
-
- if( mWindow->mEcoreEventHander )
- {
- ecore_x_input_multi_select( mEcoreWindow );
-
- // This ensures that we catch the window close (or delete) request
- ecore_x_icccm_protocol_set( mEcoreWindow, ECORE_X_WM_PROTOCOL_DELETE_REQUEST, EINA_TRUE );
-
- mWindowPropertyHandler= ecore_event_handler_add( ECORE_X_EVENT_WINDOW_PROPERTY, EcoreEventWindowPropertyChanged, this );
- mClientMessagehandler = ecore_event_handler_add( ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, this );
- mWindowDeleteRequestHandler = ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DELETE_REQUEST, EcoreEventWindowDeleteRequest, this );
- }
- }
-
- /**
- * Destructor
- */
- ~EventHandler()
- {
- if ( mWindowPropertyHandler )
- {
- ecore_event_handler_del( mWindowPropertyHandler );
- }
- if ( mClientMessagehandler )
- {
- ecore_event_handler_del( mClientMessagehandler );
- }
- if ( mWindowDeleteRequestHandler )
- {
- ecore_event_handler_del( mWindowDeleteRequestHandler );
- }
- }
-
- // Static methods
-
- /// Called when the window properties are changed.
- static Eina_Bool EcoreEventWindowPropertyChanged( void* data, int type, void* event )
- {
- Ecore_X_Event_Window_Property* propertyChangedEvent( (Ecore_X_Event_Window_Property*)event );
- EventHandler* handler( (EventHandler*)data );
- Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
-
- if ( handler && handler->mWindow )
- {
- WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
- if ( observer && ( propertyChangedEvent->win == handler->mEcoreWindow ) )
- {
- Ecore_X_Window_State_Hint state( ecore_x_icccm_state_get( propertyChangedEvent->win ) );
-
- switch ( state )
- {
- case ECORE_X_WINDOW_STATE_HINT_WITHDRAWN:
- {
- // Window was hidden.
- observer->OnWindowHidden();
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Withdrawn\n", handler->mEcoreWindow );
- handled = ECORE_CALLBACK_DONE;
- }
- break;
-
- case ECORE_X_WINDOW_STATE_HINT_ICONIC:
- {
- // Window was iconified (minimised).
- observer->OnWindowHidden();
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Iconfied\n", handler->mEcoreWindow );
- handled = ECORE_CALLBACK_DONE;
- }
- break;
-
- case ECORE_X_WINDOW_STATE_HINT_NORMAL:
- {
- // Window was shown.
- observer->OnWindowShown();
- DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Shown\n", handler->mEcoreWindow );
- handled = ECORE_CALLBACK_DONE;
- }
- break;
-
- default:
- // Ignore
- break;
- }
- }
- }
-
- return handled;
- }
-
- /// Called when the window properties are changed.
- static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
- {
- Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Event_Client_Message* clientMessageEvent( (Ecore_X_Event_Client_Message*)event );
- EventHandler* handler( (EventHandler*)data );
-
- if (clientMessageEvent->message_type == ECORE_X_ATOM_E_DEICONIFY_APPROVE)
- {
- ECore::WindowRenderSurface* x11Window( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
- WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
-
- if ( observer && ( (unsigned int)clientMessageEvent->data.l[0] == handler->mEcoreWindow ) )
- {
- if (clientMessageEvent->data.l[1] == 0) //wm sends request message using value 0
- {
- observer->OnWindowShown();
-
- // request to approve the deiconify. render-surface should send proper event after real rendering
- if(x11Window)
- {
- x11Window->RequestToApproveDeiconify();
- }
-
- handled = ECORE_CALLBACK_DONE;
- }
- }
- }
-#endif // DALI_PROFILE_UBUNTU
-
- return handled;
- }
-
- /// Called when the window receives a delete request
- static Eina_Bool EcoreEventWindowDeleteRequest( void* data, int type, void* event )
- {
- EventHandler* handler( (EventHandler*)data );
- handler->mWindow->mDeleteRequestSignal.Emit();
- return ECORE_CALLBACK_DONE;
- }
-
- // Data
- Window* mWindow;
- Ecore_Event_Handler* mWindowPropertyHandler;
- Ecore_Event_Handler* mClientMessagehandler;
- Ecore_Event_Handler* mWindowDeleteRequestHandler;
- Ecore_X_Window mEcoreWindow;
-};
-
-
-Window* Window::New( const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent )
-{
- Window* window = new Window();
- window->mIsTransparent = isTransparent;
- window->Initialize( positionSize, name, className );
- return window;
-}
-
-void Window::SetAdaptor(Dali::Adaptor& adaptor)
-{
- DALI_ASSERT_ALWAYS( !mStarted && "Adaptor already started" );
- mStarted = true;
-
- // Only create one overlay per window
- Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor);
- Integration::Core& core = adaptorImpl.GetCore();
- mOverlay = &core.GetSystemOverlay();
-
- Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
- taskList.CreateTask();
-
- mAdaptor = &adaptorImpl;
- mAdaptor->AddObserver( *this );
-
- // Can only create the detector when we know the Core has been instantiated.
- mDragAndDropDetector = DragAndDropDetector::New();
- mAdaptor->SetDragAndDropDetector( &GetImplementation( mDragAndDropDetector ) );
-
- if( mOrientation )
- {
- mOrientation->SetAdaptor(adaptor);
- }
-
- if( mIndicator != NULL )
- {
- mIndicator->SetAdaptor(mAdaptor);
- }
-}
-
-RenderSurface* Window::GetSurface()
-{
- return mSurface;
-}
-
-void Window::ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode )
-{
- DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "visible : %d\n", visibleMode );
- DALI_ASSERT_DEBUG(mOverlay);
-
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- DALI_ASSERT_DEBUG(x11Window);
- Ecore_X_Window xWinId = x11Window->GetXWindow();
-
- mIndicatorVisible = visibleMode;
-
- if ( mIndicatorVisible == Dali::Window::VISIBLE )
- {
- // when the indicator is visible, set proper mode for indicator server according to bg mode
- if ( mIndicatorOpacityMode == Dali::Window::OPAQUE )
- {
- ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_OPAQUE);
- }
- else if ( mIndicatorOpacityMode == Dali::Window::TRANSLUCENT )
- {
- ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_TRANSLUCENT);
- }
-#if defined(DALI_PROFILE_MOBILE)
- else if ( mIndicatorOpacityMode == Dali::Window::TRANSPARENT )
- {
- ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_OPAQUE);
- }
-#endif
- }
- else
- {
- // when the indicator is not visible, set TRANSPARENT mode for indicator server
- ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_TRANSPARENT); // it means hidden indicator
- }
-
- DoShowIndicator( mIndicatorOrientation );
-}
-
-void Window::RotateIndicator(Dali::Window::WindowOrientation orientation)
-{
- DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "Orientation: %d\n", orientation );
-
- DoRotateIndicator( orientation );
-}
-
-void Window::SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacityMode )
-{
- mIndicatorOpacityMode = opacityMode;
-
- if( mIndicator != NULL )
- {
- mIndicator->SetOpacityMode( opacityMode );
- }
-}
-
-void Window::SetClass(std::string name, std::string klass)
-{
- // Get render surface's x11 window
- if( mSurface )
- {
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- ecore_x_icccm_name_class_set( x11Window->GetXWindow(), name.c_str(), klass.c_str() );
- }
- }
-}
-
-Window::Window()
-: mSurface( NULL ),
- mIndicatorVisible( Dali::Window::INVISIBLE ),
- mIndicatorIsShown( false ),
- mShowRotatedIndicatorOnClose( false ),
- mStarted( false ),
- mIsTransparent( false ),
- mWMRotationAppSet( false ),
- mEcoreEventHander( true ),
- mIsFocusAcceptable( true ),
- mVisible( true ),
- mIconified( false ),
- mOpaqueState( false ),
- mResizeEnabled( true ),
- mIndicator( NULL ),
- mIndicatorOrientation( Dali::Window::PORTRAIT ),
- mNextIndicatorOrientation( Dali::Window::PORTRAIT ),
- mIndicatorOpacityMode( Dali::Window::OPAQUE ),
- mOverlay( NULL ),
- mAdaptor( NULL ),
- mType( Dali::Window::NORMAL ),
- mEventHandler( NULL ),
- mPreferredOrientation( Dali::Window::PORTRAIT ),
- mSupportedAuxiliaryHints(),
- mAuxiliaryHints(),
- mIndicatorVisibilityChangedSignal(),
- mFocusChangedSignal(),
- mResizedSignal(),
- mDeleteRequestSignal()
-{
-}
-
-Window::~Window()
-{
- delete mEventHandler;
-
- if( mIndicator )
- {
- mOverlay->Remove( mIndicator->GetActor() );
- Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
- Dali::RenderTask indicatorTask = taskList.GetTask(0);
- mOverlay->GetOverlayRenderTasks().RemoveTask(indicatorTask);
- mIndicator->Close();
- delete mIndicator;
- }
-
- if( mAdaptor )
- {
- mAdaptor->RemoveObserver( *this );
- mAdaptor->SetDragAndDropDetector( NULL );
- mAdaptor = NULL;
- }
-
- delete mSurface;
-}
-
-void Window::Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className)
-{
- // create an X11 window by default
- Any surface;
- ECore::WindowRenderSurface* windowSurface = new ECore::WindowRenderSurface( positionSize, surface, name, className, mIsTransparent );
- windowSurface->Map();
-
- mSurface = windowSurface;
-
- mOrientation = Orientation::New(this);
-
- // create event handler for X11 window
- mEventHandler = new EventHandler( this );
-}
-
-void Window::DoShowIndicator( Dali::Window::WindowOrientation lastOrientation )
-{
- if( mIndicator == NULL )
- {
- if( mIndicatorVisible != Dali::Window::INVISIBLE )
- {
- mIndicator = new Indicator( mAdaptor, mIndicatorOrientation, this );
- mIndicator->SetOpacityMode( mIndicatorOpacityMode );
- Dali::Actor actor = mIndicator->GetActor();
- SetIndicatorActorRotation();
- mOverlay->Add(actor);
- }
- // else don't create a hidden indicator
- }
- else // Already have indicator
- {
- if( mIndicatorVisible == Dali::Window::VISIBLE )
- {
- // If we are resuming, and rotation has changed,
- if( mIndicatorIsShown == false && mIndicatorOrientation != mNextIndicatorOrientation )
- {
- // then close current indicator and open new one
- mShowRotatedIndicatorOnClose = true;
- mIndicator->Close(); // May synchronously call IndicatorClosed() callback & 1 level of recursion
- // Don't show actor - will contain indicator for old orientation.
- }
- }
- }
-
- // set indicator visible mode
- if( mIndicator != NULL )
- {
- mIndicator->SetVisible( mIndicatorVisible );
- }
-
- bool show = (mIndicatorVisible != Dali::Window::INVISIBLE );
- SetIndicatorProperties( show, lastOrientation );
- mIndicatorIsShown = show;
-}
-
-void Window::DoRotateIndicator( Dali::Window::WindowOrientation orientation )
-{
- if( mIndicatorIsShown )
- {
- mShowRotatedIndicatorOnClose = true;
- mNextIndicatorOrientation = orientation;
- mIndicator->Close(); // May synchronously call IndicatorClosed() callback
- }
- else
- {
- // Save orientation for when the indicator is next shown
- mShowRotatedIndicatorOnClose = false;
- mNextIndicatorOrientation = orientation;
- }
-}
-
-void Window::SetIndicatorProperties( bool isShow, Dali::Window::WindowOrientation lastOrientation )
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
-
- int show_state = static_cast<int>( isShow );
- ecore_x_window_prop_property_set( win,
- ECORE_X_ATOM_E_ILLUME_INDICATOR_STATE,
- ECORE_X_ATOM_CARDINAL, 32, &show_state, 1);
-
- if ( isShow )
- {
- ecore_x_e_illume_indicator_state_set(win, ECORE_X_ILLUME_INDICATOR_STATE_ON);
- }
- else
- {
- ecore_x_e_illume_indicator_state_set(win, ECORE_X_ILLUME_INDICATOR_STATE_OFF);
- }
- }
-}
-
-void Window::IndicatorTypeChanged(Indicator::Type type)
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Window win = x11Window->GetXWindow();
- switch(type)
- {
- case Indicator::INDICATOR_TYPE_1:
- ecore_x_e_illume_indicator_type_set( win, ECORE_X_ILLUME_INDICATOR_TYPE_1 );
- break;
-
- case Indicator::INDICATOR_TYPE_2:
- ecore_x_e_illume_indicator_type_set( win, ECORE_X_ILLUME_INDICATOR_TYPE_2 );
- break;
-
- case Indicator::INDICATOR_TYPE_UNKNOWN:
- default:
- break;
- }
-#endif // DALI_PROFILE_UBUNTU
- }
-}
-
-void Window::IndicatorClosed( IndicatorInterface* indicator )
-{
- DALI_LOG_TRACE_METHOD( gWindowLogFilter );
-
- if( mShowRotatedIndicatorOnClose )
- {
- Dali::Window::WindowOrientation currentOrientation = mIndicatorOrientation;
- mIndicator->Open(mNextIndicatorOrientation);
- mIndicatorOrientation = mNextIndicatorOrientation;
- SetIndicatorActorRotation();
- DoShowIndicator(currentOrientation);
- }
-}
-
-void Window::IndicatorVisibilityChanged(bool isVisible)
-{
- mIndicatorVisibilityChangedSignal.Emit(isVisible);
-}
-
-void Window::SetIndicatorActorRotation()
-{
- DALI_LOG_TRACE_METHOD( gWindowLogFilter );
- DALI_ASSERT_DEBUG( mIndicator != NULL );
-
- Dali::Actor actor = mIndicator->GetActor();
- switch( mIndicatorOrientation )
- {
- case Dali::Window::PORTRAIT:
- actor.SetParentOrigin( ParentOrigin::TOP_CENTER );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(0), Vector3::ZAXIS );
- break;
- case Dali::Window::PORTRAIT_INVERSE:
- actor.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(180), Vector3::ZAXIS );
- break;
- case Dali::Window::LANDSCAPE:
- actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(270), Vector3::ZAXIS );
- break;
- case Dali::Window::LANDSCAPE_INVERSE:
- actor.SetParentOrigin( ParentOrigin::CENTER_RIGHT );
- actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
- actor.SetOrientation( Degree(90), Vector3::ZAXIS );
- break;
- }
-}
-
-void Window::Raise()
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- ecore_x_window_raise(win);
- }
-}
-
-void Window::Lower()
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- ecore_x_window_lower(win);
- }
-}
-
-void Window::Activate()
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- ecore_x_netwm_client_active_request(ecore_x_window_root_get(win), win, 1 /* request type, 1:application, 2:pager */, 0);
- }
-}
-
-Dali::DragAndDropDetector Window::GetDragAndDropDetector() const
-{
- return mDragAndDropDetector;
-}
-
-Dali::Any Window::GetNativeHandle() const
-{
- if(mEventHandler)
- {
- return mEventHandler->mEcoreWindow;
- }
- else
- {
- return Dali::Any();
- }
-}
-
-void Window::OnStart()
-{
- ShowIndicator( mIndicatorVisible );
-}
-
-void Window::OnPause()
-{
-}
-
-void Window::OnResume()
-{
- // resume indicator status
- if( mIndicator != NULL )
- {
- // Restore own indicator opacity
- // Send opacity mode to indicator service when app resumed
- mIndicator->SetOpacityMode( mIndicatorOpacityMode );
- }
-}
-
-void Window::OnStop()
-{
- if( mIndicator )
- {
- mIndicator->Close();
- }
-
- delete mIndicator;
- mIndicator = NULL;
-}
-
-void Window::OnDestroy()
-{
- mAdaptor = NULL;
-}
-
-void Window::AddAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- bool found = false;
-
- for( std::size_t i=0; i<mAvailableOrientations.size(); i++ )
- {
- if(mAvailableOrientations[i] == orientation)
- {
- found = true;
- break;
- }
- }
-
- if( ! found )
- {
- mAvailableOrientations.push_back(orientation);
- SetAvailableOrientations( mAvailableOrientations );
- }
-}
-
-void Window::RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation)
-{
- for( std::vector<Dali::Window::WindowOrientation>::iterator iter = mAvailableOrientations.begin();
- iter != mAvailableOrientations.end(); ++iter )
- {
- if( *iter == orientation )
- {
- mAvailableOrientations.erase( iter );
- break;
- }
- }
- SetAvailableOrientations( mAvailableOrientations );
-}
-
-void Window::SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations)
-{
- DALI_ASSERT_ALWAYS( mAvailableOrientations.size() <= 4 && "Incorrect number of available orientations" );
-
- mAvailableOrientations = orientations;
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
- if( ! mWMRotationAppSet )
- {
- mWMRotationAppSet = true;
- ecore_x_e_window_rotation_app_set(ecoreWindow, EINA_TRUE);
- }
-
- int rotations[4];
- for( std::size_t i=0; i<mAvailableOrientations.size(); i++ )
- {
- rotations[i] = static_cast<int>(mAvailableOrientations[i]);
- }
- ecore_x_e_window_rotation_available_rotations_set(ecoreWindow, rotations, mAvailableOrientations.size() );
-#endif // DALI_PROFILE_UBUNTU
- }
-}
-
-const std::vector<Dali::Window::WindowOrientation>& Window::GetAvailableOrientations()
-{
- return mAvailableOrientations;
-}
-
-void Window::SetPreferredOrientation(Dali::Window::WindowOrientation orientation)
-{
- mPreferredOrientation = orientation;
-
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
-
- if( ! mWMRotationAppSet )
- {
- mWMRotationAppSet = true;
- ecore_x_e_window_rotation_app_set(ecoreWindow, EINA_TRUE);
- }
-
- ecore_x_e_window_rotation_preferred_rotation_set(ecoreWindow, orientation);
-#endif // DALI_PROFILE_UBUNTU
- }
-}
-
-Dali::Window::WindowOrientation Window::GetPreferredOrientation()
-{
- return mPreferredOrientation;
-}
-
-void Window::SetAcceptFocus( bool accept )
-{
- mIsFocusAcceptable = accept;
-}
-
-bool Window::IsFocusAcceptable() const
-{
- return mIsFocusAcceptable;
-}
-
-void Window::Show()
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- ecore_x_window_show( win );
-
- // Need an update request
- if( mAdaptor )
- {
- mAdaptor->RequestUpdateOnce();
- }
- }
-}
-
-void Window::Hide()
-{
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- ecore_x_window_hide( win );
- }
-}
-
-bool Window::IsVisible() const
-{
- bool visible = false;
-
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
- Ecore_X_Window win = x11Window->GetXWindow();
- visible = static_cast< bool >( ecore_x_window_visible_get( win ) );
- }
- return visible;
-}
-
-void Window::RotationDone( int orientation, int width, int height )
-{
- // Tell window manager we're done
- ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
- if( x11Window )
- {
-#ifndef DALI_PROFILE_UBUNTU
- Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
- Ecore_X_Window root = ecore_x_window_root_get(ecoreWindow);
-
- /**
- * send rotation done message to wm, even if window is already rotated.
- * that's why wm must be wait for comming rotation done message
- * after sending rotation request.
- */
- ecore_x_e_window_rotation_change_done_send(root, ecoreWindow, orientation, width, height);
-
- /**
- * set rotate window property
- */
- int angles[2] = { orientation, orientation };
- ecore_x_window_prop_property_set( ecoreWindow,
- ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE,
- ECORE_X_ATOM_CARDINAL, 32, &angles, 2 );
-
- mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( width, height ) );
-
- // Emit signal
- mResizedSignal.Emit( Dali::Window::WindowSize( width, height ) );
-
- mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( width, height ) );
-#endif // DALI_PROFILE_UBUNTU
- }
-}
-
-void Window::SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode )
-{
- mIndicatorVisible = mode;
-}
-
-unsigned int Window::GetSupportedAuxiliaryHintCount() const
-{
- return 0;
-}
-
-std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
-{
- return std::string();
-}
-
-unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
-{
- return -1;
-}
-
-bool Window::RemoveAuxiliaryHint( unsigned int id )
-{
- return false;
-}
-
-bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
-{
- return false;
-}
-
-std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
-{
- return std::string();
-}
-
-unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
-{
- return -1;
-}
-
-void Window::SetInputRegion( const Rect< int >& inputRegion )
-{
-}
-
-void Window::SetType( Dali::Window::Type type )
-{
- mType = type;
-}
-
-Dali::Window::Type Window::GetType() const
-{
- return mType;
-}
-
-bool Window::SetNotificationLevel( Dali::Window::NotificationLevel::Type level )
-{
- return false;
-}
-
-Dali::Window::NotificationLevel::Type Window::GetNotificationLevel() const
-{
- return Dali::Window::NotificationLevel::NONE;
-}
-
-void Window::SetOpaqueState( bool opaque )
-{
- mOpaqueState = opaque;
-}
-
-bool Window::IsOpaqueState() const
-{
- return mOpaqueState;
-}
-
-bool Window::SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode)
-{
- return false;
-}
-
-Dali::Window::ScreenOffMode::Type Window::GetScreenOffMode() const
-{
- return Dali::Window::ScreenOffMode::TIMEOUT;
-}
-
-bool Window::SetBrightness( int brightness )
-{
- return false;
-}
-
-int Window::GetBrightness() const
-{
- return 0;
-}
-
-void Window::SetSize( Dali::Window::WindowSize size )
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.width != size.GetWidth() || positionSize.height != size.GetHeight() )
- {
- positionSize.width = size.GetWidth();
- positionSize.height = size.GetHeight();
-
- mSurface->MoveResize( positionSize );
-
- mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
-
- // Emit signal
- mResizedSignal.Emit( Dali::Window::WindowSize( positionSize.width, positionSize.height ) );
-
- mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
- }
-}
-
-Dali::Window::WindowSize Window::GetSize() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowSize( positionSize.width, positionSize.height );
-}
-
-void Window::SetPosition( Dali::Window::WindowPosition position )
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- if( positionSize.x != position.GetX() || positionSize.y != position.GetY() )
- {
- positionSize.x = position.GetX();
- positionSize.y = position.GetY();
-
- mSurface->MoveResize( positionSize );
- }
-}
-
-Dali::Window::WindowPosition Window::GetPosition() const
-{
- PositionSize positionSize = mSurface->GetPositionSize();
-
- return Dali::Window::WindowPosition( positionSize.x, positionSize.y );
-}
-
-void Window::SetTransparency( bool transparent )
-{
-}
-
-} // Adaptor
-
-} // Internal
-
-} // Dali
-
-#pragma GCC diagnostic pop
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "window-render-surface.h"
-
-// EXTERNAL INCLUDES
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-#include <X11/extensions/Xfixes.h> // for damage notify
-#include <X11/extensions/Xdamage.h> // for damage notify
-
-#include <dali/integration-api/gl-abstraction.h>
-#include <dali/integration-api/debug.h>
-
-// INTERNAL INCLUDES
-
-#include <ecore-x-types.h>
-#include <trigger-event.h>
-#include <gl/egl-implementation.h>
-#include <base/display-connection.h>
-
-namespace Dali
-{
-
-#if defined(DEBUG_ENABLED)
-extern Debug::Filter* gRenderSurfaceLogFilter;
-#endif
-
-namespace ECore
-{
-
-namespace
-{
-
-const int MINIMUM_DIMENSION_CHANGE( 1 ); ///< Minimum change for window to be considered to have moved
-
-} // unnamed namespace
-
-WindowRenderSurface::WindowRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- const std::string& className,
- bool isTransparent)
-: EcoreXRenderSurface( positionSize, surface, name, isTransparent ),
- mX11Window( 0 ),
- mNeedToApproveDeiconify(false),
- mClassName(className)
-{
- DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n" );
- Init( surface );
-}
-
-WindowRenderSurface::~WindowRenderSurface()
-{
- if( mOwnSurface )
- {
- ecore_x_window_free( mX11Window );
- }
-}
-
-Ecore_X_Drawable WindowRenderSurface::GetDrawable()
-{
- // already an e-core type
- return static_cast< Ecore_X_Drawable >( mX11Window );
-}
-
-Any WindowRenderSurface::GetSurface()
-{
- // already an e-core type
- return Any( mX11Window );
-}
-
-Ecore_X_Window WindowRenderSurface::GetXWindow()
-{
- return mX11Window;
-}
-
-void WindowRenderSurface::RequestToApproveDeiconify()
-{
- mNeedToApproveDeiconify = true;
-}
-
-void WindowRenderSurface::InitializeEgl( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
-
- eglImpl.ChooseConfig(true, mColorDepth);
-}
-
-void WindowRenderSurface::CreateEglSurface( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
-
- // create the EGL surface
- // need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XWindow window( mX11Window );
- eglImpl.CreateSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( window ), mColorDepth );
-}
-
-void WindowRenderSurface::DestroyEglSurface( EglInterface& eglIf )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
- eglImpl.DestroySurface();
-}
-
-bool WindowRenderSurface::ReplaceEGLSurface( EglInterface& egl )
-{
- DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
-
- // need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
- XWindow window( mX11Window );
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
-
- return eglImpl.ReplaceSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( window ) );
-}
-
-void WindowRenderSurface::MoveResize( Dali::PositionSize positionSize )
-{
- bool needToMove = false;
- bool needToResize = false;
-
- // check moving
- if( (fabs(positionSize.x - mPosition.x) > MINIMUM_DIMENSION_CHANGE) ||
- (fabs(positionSize.y - mPosition.y) > MINIMUM_DIMENSION_CHANGE) )
- {
- needToMove = true;
- }
-
- // check resizing
- if( (fabs(positionSize.width - mPosition.width) > MINIMUM_DIMENSION_CHANGE) ||
- (fabs(positionSize.height - mPosition.height) > MINIMUM_DIMENSION_CHANGE) )
- {
- needToResize = true;
- }
-
- if( needToMove && needToResize)
- {
- ecore_x_window_move_resize(mX11Window, positionSize.x, positionSize.y, positionSize.width, positionSize.height);
- mPosition = positionSize;
- }
- else if(needToMove)
- {
- ecore_x_window_move(mX11Window, positionSize.x, positionSize.y);
- mPosition = positionSize;
- }
- else if (needToResize)
- {
- ecore_x_window_resize(mX11Window, positionSize.width, positionSize.height);
- mPosition = positionSize;
- }
-
-}
-
-void WindowRenderSurface::Map()
-{
- ecore_x_window_show(mX11Window);
-}
-
-void WindowRenderSurface::StartRender()
-{
-}
-
-bool WindowRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
-{
- // nothing to do for windows
- return true;
-}
-
-void WindowRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
-{
- Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
- eglImpl.SwapBuffers();
-
- // When the window is deiconified, it approves the deiconify operation to window manager after rendering
- if(mNeedToApproveDeiconify)
- {
- // SwapBuffer is desychronized. So make sure to sychronize when window is deiconified.
- glAbstraction.Finish();
-
- XDisplay* display = AnyCast<XDisplay *>(displayConnection->GetDisplay());
-
-#ifndef DALI_PROFILE_UBUNTU
- /* client sends immediately reply message using value 1 */
- XEvent xev;
-
- xev.xclient.window = mX11Window;
- xev.xclient.type = ClientMessage;
- xev.xclient.message_type = ECORE_X_ATOM_E_DEICONIFY_APPROVE;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = mX11Window;
- xev.xclient.data.l[1] = 1;
- xev.xclient.data.l[2] = 0;
- xev.xclient.data.l[3] = 0;
- xev.xclient.data.l[4] = 0;
-
- XSendEvent(display, mX11Window, false, ECORE_X_EVENT_MASK_WINDOW_CONFIGURE, &xev);
-#endif // DALI_PROFILE_UBUNTU
-
- XSync(display, false);
-
- mNeedToApproveDeiconify = false;
- }
-}
-
-void WindowRenderSurface::StopRender()
-{
-}
-
-void WindowRenderSurface::SetViewMode( ViewMode viewMode )
-{
- Ecore_X_Atom viewModeAtom( ecore_x_atom_get( "_E_COMP_3D_APP_WIN" ) );
-
- if( viewModeAtom != None )
- {
- unsigned int value( static_cast<unsigned int>( viewMode ) );
- ecore_x_window_prop_card32_set( mX11Window, viewModeAtom, &value, 1 );
- }
-}
-
-void WindowRenderSurface::CreateXRenderable()
-{
- // if width or height are zero, go full screen.
- if ( (mPosition.width == 0) || (mPosition.height == 0) )
- {
- // Default window size == screen size
- mPosition.x = 0;
- mPosition.y = 0;
-
- ecore_x_screen_size_get( ecore_x_default_screen_get(), &mPosition.width, &mPosition.height );
- }
-
- if(mColorDepth == COLOR_DEPTH_32)
- {
- // create 32 bit window
- mX11Window = ecore_x_window_argb_new( 0, mPosition.x, mPosition.y, mPosition.width, mPosition.height );
- }
- else
- {
- // create 24 bit window
- mX11Window = ecore_x_window_new( 0, mPosition.x, mPosition.y, mPosition.width, mPosition.height );
- }
-
- if ( mX11Window == 0 )
- {
- DALI_ASSERT_ALWAYS(0 && "Failed to create X window");
- }
-
- // set up window title which will be helpful for debug utitilty
- ecore_x_icccm_title_set( mX11Window, mTitle.c_str() );
- ecore_x_netwm_name_set( mX11Window, mTitle.c_str() );
- ecore_x_icccm_name_class_set( mX11Window, mTitle.c_str(), mClassName.c_str() );
-
- // set up etc properties to match with ecore-evas
- char *id = NULL;
- if( ( id = getenv("DESKTOP_STARTUP_ID") ) )
- {
- ecore_x_netwm_startup_id_set( mX11Window, id );
- }
-
- ecore_x_icccm_hints_set( mX11Window,
- 1, // accepts_focus
- ECORE_X_WINDOW_STATE_HINT_NORMAL, // initial_state
- 0, // icon_pixmap
- 0, // icon_mask
- 0, // icon_window
- 0, // window_group
- 0 ); // is_urgent
-
- // we SHOULD guarantee the x11 window was created in x server.
- ecore_x_sync();
-}
-
-void WindowRenderSurface::UseExistingRenderable( unsigned int surfaceId )
-{
- mX11Window = static_cast< Ecore_X_Window >( surfaceId );
-}
-
-void WindowRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& /* threadSynchronization */ )
-{
- // Nothing to do.
-}
-
-void WindowRenderSurface::ReleaseLock()
-{
- // Nothing to do.
-}
-
-} // namespace ECore
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
-#define __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
-
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <ecore-x-render-surface.h>
-
-namespace Dali
-{
-
-namespace ECore
-{
-
-/**
- * @copydoc Dali::ECore::EcoreXRenderSurface.
- * Window specialization.
- */
-class WindowRenderSurface : public EcoreXRenderSurface
-{
-public:
-
- /**
- * Uses an X11 surface to render to.
- * @param [in] positionSize the position and size of the surface
- * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
- * @param [in] name optional name of surface passed in
- * @param [in] className optional class name of the surface passed in
- * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
- */
- WindowRenderSurface( Dali::PositionSize positionSize,
- Any surface,
- const std::string& name,
- const std::string& className,
- bool isTransparent = false );
-
- /**
- * @copydoc Dali::ECore::EcoreXRenderSurface::~EcoreXRenderSurface
- */
- virtual ~WindowRenderSurface();
-
-public: // API
-
- /**
- * @copydoc Dali::RenderSurface::GetDrawable()
- */
- virtual Ecore_X_Drawable GetDrawable();
-
- /**
- * Request to approve deiconify operation
- * If it is requested, it will send ECORE_X_ATOM_E_DEICONIFY_APPROVE event to window manager after rendering
- */
- void RequestToApproveDeiconify();
-
- /**
- * Map window
- */
- virtual void Map();
-
- /**
- * @copydoc Dali::ECore::EcoreXRenderSurface::GetSurface()
- */
- virtual Any GetSurface();
-
- /**
- * @copydoc Dali::ECore::EcoreXRenderSurface::GetXWindow()
- */
- virtual Ecore_X_Window GetXWindow();
-
-public: // from Dali::RenderSurface
-
- /**
- * @copydoc Dali::RenderSurface::InitializeEgl()
- */
- virtual void InitializeEgl( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::CreateEglSurface()
- */
- virtual void CreateEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::DestroyEglSurface()
- */
- virtual void DestroyEglSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
- */
- virtual bool ReplaceEGLSurface( EglInterface& egl );
-
- /**
- * @copydoc Dali::RenderSurface::MoveResize()
- */
- virtual void MoveResize( Dali::PositionSize positionSize);
-
- /**
- * @copydoc Dali::RenderSurface::SetViewMode()
- */
- void SetViewMode( ViewMode viewMode );
-
- /**
- * @copydoc Dali::RenderSurface::StartRender()
- */
- virtual void StartRender();
-
- /**
- * @copydoc Dali::RenderSurface::PreRender()
- */
- virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::PostRender()
- */
- virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
-
- /**
- * @copydoc Dali::RenderSurface::StopRender()
- */
- virtual void StopRender();
-
- /**
- * @copydoc Dali::RenderSurface::SetThreadSynchronization
- */
- virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
-
- /**
- * @copydoc Dali::RenderSurface::ReleaseLock()
- */
- virtual void ReleaseLock();
-
-protected:
-
- /**
- * Create XWindow
- */
- virtual void CreateXRenderable();
-
- /**
- * @copydoc Dali::Internal::Adaptor::ECore::EcoreXRenderSurface::UseExistingRenderable
- */
- virtual void UseExistingRenderable( unsigned int surfaceId );
-
-private: // Data
-
- Ecore_X_Window mX11Window; ///< X-Window
- bool mNeedToApproveDeiconify; ///< Whether need to send ECORE_X_ATOM_E_DEICONIFY_APPROVE event
- std::string mClassName; ///< The class name of the window
-
-}; // class WindowRenderSurface
-
-} // namespace ECore
-
-} // namespace Dali
-
-#endif // __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
# Adaptor directories are included in order of most-specific to least specific:
INCLUDE_DIRECTORIES(
../../../
- ../../../adaptors/mobile
- ../../../adaptors/x11
- ../../../adaptors/common
- ../../../adaptors/base
- ../../../adaptors/public-api
- ../../../adaptors/devel-api
- ../../../adaptors/devel-api/adaptor-framework
- ../../../adaptors/public-api/adaptor-framework
- ../../../adaptors/tizen
- ../../../adaptors/ubuntu
- ../../../text
../../../third-party/image-resampler
${${CAPI_LIB}_INCLUDE_DIRS}
../dali-adaptor/dali-test-suite-utils
#include "image-loaders.h"
#include <dali-test-suite-utils.h>
-#include <adaptors/common/pixel-buffer-impl.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
AutoCloseFile::AutoCloseFile( FILE *fp )
: filePtr( fp )
#include <dali/dali.h>
#include <dali/integration-api/bitmap.h>
#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
-#include "platform-abstractions/tizen/image-loaders/image-loader-input.h"
+#include <dali/internal/imaging/common/image-loader-input.h>
// Simple structure to close the file when finished with it.
struct AutoCloseFile
#include <stdlib.h>
#include <dali-test-suite-utils.h>
-#include "platform-abstractions/tizen/image-loaders/loader-bmp.h"
+#include <dali/internal/imaging/common/loader-bmp.h>
#include "image-loaders.h"
using namespace Dali;
#include <stdlib.h>
#include <getopt.h>
#include <dali/dali.h>
-#include <command-line-options.h>
+#include <dali/internal/system/common/command-line-options.h>
#include <dali-test-suite-utils.h>
using namespace Dali;
#include <stdlib.h>
#include <vector>
#include <dali-test-suite-utils.h>
-#include "platform-abstractions/tizen/image-loaders/loader-ktx.h"
-#include "platform-abstractions/tizen/image-loaders/loader-astc.h"
+#include <dali/internal/imaging/common/loader-ktx.h>
+#include <dali/internal/imaging/common/loader-astc.h>
// INTERNAL INCLUDES
#include "image-loaders.h"
#include <stdint.h>
#include <dali/dali.h>
#include <dali-test-suite-utils.h>
-#include <dali/internal/text-abstraction/font-client-helper.h>
+#include <dali/internal/text/text-abstraction/font-client-helper.h>
using namespace Dali;
#include <stdlib.h>
#include <dali-test-suite-utils.h>
-#include "platform-abstractions/tizen/image-loaders/loader-gif.h"
+#include <dali/internal/imaging/common/loader-gif.h>
#include "image-loaders.h"
using namespace Dali;
#include <stdlib.h>
#include <dali-test-suite-utils.h>
-#include "platform-abstractions/tizen/image-loaders/loader-ico.h"
+#include <dali/internal/imaging/common/loader-ico.h>
#include "image-loaders.h"
using namespace Dali;
*/
#include <dali-test-suite-utils.h>
-#include "platform-abstractions/portable/image-operations.h"
+#include <dali/internal/imaging/common/image-operations.h>
#include <dali/devel-api/common/ref-counted-dali-vector.h>
#include <sys/mman.h>
// Internal headers are allowed here
-#include <platform-abstractions/portable/pixel-manipulation.h>
+#include <dali/internal/imaging/common/pixel-manipulation.h>
using namespace Dali;
using namespace Dali::Internal::Adaptor;
#include <iostream>
#include <dali.h>
#include <dali-test-suite-utils.h>
-#include <lifecycle-controller.h>
+#include <dali/devel-api/adaptor-framework/lifecycle-controller.h>
-#include <lifecycle-controller-impl.h>
+#include <dali/internal/adaptor/common/lifecycle-controller-impl.h>
using namespace Dali;
#include <dali/dali.h>
#include <dali-test-suite-utils.h>
#include <adaptor-test-application.h>
-#include <tilt-sensor-impl.h>
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+#include <dali/internal/sensor/common/tilt-sensor-factory.h>
using namespace Dali;
TiltSensor GetTiltSensor()
{
- return Internal::Adaptor::TiltSensor::New();
+ return Dali::TiltSensor(Dali::Internal::Adaptor::TiltSensorFactory::Create());
}
bool ecore_timer_running = false;
#include "utc-image-loading-common.h"
-#include "platform-abstractions/portable/image-operations.h"
+#include <dali/internal/imaging/common/image-operations.h>
using Dali::Internal::Platform::ApplyAttributesToBitmap;
#include <ctime>
#include <dali/dali.h>
#include <dali-test-suite-utils.h>
-#include "tizen-platform-abstraction.h"
+#include <dali/internal/legacy/common/tizen-platform-abstraction.h>
using namespace Dali;
using namespace Dali::Integration;
############# INCLUDE FILE LISTS #############
-# Base Adaptor
-base_adaptor_src_dir = ../../../adaptors/base
-include ../../../adaptors/base/file.list
+# New structure includes
+include ./module.list
-# Platform Abstraction
-tizen_platform_abstraction_src_dir = ../../../platform-abstractions/tizen
-portable_platform_abstraction_src_dir = ../../../platform-abstractions/portable
-include ../../../platform-abstractions/tizen/file.list
-
-# Text Abstraction
-text_src_dir = ../../../text
-include ../../../text/file.list
-
-# Integration
-adaptor_integration_api_dir = ../../../adaptors/integration-api
-include ../../../adaptors/integration-api/file.list
-
-# Internal Common
-adaptor_common_dir = ../../../adaptors/common
-include ../../../adaptors/common/file.list
-
-# ECore Common
-adaptor_ecore_common_dir = ../../../adaptors/ecore/common
-include ../../../adaptors/ecore/common/file.list
+pkgconfigdir = $(libdir)/pkgconfig
-# Wayland
-if WAYLAND
-## Use ecore_wayland
-adaptor_ecore_wayland_dir = ../../../adaptors/ecore/wayland
-include ../../../adaptors/ecore/wayland/file.list
+if ENABLE_CXX03_ABI
+pkgconfig_DATA = dali-adaptor-cxx03.pc dali-adaptor-integration-cxx03.pc
else
-# X11
-adaptor_x11_dir = ../../../adaptors/x11
-include ../../../adaptors/x11/file.list
+pkgconfig_DATA = dali-adaptor.pc dali-adaptor-integration.pc
endif
-# Ubuntu
+# sources
if UBUNTU_PROFILE
-adaptor_ubuntu_dir = ../../../adaptors/ubuntu
-include ../../../adaptors/ubuntu/file.list
-else
+LIBDALI_ADAPTOR_LA_SOURCES = \
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_ubuntu_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_ubuntu_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_ubuntu_x11_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_ubuntu_gl_src_files) \
+ $(adaptor_graphics_ubuntu_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_ubuntu_x11_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_ubuntu_src_files) \
+ $(adaptor_input_ubuntu_x11_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_ubuntu_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_ubuntu_src_files) \
+ $(adaptor_system_ubuntu_x11_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_text_ubuntu_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_ubuntu_x11_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
-# Tizen
-adaptor_tizen_dir = ../../../adaptors/tizen
-if USE_APPFW_EFL_BASE
-include ../../../adaptors/tizen/file-3.list
-else
-include ../../../adaptors/tizen/file.list
-endif
endif
-# Mobile
-adaptor_mobile_dir = ../../../adaptors/mobile
-include ../../../adaptors/mobile/file.list
-
-# WEARABLE
-adaptor_wearable_dir = ../../../adaptors/wearable
-include ../../../adaptors/wearable/file.list
-
-# TV
-adaptor_tv_dir = ../../../adaptors/tv
-include ../../../adaptors/tv/file.list
-
-# Public API
-adaptor_public_api_dir = ../../../adaptors/public-api
-include ../../../adaptors/public-api/file.list
-
-# Devel API ( for use by Toolkit)
-adaptor_devel_api_dir = ../../../adaptors/devel-api
-include ../../../adaptors/devel-api/file.list
-
-
-# Static libraries
-static_libraries_libunibreak_src_dir = ../../../text/dali/internal/libunibreak
-include ../../../text/dali/internal/libunibreak/file.list
-
-static_libraries_glyphy_src_dir = ../../../text/dali/internal/glyphy
-include ../../../text/dali/internal/glyphy/file.list
-
-static_libraries_image_resampler_src_dir = ../../../third-party/image-resampler
-include ../../../third-party/image-resampler/file.list
-
-# Package doc
-package_doxy_dir = ../../../doc
-include ../../../doc/file.list
-
-############# source files #############
-adaptor_internal_src_files = $(adaptor_tizen_framework_efl_src_files) \
- $(adaptor_ecore_common_internal_src_files)
-
-# COMMON
-if COMMON_PROFILE
-
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_default_profile_src_files) \
- $(adaptor_tizen_internal_src_files) \
- $(adaptor_tizen_internal_non_mobile_src_files) \
- $(static_libraries_libunibreak_src_files)
-
-if WAYLAND
-
-if USE_ECORE_WAYLAND
-adaptor_internal_src_files += $(adaptor_ecore_wayland_tizen_internal_src_files) \
- $(adaptor_ecore_wayland_internal_default_profile_src_files)
-else
-adaptor_internal_src_files += $(adaptor_wayland_tizen_internal_src_files)
-endif # USE_ECORE_WAYLAND
-
-adaptor_internal_src_files += $(adaptor_tizen_internal_egl_extension_src_files) \
- $(adaptor_tizen_internal_native_image_src_files)
-else
-adaptor_internal_src_files += $(adaptor_x11_tizen_internal_src_files) \
- $(adaptor_common_internal_egl_extension_src_files) \
- $(adaptor_x11_internal_default_profile_src_files)
-endif # WAYLAND
-endif # COMMON_PROFILE
-
-
-# UBUNTU
-if UBUNTU_PROFILE
-
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_default_profile_src_files) \
- $(adaptor_ubuntu_internal_src_files) \
- $(adaptor_x11_ubuntu_internal_src_files) \
- $(adaptor_x11_internal_default_profile_src_files) \
- $(static_libraries_libunibreak_src_files) \
- $(adaptor_common_internal_egl_extension_src_files)
-
-endif # UBUNTU_PROFILE
-
-
-# MOBILE
+# $(adaptor_accessibility_tizen_common_src_files)
if MOBILE_PROFILE
+LIBDALI_ADAPTOR_LA_SOURCES = \
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_tizen_mobile_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_tizen_src_files) \
+ $(adaptor_adaptor_tizen_wayland_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_tizen_wayland_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_tizen_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_tizen_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_tizen_wayland_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_tizen_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_tizen_mobile_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_tizen_mobile_src_files) \
+ $(adaptor_window_system_tizen_src_files) \
+ $(adaptor_window_system_tizen_wayland_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_mobile_profile_src_files) \
- $(adaptor_tizen_internal_src_files) \
- $(static_libraries_libunibreak_src_files)
-
-if WAYLAND
-
-if USE_ECORE_WAYLAND
-adaptor_internal_src_files += $(adaptor_ecore_wayland_tizen_internal_src_files)
-else
-adaptor_internal_src_files += $(adaptor_wayland_tizen_internal_src_files)
-endif # USE_ECORE_WAYLAND
-
-adaptor_internal_src_files += $(adaptor_tizen_internal_egl_extension_src_files) \
- $(adaptor_tizen_internal_native_image_src_files) \
- $(adaptor_common_internal_wayland_mobile_profile_src_files)
-else
-adaptor_internal_src_files += $(adaptor_x11_tizen_internal_src_files) \
- $(adaptor_common_internal_egl_extension_src_files) \
- $(adaptor_common_internal_x_mobile_profile_src_files)
-endif # WAYLAND
-
-endif # MOBILE_PROFILE
-
-# WEARABLE
-if WEARABLE_PROFILE
+endif
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_mobile_profile_src_files) \
- $(adaptor_tizen_internal_src_files) \
- $(static_libraries_libunibreak_src_files)
-if WAYLAND
+# $(adaptor_accessibility_tizen_common_src_files)
-if USE_ECORE_WAYLAND
-adaptor_internal_src_files += $(adaptor_ecore_wayland_tizen_internal_src_files)
-else
-adaptor_internal_src_files += $(adaptor_wayland_tizen_internal_src_files)
-endif # USE_ECORE_WAYLAND
-
-adaptor_internal_src_files += $(adaptor_tizen_internal_egl_extension_src_files) \
- $(adaptor_tizen_internal_native_image_src_files) \
- $(adaptor_tizen_internal_capture_src_files) \
- $(adaptor_internal_wearable_profile_src_files) \
- $(adaptor_common_internal_wayland_mobile_profile_src_files)
-else
-adaptor_internal_src_files += $(adaptor_x11_tizen_internal_src_files) \
- $(adaptor_common_internal_egl_extension_src_files) \
- $(adaptor_common_internal_x_mobile_profile_src_files)
-endif # WAYLAND
-
-endif # WEARABLE
+if IVI_PROFILE
+LIBDALI_ADAPTOR_LA_SOURCES = \
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_tizen_ivi_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_tizen_src_files) \
+ $(adaptor_adaptor_tizen_wayland_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_tizen_wayland_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_tizen_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_haptics_tizen_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_tizen_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_tizen_wayland_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_tizen_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_tizen_ivi_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_tizen_src_files) \
+ $(adaptor_window_system_tizen_wayland_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
+endif
+# $(adaptor_accessibility_tizen_common_src_files)
-# TV
if TV_PROFILE
-
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_tv_profile_src_files) \
- $(adaptor_tizen_internal_src_files) \
- $(adaptor_tizen_internal_non_mobile_src_files) \
- $(static_libraries_libunibreak_src_files)
-if WAYLAND
-
-if USE_ECORE_WAYLAND
-adaptor_internal_src_files += $(adaptor_ecore_wayland_tizen_internal_src_files)
-else
-adaptor_internal_src_files += $(adaptor_wayland_tizen_internal_src_files)
-endif # USE_ECORE_WAYLAND
-
-adaptor_internal_src_files += $(adaptor_tizen_internal_egl_extension_src_files) \
- $(adaptor_tizen_internal_native_image_src_files)
-else
-adaptor_internal_src_files += $(adaptor_x11_tv_internal_src_files) \
- $(adaptor_x11_internal_tv_profile_key_src_files) \
- $(adaptor_common_internal_egl_extension_src_files)
-endif # WAYLAND
-
+LIBDALI_ADAPTOR_LA_SOURCES = \
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_tizen_tv_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_tizen_src_files) \
+ $(adaptor_adaptor_tizen_wayland_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_tizen_wayland_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_tizen_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_tizen_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_tizen_wayland_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_tizen_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_tizen_tv_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_tizen_src_files) \
+ $(adaptor_window_system_tizen_wayland_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
endif
-# IVI
-if IVI_PROFILE
-
-adaptor_internal_src_files += $(adaptor_common_internal_src_files) \
- $(adaptor_common_internal_mobile_profile_src_files) \
- $(adaptor_tizen_internal_src_files) \
- $(static_libraries_libunibreak_src_files)
-
-if WAYLAND
-
-if USE_ECORE_WAYLAND
-adaptor_internal_src_files += $(adaptor_ecore_wayland_tizen_internal_src_files)
-else
-adaptor_internal_src_files += $(adaptor_wayland_tizen_internal_src_files)
-endif # USE_ECORE_WAYLAND
-
-adaptor_internal_src_files += $(adaptor_tizen_internal_egl_extension_src_files) \
- $(adaptor_tizen_internal_native_image_src_files)
-else
-adaptor_internal_src_files += $(adaptor_x11_tizen_internal_src_files) \
- $(adaptor_common_internal_egl_extension_src_files)
-endif # WAYLAND
-
-endif # IVI_PROFILE
-
-main_loop_integration_src_files = $(adaptor_common_internal_ecore_src_files)
-input_event_handler_src_files = $(adaptor_ecore_x_event_handler_internal_src_files)
-
-if ENABLE_VECTOR_BASED_TEXT_RENDERING
-adaptor_internal_src_files += $(static_libraries_glyphy_src_files)
-DALI_ADAPTOR_CFLAGS += -DENABLE_VECTOR_BASED_TEXT_RENDERING
+if COMMON_PROFILE
+LIBDALI_ADAPTOR_LA_SOURCES = \
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_tizen_common_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_tizen_src_files) \
+ $(adaptor_adaptor_tizen_wayland_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_tizen_wayland_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_tizen_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_tizen_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_tizen_wayland_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_tizen_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_generic_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_tizen_src_files) \
+ $(adaptor_window_system_tizen_wayland_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
endif
-pkgconfigdir = $(libdir)/pkgconfig
+# $(adaptor_accessibility_tizen_common_src_files)
-if ENABLE_CXX03_ABI
-pkgconfig_DATA = dali-adaptor-cxx03.pc dali-adaptor-integration-cxx03.pc
-else
-pkgconfig_DATA = dali-adaptor.pc dali-adaptor-integration.pc
-endif
+if WEARABLE_PROFILE
LIBDALI_ADAPTOR_LA_SOURCES = \
- $(base_adaptor_src_files) \
- $(main_loop_integration_src_files) \
- $(tizen_platform_abstraction_src_files) \
- $(text_abstraction_src_files) \
- $(devel_api_src_files) \
- $(public_api_src_files) \
- $(adaptor_internal_src_files) \
- $(input_event_handler_src_files) \
- $(image_resampler_src_files)
-
-
-if ENABLE_NETWORK_LOGGING
-LIBDALI_ADAPTOR_LA_SOURCES += \
- $(base_adaptor_networking_src_files)
+ $(adaptor_accessibility_common_src_files) \
+ $(adaptor_accessibility_tizen_wearable_src_files) \
+ $(adaptor_adaptor_common_src_files) \
+ $(adaptor_adaptor_tizen_src_files) \
+ $(adaptor_adaptor_tizen_wayland_src_files) \
+ $(adaptor_adaptor_tizen_wearable_src_files) \
+ $(adaptor_clipboard_common_src_files) \
+ $(adaptor_clipboard_tizen_wayland_src_files) \
+ $(devel_api_src_files) \
+ $(adaptor_devel_api_text_abstraction_src_files) \
+ $(adaptor_graphics_common_src_files) \
+ $(adaptor_graphics_gles20_src_files) \
+ $(adaptor_graphics_tizen_src_files) \
+ $(adaptor_haptics_common_src_files) \
+ $(adaptor_imaging_common_src_files) \
+ $(adaptor_imaging_tizen_src_files) \
+ $(adaptor_input_common_src_files) \
+ $(adaptor_input_tizen_wayland_src_files) \
+ $(adaptor_legacy_common_src_files) \
+ $(adaptor_network_common_src_files) \
+ $(adaptor_public_api_src_files) \
+ $(adaptor_sensor_common_src_files) \
+ $(adaptor_sensor_tizen_src_files) \
+ $(adaptor_styling_common_src_files) \
+ $(adaptor_system_common_src_files) \
+ $(adaptor_system_tizen_wearable_src_files) \
+ $(adaptor_text_common_src_files) \
+ $(adaptor_resampler_src_files) \
+ $(adaptor_video_common_src_files) \
+ $(adaptor_window_system_common_src_files) \
+ $(adaptor_window_system_tizen_src_files) \
+ $(adaptor_window_system_tizen_wayland_src_files) \
+ $(adaptor_window_system_tizen_wearable_src_files) \
+ $(devel_api_text_abstraction_src_files) \
+ $(static_libraries_glyphy_src_files) \
+ $(static_libraries_libunibreak_src_files)
endif
+# Package doc
+package_doxy_dir = ../../../doc
+include ../../../doc/file.list
+
libdali_adaptor_la_DEPENDENCIES =
# List include directories with more platform-specific (tizen) before portable root:
LIBDALI_ADAPTOR_LA_includes = \
- -I../../.. \
- -I../../../platform-abstractions/tizen \
- -I../../../platform-abstractions/tizen/resource-loader \
- -I../../../platform-abstractions/portable \
- -I../../../platform-abstractions/ \
- -I../../../adaptors/public-api \
- -I../../../adaptors/integration-api \
- -I../../../adaptors/public-api/adaptor-framework \
- -I../../../adaptors/devel-api/adaptor-framework \
- -I../../../adaptors/common \
- -I../../../adaptors/base/interfaces \
- -I../../../adaptors/ \
- -I../../../text \
- -I../../../text/dali/internal/libunibreak \
- -I../../../third-party/image-resampler
-
-if WAYLAND
-LIBDALI_ADAPTOR_LA_includes += -I../../../adaptors/integration-api/wayland
-
-if USE_ECORE_WAYLAND
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/ecore/common \
- -I../../../adaptors/ecore/wayland
-else
-LIBDALI_ADAPTOR_LA_includes += -I../../../adaptors/wayland \
- -I../../../adaptors/wayland/input/text/imf \
- -I../../../adaptors/wayland/clipboard
-endif # USE_ECORE_WAYLADN
-
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/tizen
-else
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/ecore/common \
- -I../../../adaptors/x11 \
- -I../../../adaptors/integration-api/x11
-endif # WAYLAND
-
-if UBUNTU_PROFILE
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/ubuntu
-else
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/tizen
-endif
-
-if WEARABLE_PROFILE
-LIBDALI_ADAPTOR_LA_includes += \
- -I../../../adaptors/wearable \
- -I../../../adaptors/wearable/capture
-endif
+ -I../../../
daliDefaultThemeDir = ${dataReadWriteDir}/theme/
daliShaderbinCacheDir = ${dataReadOnlyDir}/core/shaderbin/
linker_test_CXXFLAGS = \
-DDALI_ADAPTOR_COMPILATION \
- -I../../../adaptors/common \
- -I../../../adaptors/public-api \
- -I../../../adaptors/integration-api \
- -I../../../adaptors/base/interfaces \
- -I../../../adaptors/public-api/adaptor-framework \
- -I../../../adaptors/devel-api/adaptor-framework \
+ -I../../../ \
$(DALI_ADAPTOR_CFLAGS) \
$(DALICORE_CFLAGS) \
$(VCONF_CFLAGS) \
$(DALIX11_CFLAGS) \
-Werror -Wall
-if WAYLAND
-linker_test_CXXFLAGS += \
- -I../../../adaptors/integration-api/wayland
-else
-
-linker_test_CXXFLAGS += \
- -I../../../adaptors/integration-api/x11
-endif
-
linker_test_LDADD = \
$(DALICORE_LIBS) \
$(VCONF_LIBS) \
m4_define([dali_version],[0.1.0])
AC_INIT([dali], [dali_version])
AM_INIT_AUTOMAKE([-Wall foreign])
-
AC_CONFIG_MACRO_DIR([m4])
AC_PROG_CXX
AC_PROG_LIBTOOL
AC_PROG_MKDIR_P
+AM_CONDITIONAL(DEADCODE, [no])
+
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
LT_INIT
#include <dali/public-api/dali-core.h>
-#include <application.h>
-#include <adaptor.h>
-#include <render-surface.h>
-#include <orientation.h>
-#include <timer.h>
+#include <dali/public-api/adaptor-framework/application.h>
+#include <dali/integration-api/adaptor.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/devel-api/adaptor-framework/orientation.h>
+#include <dali/public-api/adaptor-framework/timer.h>
#include <iostream>
using namespace Dali;
--- /dev/null
+
+# Module: accessibility
+adaptor_accessibility_dir = ../../../dali/internal/accessibility
+include ../../../dali/internal/accessibility/file.list
+
+# Module: adaptor
+adaptor_adaptor_dir = ../../../dali/internal/adaptor
+include ../../../dali/internal/adaptor/file.list
+
+# Module: clipboard
+adaptor_clipboard_dir = ../../../dali/internal/clipboard
+include ../../../dali/internal/clipboard/file.list
+
+# Module: graphics
+adaptor_graphics_dir = ../../../dali/internal/graphics
+include ../../../dali/internal/graphics/file.list
+
+# Module: haptics
+adaptor_haptics_dir = ../../../dali/internal/haptics
+include ../../../dali/internal/haptics/file.list
+
+# Module: imaging
+adaptor_imaging_dir = ../../../dali/internal/imaging
+include ../../../dali/internal/imaging/file.list
+
+# Module: input
+adaptor_input_dir = ../../../dali/internal/input
+include ../../../dali/internal/input/file.list
+
+# Module: legacy
+adaptor_legacy_dir = ../../../dali/internal/legacy
+include ../../../dali/internal/legacy/file.list
+
+# Module: network
+adaptor_network_dir = ../../../dali/internal/network
+include ../../../dali/internal/network/file.list
+
+# Module: sensor
+adaptor_sensor_dir = ../../../dali/internal/sensor
+include ../../../dali/internal/sensor/file.list
+
+# Module: styling
+adaptor_styling_dir = ../../../dali/internal/styling
+include ../../../dali/internal/styling/file.list
+
+# Module: system
+adaptor_system_dir = ../../../dali/internal/system
+include ../../../dali/internal/system/file.list
+
+# Module: text
+adaptor_text_dir = ../../../dali/internal/text
+include ../../../dali/internal/text/file.list
+
+# Module: video
+adaptor_video_dir = ../../../dali/internal/video
+include ../../../dali/internal/video/file.list
+
+# Module: window-system
+adaptor_window_system_dir = ../../../dali/internal/window-system
+include ../../../dali/internal/window-system/file.list
+
+# Module: public-api
+adaptor_public_api_dir = ../../../dali/public-api
+include ../../../dali/public-api/file.list
+
+# Module: devel-api
+adaptor_devel_api_dir = ../../../dali/devel-api
+include ../../../dali/devel-api/file.list
+
+# Module: integration-api
+adaptor_integration_api_dir = ../../../dali/integration-api
+include ../../../dali/integration-api/file.list
+
+# Module: thirdparty ( external )
+adaptor_thirdparty_dir = ../../../third-party
+include ../../../third-party/file.list
+
$(FEEDBACK_CFLAGS) \
$(DALI_PROFILE_CFLAGS) \
$(DALI_ADAPTOR_CFLAGS) \
- -I../../../adaptors/public-api \
- -I../../../adaptors/integration-api \
- -I../../../adaptors/public-api/adaptor-framework \
- -I../../../adaptors/devel-api/adaptor-framework \
+ -I../../../ \
-Werror -Wall
LIBDALI_FEEDBACK_PLUGIN_LA_LIBADD = \
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/accessibility-adaptor.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+namespace Dali
+{
+
+AccessibilityAdaptor::AccessibilityAdaptor()
+{
+}
+
+AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::Get();
+}
+
+AccessibilityAdaptor::~AccessibilityAdaptor()
+{
+}
+
+Vector2 AccessibilityAdaptor::GetReadPosition() const
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).GetReadPosition();
+}
+
+bool AccessibilityAdaptor::IsEnabled() const
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).IsEnabled();
+}
+
+void AccessibilityAdaptor::SetActionHandler(AccessibilityActionHandler& handler)
+{
+ Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).SetActionHandler(handler);
+}
+
+void AccessibilityAdaptor::SetGestureHandler(AccessibilityGestureHandler& handler)
+{
+ Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).SetGestureHandler(handler);
+}
+
+bool AccessibilityAdaptor::HandleActionNextEvent(bool allowEndFeedback)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionNextEvent(allowEndFeedback);
+}
+
+bool AccessibilityAdaptor::HandleActionPreviousEvent(bool allowEndFeedback)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPreviousEvent(allowEndFeedback);
+}
+
+bool AccessibilityAdaptor::HandleActionActivateEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionActivateEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadEvent(x, y, allowReadAgain);
+}
+
+bool AccessibilityAdaptor::HandleActionReadNextEvent(bool allowEndFeedback)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadNextEvent(allowEndFeedback);
+}
+
+bool AccessibilityAdaptor::HandleActionReadPreviousEvent(bool allowEndFeedback)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadPreviousEvent(allowEndFeedback);
+}
+
+bool AccessibilityAdaptor::HandleActionUpEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionUpEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionDownEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionDownEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionClearFocusEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionClearFocusEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollEvent(point, timeStamp);
+}
+
+bool AccessibilityAdaptor::HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp)
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionTouchEvent(point, timeStamp);
+}
+
+bool AccessibilityAdaptor::HandleActionBackEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionBackEvent();
+}
+
+void AccessibilityAdaptor::HandleActionEnableEvent()
+{
+ Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionEnableEvent();
+}
+
+void AccessibilityAdaptor::HandleActionDisableEvent()
+{
+ Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionDisableEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionScrollUpEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollUpEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionScrollDownEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionScrollDownEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionPageLeftEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageLeftEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionPageRightEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageRightEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionPageUpEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageUpEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionPageDownEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionPageDownEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionMoveToFirstEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionMoveToFirstEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionMoveToLastEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionMoveToLastEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionReadFromTopEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadFromTopEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionReadFromNextEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadFromNextEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionZoomEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionZoomEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadIndicatorInformationEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionReadPauseResumeEvent();
+}
+
+bool AccessibilityAdaptor::HandleActionStartStopEvent()
+{
+ return Internal::Adaptor::AccessibilityAdaptor::GetImplementation(*this).HandleActionStartStopEvent();
+}
+
+AccessibilityAdaptor::AccessibilityAdaptor( Internal::Adaptor::AccessibilityAdaptor& manager )
+: BaseHandle( &manager )
+{
+}
+
+AccessibilityAdaptor::AccessibilityAdaptor( Internal::Adaptor::AccessibilityAdaptor* manager )
+: BaseHandle( manager )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/application-devel.h>
+#include <dali/internal/adaptor/common/application-impl.h>
+
+namespace Dali
+{
+
+namespace DevelApplication
+{
+
+void PreInitialize( int* argc, char** argv[] )
+{
+ Internal::Adaptor::Application::PreInitialize( argc, argv );
+}
+
+} // namespace DevelApplication
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_APPLICATION_DEVEL_H
+#define DALI_APPLICATION_DEVEL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application.h>
+
+namespace Dali
+{
+
+namespace DevelApplication
+{
+/**
+ * @brief This is used to improve application launch performance.
+ * It preloads so files, initializes some functions in advance and makes a window in advance.
+ *
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ */
+DALI_IMPORT_API void PreInitialize( int* argc, char** argv[] );
+
+} // namespace DevelApplication
+
+} // namespace Dali
+
+#endif // DALI_APPLICATION_DEVEL_H
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/application-extensions.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/application-impl.h>
+#include <dali/public-api/adaptor-framework/application.h>
+
+namespace Dali
+{
+
+ApplicationExtensions::ApplicationExtensions()
+: mApplication( NULL )
+{
+}
+
+ApplicationExtensions::ApplicationExtensions(Dali::Application* application)
+: mApplication( application )
+{
+}
+
+ApplicationExtensions::~ApplicationExtensions()
+{
+}
+
+void ApplicationExtensions::Init()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoInit();
+}
+
+void ApplicationExtensions::Start()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoStart();
+}
+
+void ApplicationExtensions::Terminate()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoTerminate();
+}
+
+void ApplicationExtensions::Pause()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoPause();
+}
+
+void ApplicationExtensions::Resume()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoResume();
+}
+
+void ApplicationExtensions::LanguageChange()
+{
+ Internal::Adaptor::GetImplementation(*mApplication).DoLanguageChange();
+}
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/bitmap-saver.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/loader-jpeg.h>
+#include <dali/internal/imaging/common/loader-png.h>
+#include <dali/internal/legacy/common/tizen-platform-abstraction.h>
+#include <dali/internal/legacy/tizen/image-encoder.h>
+
+
+namespace Dali
+{
+
+// Pieces needed to save compressed images (temporary location while plumbing):
+namespace
+{
+
+/**
+ * Simple function to tell intended image file format from filename
+ */
+FileFormat GetFormatFromFileName( const std::string& filename )
+{
+ if (filename.length() < 5)
+ {
+ DALI_LOG_WARNING("Invalid (short) filename.\n");
+ }
+ FileFormat format(INVALID_FORMAT);
+
+ const std::size_t filenameSize = filename.length();
+
+ if(filenameSize >= 4){ // Avoid throwing out_of_range or failing silently if exceptions are turned-off on the compare(). (http://www.cplusplus.com/reference/string/string/compare/)
+ if( !filename.compare( filenameSize - 4, 4, ".jpg" )
+ || !filename.compare( filenameSize - 4, 4, ".JPG" ) )
+ {
+ format = JPG_FORMAT;
+ }
+ else if( !filename.compare( filenameSize - 4, 4, ".png" )
+ || !filename.compare( filenameSize - 4, 4, ".PNG" ) )
+ {
+ format = PNG_FORMAT;
+ }
+ else if( !filename.compare( filenameSize - 4, 4, ".bmp" )
+ || !filename.compare( filenameSize - 4, 4, ".BMP" ) )
+ {
+ format = BMP_FORMAT;
+ }
+ else if( !filename.compare( filenameSize - 4, 4, ".gif" )
+ || !filename.compare( filenameSize - 4, 4, ".GIF" ) )
+ {
+ format = GIF_FORMAT;
+ }
+ else if( !filename.compare( filenameSize - 4, 4, ".ico" )
+ || !filename.compare( filenameSize - 4, 4, ".ICO" ) )
+ {
+ format = ICO_FORMAT;
+ }
+ else if(filenameSize >= 5){
+ if( !filename.compare( filenameSize - 5, 5, ".jpeg" )
+ || !filename.compare( filenameSize - 5, 5, ".JPEG" ) )
+ {
+ format = JPG_FORMAT;
+ }
+ }
+ }
+
+ return format;
+}
+
+bool EncodeToFormat( const unsigned char* pixelBuffer,
+ Vector< unsigned char >& encodedPixels,
+ FileFormat formatEncoding,
+ std::size_t width,
+ std::size_t height,
+ Pixel::Format pixelFormat )
+{
+ switch( formatEncoding )
+ {
+ case JPG_FORMAT:
+ {
+ return TizenPlatform::EncodeToJpeg( pixelBuffer, encodedPixels, width, height, pixelFormat );
+ break;
+ }
+ case PNG_FORMAT:
+ {
+ return TizenPlatform::EncodeToPng( pixelBuffer, encodedPixels, width, height, pixelFormat );
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR("Format not supported for image encoding (supported formats are PNG and JPEG)\n");
+ break;
+ }
+ }
+ return false;
+}
+} // anonymous namespace
+
+
+bool EncodeToFile(const unsigned char* const pixelBuffer,
+ const std::string& filename,
+ const Pixel::Format pixelFormat,
+ const std::size_t width,
+ const std::size_t height )
+{
+ DALI_ASSERT_DEBUG(pixelBuffer != 0 && filename.size() > 4 && width > 0 && height > 0);
+ Vector< unsigned char > pixbufEncoded;
+ const FileFormat format = GetFormatFromFileName( filename );
+ const bool encodeResult = EncodeToFormat( pixelBuffer, pixbufEncoded, format, width, height, pixelFormat );
+ if(!encodeResult)
+ {
+ DALI_LOG_ERROR("Encoding pixels failed\n");
+ return false;
+ }
+ return TizenPlatform::SaveFile( filename, pixbufEncoded.Begin(), pixbufEncoded.Count() );
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/clipboard/common/clipboard-event-notifier-impl.h>
+
+namespace Dali
+{
+
+ClipboardEventNotifier::ClipboardEventNotifier()
+{
+}
+
+ClipboardEventNotifier ClipboardEventNotifier::Get()
+{
+ return Internal::Adaptor::ClipboardEventNotifier::Get();
+}
+
+ClipboardEventNotifier::~ClipboardEventNotifier()
+{
+}
+
+const std::string& ClipboardEventNotifier::GetContent() const
+{
+ return Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).GetContent();
+}
+
+void ClipboardEventNotifier::SetContent( const std::string& content )
+{
+ Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).SetContent(content);
+}
+
+void ClipboardEventNotifier::ClearContent()
+{
+ Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).ClearContent();
+}
+
+void ClipboardEventNotifier::EmitContentSelectedSignal()
+{
+ Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).EmitContentSelectedSignal();
+}
+
+ClipboardEventNotifier::ClipboardEventSignalType& ClipboardEventNotifier::ContentSelectedSignal()
+{
+ return Internal::Adaptor::ClipboardEventNotifier::GetImplementation(*this).ContentSelectedSignal();
+}
+
+ClipboardEventNotifier::ClipboardEventNotifier( Internal::Adaptor::ClipboardEventNotifier* notifier )
+: BaseHandle( notifier )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/clipboard.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+
+namespace Dali
+{
+
+Clipboard::Clipboard()
+{
+}
+Clipboard::~Clipboard()
+{
+}
+Clipboard::Clipboard(Internal::Adaptor::Clipboard *impl)
+ : BaseHandle(impl)
+{
+}
+
+Clipboard Clipboard::Get()
+{
+ return Internal::Adaptor::Clipboard::Get();
+}
+
+bool Clipboard::SetItem( const std::string &itemData)
+{
+ return GetImplementation(*this).SetItem( itemData );
+}
+
+void Clipboard::RequestItem()
+{
+ GetImplementation(*this).RequestItem();
+}
+
+unsigned int Clipboard::NumberOfItems()
+{
+ return GetImplementation(*this).NumberOfItems();
+}
+
+void Clipboard::ShowClipboard()
+{
+ GetImplementation(*this).ShowClipboard();
+}
+
+void Clipboard::HideClipboard()
+{
+ GetImplementation(*this).HideClipboard(false);
+}
+
+bool Clipboard::IsVisible() const
+{
+ return GetImplementation(*this).IsVisible();
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/color-controller.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+namespace Dali
+{
+
+ColorController::ColorController()
+{
+}
+
+ColorController::ColorController(const ColorController& controller)
+: BaseHandle(controller)
+{
+}
+
+ColorController& ColorController::operator=(const ColorController& rhs)
+{
+ BaseHandle::operator=(rhs);
+ return *this;
+}
+
+ColorController ColorController::Get()
+{
+ return Internal::Adaptor::ColorController::Get();
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return GetImplementation(*this).RetrieveColor( colorCode, colorValue );
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return GetImplementation(*this).RetrieveColor( colorCode, textColor, textOutlineColor, textShadowColor );
+}
+
+ColorController::ColorController(Internal::Adaptor::ColorController* internal)
+: BaseHandle(internal)
+{
+}
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/drag-and-drop-detector.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+
+namespace Dali
+{
+
+DragAndDropDetector::DragAndDropDetector()
+{
+}
+
+DragAndDropDetector::~DragAndDropDetector()
+{
+}
+
+const std::string& DragAndDropDetector::GetContent() const
+{
+ return GetImplementation(*this).GetContent();
+}
+
+Vector2 DragAndDropDetector::GetCurrentScreenPosition() const
+{
+ return GetImplementation(*this).GetCurrentScreenPosition();
+}
+
+DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::EnteredSignal()
+{
+ return GetImplementation(*this).EnteredSignal();
+}
+
+DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::ExitedSignal()
+{
+ return GetImplementation(*this).ExitedSignal();
+}
+
+DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::MovedSignal()
+{
+ return GetImplementation(*this).MovedSignal();
+}
+
+DragAndDropDetector::DragAndDropSignal& DragAndDropDetector::DroppedSignal()
+{
+ return GetImplementation(*this).DroppedSignal();
+}
+
+DragAndDropDetector::DragAndDropDetector( Internal::Adaptor::DragAndDropDetector* detector )
+: BaseHandle( detector )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/environment-variable.h>
+
+// EXTERNAL INCLUDE
+#include <cstdlib>
+
+namespace Dali
+{
+
+namespace EnvironmentVariable
+{
+
+const char * GetEnvironmentVariable( const char * variable )
+{
+ return std::getenv( variable );
+}
+
+} // namespace EnvironmentVariable
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/event-feeder.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace EventFeeder
+{
+
+void FeedTouchPoint( TouchPoint& point, int timeStamp )
+{
+ if ( Adaptor::IsAvailable() )
+ {
+ Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedTouchPoint( point, timeStamp );
+ }
+}
+
+void FeedWheelEvent( WheelEvent& wheelEvent )
+{
+ if ( Adaptor::IsAvailable() )
+ {
+ Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedWheelEvent( wheelEvent );
+ }
+}
+
+void FeedKeyEvent( KeyEvent& keyEvent )
+{
+ if ( Adaptor::IsAvailable() )
+ {
+ Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).FeedKeyEvent( keyEvent );
+ }
+}
+
+} // namespace EventFeeder
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/event-thread-callback.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+struct EventThreadCallback::Impl
+{
+ TriggerEventInterface* eventTrigger;
+};
+
+EventThreadCallback::EventThreadCallback( CallbackBase* callback )
+: mImpl( new Impl() )
+{
+ mImpl->eventTrigger = NULL;
+ if ( Adaptor::IsAvailable() )
+ {
+ Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() );
+ mImpl->eventTrigger = adaptorImpl.GetTriggerEventFactoryInterface().CreateTriggerEvent( callback, TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
+ }
+}
+
+EventThreadCallback::~EventThreadCallback()
+{
+ if ( Adaptor::IsAvailable() )
+ {
+ Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() );
+ adaptorImpl.GetTriggerEventFactoryInterface().DestroyTriggerEvent( mImpl->eventTrigger );
+ }
+ delete mImpl;
+}
+
+void EventThreadCallback::Trigger()
+{
+ if( mImpl->eventTrigger )
+ {
+ mImpl->eventTrigger->Trigger();
+ }
+}
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/feedback-player.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/haptics/common/feedback-player-impl.h>
+
+namespace Dali
+{
+
+FeedbackPlayer::FeedbackPlayer()
+{
+}
+
+FeedbackPlayer FeedbackPlayer::Get()
+{
+ return Internal::Adaptor::FeedbackPlayer::Get();
+}
+
+FeedbackPlayer::~FeedbackPlayer()
+{
+}
+
+void FeedbackPlayer::PlayMonotone(unsigned int duration)
+{
+ GetImplementation(*this).PlayMonotone(duration);
+}
+
+void FeedbackPlayer::PlayFile(const std::string filePath)
+{
+ GetImplementation(*this).PlayFile(filePath);
+}
+
+void FeedbackPlayer::Stop()
+{
+ GetImplementation(*this).Stop();
+}
+
+int FeedbackPlayer::PlaySound( const std::string& fileName )
+{
+ return GetImplementation(*this).PlaySound(fileName);
+}
+
+void FeedbackPlayer::StopSound( int handle )
+{
+ GetImplementation(*this).StopSound(handle);
+}
+
+void FeedbackPlayer::PlayFeedbackPattern( int type, int pattern )
+{
+ GetImplementation(*this).PlayFeedbackPattern(type, pattern);
+}
+
+bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data)
+{
+ return GetImplementation(*this).LoadFile(filename, data);
+}
+
+FeedbackPlayer::FeedbackPlayer( Internal::Adaptor::FeedbackPlayer* player )
+: BaseHandle( player )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/file-loader.h>
+
+
+#include <iostream>
+#include <fstream>
+
+namespace Dali
+{
+
+namespace FileLoader
+{
+
+int ReadFile(const std::string& filename, Dali::Vector<char> & memblock, FileLoader::FileType fileType)
+{
+ std::streampos size;
+
+ return ReadFile( filename, size, memblock, fileType);
+}
+
+int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector<char> & memblock, FileLoader::FileType fileType)
+{
+ int errorCode = 0;
+ std::ifstream * file;
+
+
+ if( fileType == BINARY )
+ {
+ file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
+ }
+ else if( fileType == TEXT )
+ {
+ file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::ate);
+ }
+ else
+ {
+ return errorCode;
+ }
+
+ if( file->is_open() )
+ {
+ fileSize = file->tellg();
+
+ memblock.Resize( fileSize );
+
+ file->seekg (0, std::ios::beg);
+ file->read( memblock.Begin(), fileSize );
+ file->close();
+
+ delete file;
+
+ errorCode = 1;
+ }
+
+ return errorCode;
+}
+
+
+std::streampos GetFileSize(const std::string& filename)
+{
+ std::streampos size = 0;
+
+ std::ifstream file (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
+ if( file.is_open() )
+ {
+ size = file.tellg();
+ file.close();
+ }
+ return size;
+}
+
+} //FileLoader
+
+} //Dali
--- /dev/null
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Copyright notice for the EFL:
+ * Copyright (C) EFL developers (see AUTHORS)
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/gif-loading.h>
+
+// EXTERNAL INCLUDES
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <gif_lib.h>
+#include <cstring>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/images/pixel-data.h>
+
+#define IMG_TOO_BIG( w, h ) \
+ ( ( static_cast<unsigned long long>(w) * static_cast<unsigned long long>(h) ) >= \
+ ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) )
+
+#define LOADERR( x ) \
+ do { \
+ DALI_LOG_ERROR( x ); \
+ goto on_error; \
+ } while ( 0 )
+
+namespace Dali
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" );
+#endif
+
+const int IMG_MAX_SIZE = 65000;
+
+#if GIFLIB_MAJOR < 5
+const int DISPOSE_BACKGROUND = 2; /* Set area too background color */
+const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */
+#endif
+
+struct FrameInfo
+{
+ FrameInfo()
+ : x( 0 ),
+ y( 0 ),
+ w( 0 ),
+ h( 0 ),
+ delay( 0 ),
+ transparent( -1 ),
+ dispose( DISPOSE_BACKGROUND ),
+ interlace( 0 )
+ {
+ }
+
+ int x, y, w, h;
+ unsigned short delay; // delay time in 1/100ths of a sec
+ short transparent : 10; // -1 == not, anything else == index
+ short dispose : 6; // 0, 1, 2, 3 (others invalid)
+ short interlace : 1; // interlaced or not
+};
+
+struct ImageFrame
+{
+ ImageFrame()
+ : index( 0 ),
+ data( nullptr ),
+ info(),
+ loaded( false )
+ {
+ }
+
+ ~ImageFrame()
+ {
+ }
+
+ int index;
+ uint32_t *data; /* frame decoding data */
+ FrameInfo info; /* special image type info */
+ bool loaded : 1;
+};
+
+struct GifAnimationData
+{
+ GifAnimationData()
+ : frames( ),
+ frameCount( 0 ),
+ loopCount( 0 ),
+ currentFrame( 0 ),
+ animated( false )
+ {
+ }
+
+ std::vector<ImageFrame> frames;
+ int frameCount;
+ int loopCount;
+ int currentFrame;
+ bool animated;
+};
+
+struct LoaderInfo
+{
+ LoaderInfo()
+ : gif( nullptr ) ,
+ imageNumber ( 0 )
+ {
+ }
+
+ struct FileData
+ {
+ FileData()
+ : fileName( nullptr ),
+ globalMap ( nullptr ),
+ length( 0 ),
+ fileDescriptor( -1 )
+ {
+ }
+
+ const char *fileName; /**< The absolute path of the file. */
+ unsigned char *globalMap ; /**< A pointer to the entire contents of the file that have been mapped with mmap(2). */
+ long long length; /**< The length of the file in bytes. */
+ int fileDescriptor; /**< The file descriptor. */
+ };
+
+ struct FileInfo
+ {
+ FileInfo()
+ : map( nullptr ),
+ position( 0 ),
+ length( 0 )
+ {
+ }
+
+ unsigned char *map;
+ int position, length; // yes - gif uses ints for file sizes.
+ };
+
+ FileData fileData;
+ GifAnimationData animated;
+ GifFileType *gif;
+ int imageNumber;
+ FileInfo fileInfo;
+};
+
+struct ImageProperties
+{
+ unsigned int w;
+ unsigned int h;
+ bool alpha;
+};
+
+/**
+ * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value.
+ *
+ * @param[in] animated A structure containing GIF animation data
+ * @param[in] index Frame index to be searched in GIF
+ * @return A pointer to the ImageFrame.
+ */
+inline int CombinePixelABGR( int a, int r, int g, int b )
+{
+ return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) );
+}
+
+inline int PixelLookup( ColorMapObject *colorMap, int index )
+{
+ return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue );
+}
+
+/**
+ * @brief Brute force find frame index - gifs are normally small so ok for now.
+ *
+ * @param[in] animated A structure containing GIF animation data
+ * @param[in] index Frame index to be searched in GIF
+ * @return A pointer to the ImageFrame.
+ */
+ImageFrame *FindFrame( const GifAnimationData &animated, int index )
+{
+ for( auto &&elem : animated.frames )
+ {
+ if( elem.index == index )
+ {
+ return const_cast<ImageFrame *>( &elem );
+ }
+ }
+ return nullptr;
+}
+
+/**
+ * @brief Fill in an image with a specific rgba color value.
+ *
+ * @param[in] data A pointer pointing to an image data
+ * @param[in] row A int containing the number of rows in an image
+ * @param[in] val A uint32_t containing rgba color value
+ * @param[in] x X-coordinate used an offset to calculate pixel position
+ * @param[in] y Y-coordinate used an offset to calculate pixel position
+ * @param[in] width Width of the image
+ * @param[in] height Height of the image
+ */
+void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height )
+{
+ int xAxis, yAxis;
+ uint32_t *pixelPosition;
+
+ for( yAxis = 0; yAxis < height; yAxis++ )
+ {
+ pixelPosition = data + ((y + yAxis) * row) + x;
+ for( xAxis = 0; xAxis < width; xAxis++ )
+ {
+ *pixelPosition = val;
+ pixelPosition++;
+ }
+ }
+}
+
+/**
+ * @brief Fill a rgba data pixle blob with a frame color (bg or trans)
+ *
+ * @param[in] data A pointer pointing to an image data
+ * @param[in] row A int containing the number of rows in an image
+ * @param[in] gif A pointer pointing to GIF File Type
+ * @param[in] frameInfo A pointer pointing to Frame Information data
+ * @param[in] x X-coordinate used an offset to calculate pixel position
+ * @param[in] y Y-coordinate used an offset to calculate pixel position
+ * @param[in] width Width of the image
+ * @param[in] height Height of the image
+ */
+void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h )
+{
+ // solid color fill for pre frame region
+ if( frameInfo->transparent < 0 )
+ {
+ ColorMapObject *colorMap;
+ int backGroundColor;
+
+ // work out color to use from colorMap
+ if( gif->Image.ColorMap )
+ {
+ colorMap = gif->Image.ColorMap;
+ }
+ else
+ {
+ colorMap = gif->SColorMap;
+ }
+ backGroundColor = gif->SBackGroundColor;
+ // and do the fill
+ FillImage( data, row,
+ CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red,
+ colorMap->Colors[backGroundColor].Green,
+ colorMap->Colors[backGroundColor].Blue ),
+ x, y, w, h );
+ }
+ // fill in region with 0 (transparent)
+ else
+ {
+ FillImage( data, row, 0, x, y, w, h );
+ }
+}
+
+/**
+ * @brief Store common fields from gif file info into frame info
+ *
+ * @param[in] gif A pointer pointing to GIF File Type
+ * @param[in] frameInfo A pointer pointing to Frame Information data
+ */
+void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo )
+{
+ frameInfo->x = gif->Image.Left;
+ frameInfo->y = gif->Image.Top;
+ frameInfo->w = gif->Image.Width;
+ frameInfo->h = gif->Image.Height;
+ frameInfo->interlace = gif->Image.Interlace;
+}
+
+/**
+ * @brief Check if image fills "screen space" and if so, if it is transparent
+ * at all then the image could be transparent - OR if image doesnt fill,
+ * then it could be trasnparent (full coverage of screen). Some gifs will
+ * be recognized as solid here for faster rendering, but not all.
+ *
+ * @param[out] full A boolean to show whether image is transparent or not
+ * @param[in] frameInfo A pointer pointing to Frame Information data
+ * @param[in] width Width of the image
+ * @param[in] height Height of the image
+ */
+void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height )
+{
+ if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) &&
+ ( frameInfo->w == width ) && ( frameInfo->h == height ) )
+ {
+ if( frameInfo->transparent >= 0 )
+ {
+ full = false;
+ }
+ }
+ else
+ {
+ full = false;
+ }
+}
+
+/**
+ * @brief Fix coords and work out an x and y inset in orig data if out of image bounds.
+ */
+void ClipCoordinates( int imageWidth, int imageHeight, int *xin, int *yin, int x0, int y0, int w0, int h0, int *x, int *y, int *w, int *h )
+{
+ if( x0 < 0 )
+ {
+ w0 += x0;
+ *xin = -x0;
+ x0 = 0;
+ }
+ if( (x0 + w0) > imageWidth )
+ {
+ w0 = imageWidth - x0;
+ }
+ if( y0 < 0 )
+ {
+ h0 += y0;
+ *yin = -y0;
+ y0 = 0;
+ }
+ if( (y0 + h0) > imageHeight )
+ {
+ h0 = imageHeight - y0;
+ }
+ *x = x0;
+ *y = y0;
+ *w = w0;
+ *h = h0;
+}
+
+/**
+ * @brief Flush out rgba frame images to save memory but skip current,
+ * previous and lastPreservedFrame frames (needed for dispose mode DISPOSE_PREVIOUS)
+ *
+ * @param[in] animated A structure containing GIF animation data
+ * @param[in] width Width of the image
+ * @param[in] height Height of the image
+ * @param[in] thisframe The current frame
+ * @param[in] prevframe The previous frame
+ * @param[in] lastPreservedFrame The last preserved frame
+ */
+void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame )
+{
+ DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" );
+
+ // target is the amount of memory we want to be under for stored frames
+ int total = 0, target = 512 * 1024;
+
+ // total up the amount of memory used by stored frames for this image
+ for( auto &&frame : animated.frames )
+ {
+ if( frame.data )
+ {
+ total++;
+ }
+ }
+ total *= ( width * height * sizeof( uint32_t ) );
+
+ DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total );
+
+ // If we use more than target (512k) for frames - flush
+ if( total > target )
+ {
+ // Clean frames (except current and previous) until below target
+ for( auto &&frame : animated.frames )
+ {
+ if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) &&
+ (!lastPreservedFrame || frame.index != lastPreservedFrame->index) )
+ {
+ if( frame.data != nullptr )
+ {
+ delete[] frame.data;
+ frame.data = nullptr;
+
+ // subtract memory used and if below target - stop flush
+ total -= ( width * height * sizeof( uint32_t ) );
+ if( total < target )
+ {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" );
+}
+
+/**
+ * @brief allocate frame and frame info and append to list and store fields.
+ *
+ * @param[in] animated A structure containing GIF animation data
+ * @param[in] transparent Transparent index of the new frame
+ * @param[in] dispose Dispose mode of new frame
+ * @param[in] delay The frame delay of new frame
+ * @param[in] index The index of new frame
+ */
+FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index )
+{
+ ImageFrame frame;
+
+ // record transparent index to be used or -1 if none
+ // for this SPECIFIC frame
+ frame.info.transparent = transparent;
+ // record dispose mode (3 bits)
+ frame.info.dispose = dispose;
+ // record delay (2 bytes so max 65546 /100 sec)
+ frame.info.delay = delay;
+ // record the index number we are at
+ frame.index = index;
+ // that frame is stored AT image/screen size
+
+ animated.frames.push_back( frame );
+
+ DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() );
+
+ return &( animated.frames.back().info );
+}
+
+/**
+ * @brief Copy data from gif file into buffer.
+ *
+ * @param[in] gifFileType A pointer pointing to GIF File Type
+ * @param[out] buffer A pointer to buffer containing GIF raw data
+ * @param[in] len The length in bytes to be copied
+ * @return The data length of the image in bytes
+ */
+int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length )
+{
+ LoaderInfo::FileInfo *fi = reinterpret_cast<LoaderInfo::FileInfo *>( gifFileType->UserData );
+
+ if( fi->position >= fi->length )
+ {
+ return 0; // if at or past end - no
+ }
+ if( (fi->position + length) >= fi->length )
+ {
+ length = fi->length - fi->position;
+ }
+ memcpy( buffer, fi->map + fi->position, length );
+ fi->position += length;
+ return length;
+}
+
+/**
+ * @brief Decode a gif image into rows then expand to 32bit into the destination
+ * data pointer.
+ */
+bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin,
+ int transparent, int x, int y, int w, int h, bool fill )
+{
+ int intoffset[] = {0, 4, 2, 1};
+ int intjump[] = {8, 8, 4, 2};
+ int i, xx, yy, pix;
+ GifRowType *rows = NULL;
+ bool ret = false;
+ ColorMapObject *colorMap;
+ uint32_t *p;
+
+ // what we need is image size.
+ SavedImage *sp;
+ sp = &gif->SavedImages[ gif->ImageCount - 1 ];
+ if( !sp )
+ {
+ goto on_error;
+ }
+ w = sp->ImageDesc.Width;
+ h = sp->ImageDesc.Height;
+
+ // build a blob of memory to have pointers to rows of pixels
+ // AND store the decoded gif pixels (1 byte per pixel) as welll
+ rows = static_cast<GifRowType *>(malloc( (h * sizeof(GifRowType) ) + ( w * h * sizeof(GifPixelType) )));
+ if( !rows )
+ {
+ goto on_error;
+ }
+
+ // fill in the pointers at the start
+ for( yy = 0; yy < h; yy++ )
+ {
+ rows[yy] = reinterpret_cast<unsigned char *>(rows) + (h * sizeof(GifRowType)) + (yy * w * sizeof(GifPixelType));
+ }
+
+ // if gif is interlaced, walk interlace pattern and decode into rows
+ if( gif->Image.Interlace )
+ {
+ for( i = 0; i < 4; i++ )
+ {
+ for( yy = intoffset[i]; yy < h; yy += intjump[i] )
+ {
+ if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
+ {
+ goto on_error;
+ }
+ }
+ }
+ }
+ // normal top to bottom - decode into rows
+ else
+ {
+ for( yy = 0; yy < h; yy++ )
+ {
+ if( DGifGetLine( gif, rows[yy], w ) != GIF_OK )
+ {
+ goto on_error;
+ }
+ }
+ }
+
+ // work out what colormap to use
+ if( gif->Image.ColorMap )
+ {
+ colorMap = gif->Image.ColorMap;
+ }
+ else
+ {
+ colorMap = gif->SColorMap;
+ }
+
+ // if we need to deal with transparent pixels at all...
+ if( transparent >= 0 )
+ {
+ // if we are told to FILL (overwrite with transparency kept)
+ if( fill )
+ {
+ for( yy = 0; yy < h; yy++ )
+ {
+ p = data + ((y + yy) * rowpix) + x;
+ for( xx = 0; xx < w; xx++ )
+ {
+ pix = rows[yin + yy][xin + xx];
+ if( pix != transparent )
+ {
+ *p = PixelLookup( colorMap, pix );
+ }
+ else
+ {
+ *p = 0;
+ }
+ p++;
+ }
+ }
+ }
+ // paste on top with transparent pixels untouched
+ else
+ {
+ for( yy = 0; yy < h; yy++ )
+ {
+ p = data + ((y + yy) * rowpix) + x;
+ for( xx = 0; xx < w; xx++ )
+ {
+ pix = rows[yin + yy][xin + xx];
+ if( pix != transparent )
+ {
+ *p = PixelLookup( colorMap, pix );
+ }
+ p++;
+ }
+ }
+ }
+ }
+ else
+ {
+ // walk pixels without worring about transparency at all
+ for( yy = 0; yy < h; yy++ )
+ {
+ p = data + ((y + yy) * rowpix) + x;
+ for( xx = 0; xx < w; xx++ )
+ {
+ pix = rows[yin + yy][xin + xx];
+ *p = PixelLookup( colorMap, pix );
+ p++;
+ }
+ }
+ }
+ ret = true;
+
+on_error:
+ if( rows )
+ {
+ free( rows );
+ }
+ return ret;
+}
+
+/**
+ * @brief Reader header from the gif file and populates structures accordingly.
+ *
+ * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
+ * @param[out] prop A ImageProperties structure for storing information about GIF data.
+ * @param[out] error Error code
+ * @return The true or false whether reading was successful or not.
+ */
+bool ReadHeader( LoaderInfo &loaderInfo,
+ ImageProperties &prop, //output struct
+ int *error )
+{
+ GifAnimationData &animated = loaderInfo.animated;
+ LoaderInfo::FileData &fileData = loaderInfo.fileData;
+ bool ret = false;
+ LoaderInfo::FileInfo fileInfo;
+ GifRecordType rec;
+ GifFileType *gif = NULL;
+ // it is possible which gif file have error midle of frames,
+ // in that case we should play gif file until meet error frame.
+ int imageNumber = 0;
+ int loopCount = -1;
+ FrameInfo *frameInfo = NULL;
+ bool full = true;
+
+ // init prop struct with some default null values
+ prop.w = 0;
+ prop.h = 0;
+
+ fileData.fileDescriptor = open( fileData.fileName, O_RDONLY );
+
+ if( fileData.fileDescriptor == -1 )
+ {
+ return false;
+ }
+
+ fileData.length = lseek( fileData.fileDescriptor, 0, SEEK_END );
+ if( fileData.length <= -1 )
+ {
+ close( fileData.fileDescriptor );
+ return false;
+ }
+
+ if( lseek( fileData.fileDescriptor, 0, SEEK_SET ) == -1 )
+ {
+ close( fileData.fileDescriptor );
+ return false;
+ }
+
+ // map the file and store/track info
+ fileData.globalMap = reinterpret_cast<unsigned char *>( mmap(NULL, fileData.length, PROT_READ, MAP_SHARED, fileData.fileDescriptor, 0 ));
+ fileInfo.map = fileData.globalMap ;
+
+ close(fileData.fileDescriptor);
+ fileData.fileDescriptor = -1;
+
+ if( !fileInfo.map )
+ {
+ LOADERR("LOAD_ERROR_CORRUPT_FILE");
+ }
+ fileInfo.length = fileData.length;
+ fileInfo.position = 0;
+
+// actually ask libgif to open the file
+#if GIFLIB_MAJOR >= 5
+ gif = DGifOpen( &fileInfo, FileRead, NULL );
+#else
+ gif = DGifOpen( &fileInfo, FileRead );
+#endif
+
+ if (!gif)
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+
+ // get the gif "screen size" (the actual image size)
+ prop.w = gif->SWidth;
+ prop.h = gif->SHeight;
+
+ // if size is invalid - abort here
+ if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) )
+ {
+ if( IMG_TOO_BIG(prop.w, prop.h) )
+ {
+ LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
+ }
+ LOADERR("LOAD_ERROR_GENERIC");
+ }
+ // walk through gif records in file to figure out info
+ do
+ {
+ if( DGifGetRecordType(gif, &rec) == GIF_ERROR )
+ {
+ // if we have a gif that ends part way through a sequence
+ // (or animation) consider it valid and just break - no error
+ if( imageNumber > 1 )
+ {
+ break;
+ }
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+
+ // get image description section
+ if( rec == IMAGE_DESC_RECORD_TYPE )
+ {
+ int img_code;
+ GifByteType *img;
+
+ // get image desc
+ if( DGifGetImageDesc(gif) == GIF_ERROR )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+ // skip decoding and just walk image to next
+ if( DGifGetCode(gif, &img_code, &img) == GIF_ERROR )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+ // skip till next...
+ while( img )
+ {
+ img = NULL;
+ DGifGetCodeNext( gif, &img );
+ }
+ // store geometry in the last frame info data
+ if( frameInfo )
+ {
+ StoreFrameInfo( gif, frameInfo );
+ CheckTransparency( full, frameInfo, prop.w, prop.h );
+ }
+ // or if we dont have a frameInfo entry - create one even for stills
+ else
+ {
+ // allocate and save frame with field data
+ frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 );
+ if (!frameInfo)
+ {
+ LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
+ }
+ // store geometry info from gif image
+ StoreFrameInfo( gif, frameInfo );
+ // check for transparency/alpha
+ CheckTransparency( full, frameInfo, prop.w, prop.h );
+ }
+ imageNumber++;
+ }
+ // we have an extension code block - for animated gifs for sure
+ else if( rec == EXTENSION_RECORD_TYPE )
+ {
+ int ext_code;
+ GifByteType *ext;
+
+ ext = NULL;
+ // get the first extension entry
+ DGifGetExtension( gif, &ext_code, &ext );
+ while( ext )
+ {
+ // graphic control extension - for animated gif data
+ // and transparent index + flag
+ if( ext_code == 0xf9 )
+ {
+ // create frame and store it in image
+ int transparencyIndex = (ext[1] & 1) ? ext[4] : -1;
+ int disposeMode = (ext[1] >> 2) & 0x7;
+ int delay = (int(ext[3]) << 8) | int(ext[2]);
+ frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1);
+ if( !frameInfo )
+ {
+ LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
+ }
+ }
+ // netscape extension indicating loop count.
+ else if( ext_code == 0xff ) /* application extension */
+ {
+ if( !strncmp(reinterpret_cast<char *>(&ext[1]), "NETSCAPE2.0", 11) ||
+ !strncmp(reinterpret_cast<char *>(&ext[1]), "ANIMEXTS1.0", 11) )
+ {
+ ext = NULL;
+ DGifGetExtensionNext( gif, &ext );
+ if( ext[1] == 0x01 )
+ {
+ loopCount = (int(ext[3]) << 8) | int(ext[2]);
+ if( loopCount > 0 )
+ {
+ loopCount++;
+ }
+ }
+ }
+ }
+ // and continue onto the next extension entry
+ ext = NULL;
+ DGifGetExtensionNext( gif, &ext );
+ }
+ }
+ } while( rec != TERMINATE_RECORD_TYPE );
+
+ // if the gif main says we have more than one image or our image counting
+ // says so, then this image is animated - indicate this
+ if( (gif->ImageCount > 1) || (imageNumber > 1) )
+ {
+ animated.animated = 1;
+ animated.loopCount = loopCount;
+ }
+ animated.frameCount = std::min( gif->ImageCount, imageNumber );
+
+ if( !full )
+ {
+ prop.alpha = 1;
+ }
+
+ animated.currentFrame = 1;
+
+ // no errors in header scan etc. so set err and return value
+ *error = 0;
+ ret = true;
+
+on_error: // jump here on any errors to clean up
+#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
+ if( gif )
+ {
+ DGifCloseFile( gif, NULL );
+ }
+#else
+ if( gif )
+ {
+ DGifCloseFile( gif );
+ }
+#endif
+
+ return ret;
+}
+
+/**
+ * @brief Reader next frame of the gif file and populates structures accordingly.
+ *
+ * @param[in] loaderInfo A LoaderInfo structure containing file descriptor and other data about GIF.
+ * @param[in/out] prop A ImageProperties structure containing information about gif data.
+ * @param[out] pixels A pointer to buffer which will contain all pixel data of the frame on return.
+ * @param[out] error Error code
+ * @return The true or false whether reading was successful or not.
+ */
+bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h
+ unsigned char *pixels, int *error )
+{
+ GifAnimationData &animated = loaderInfo.animated;
+ LoaderInfo::FileData &fileData = loaderInfo.fileData;
+ bool ret = false;
+ GifRecordType rec;
+ GifFileType *gif = NULL;
+ int index = 0, imageNumber = 0;
+ FrameInfo *frameInfo;
+ ImageFrame *frame = NULL;
+ ImageFrame *lastPreservedFrame = NULL;
+
+ index = animated.currentFrame;
+
+ // if index is invalid for animated image - error out
+ if ((animated.animated) && ((index <= 0) || (index > animated.frameCount)))
+ {
+ LOADERR("LOAD_ERROR_GENERIC");
+ }
+
+ // find the given frame index
+ frame = FindFrame( animated, index );
+ if( frame )
+ {
+ if( (frame->loaded) && (frame->data) )
+ {
+ // frame is already there and decoded - jump to end
+ goto on_ok;
+ }
+ }
+ else
+ {
+ LOADERR("LOAD_ERROR_CORRUPT_FILE");
+ }
+
+open_file:
+ // actually ask libgif to open the file
+ gif = loaderInfo.gif;
+ if( !gif )
+ {
+ loaderInfo.fileInfo.map = fileData.globalMap ;
+ if( !loaderInfo.fileInfo.map )
+ {
+ LOADERR("LOAD_ERROR_CORRUPT_FILE");
+ }
+ loaderInfo.fileInfo.length = fileData.length;
+ loaderInfo.fileInfo.position = 0;
+
+#if GIFLIB_MAJOR >= 5
+ gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead, NULL );
+#else
+ gif = DGifOpen( &( loaderInfo.fileInfo ), FileRead );
+#endif
+ // if gif open failed... get out of here
+ if( !gif )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+ loaderInfo.gif = gif;
+ loaderInfo.imageNumber = 1;
+ }
+
+ // if we want to go backwards, we likely need/want to re-decode from the
+ // start as we have nothing to build on
+ if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) )
+ {
+#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
+ if( loaderInfo.gif )
+ DGifCloseFile( loaderInfo.gif, NULL );
+#else
+ if( loaderInfo.gif )
+ DGifCloseFile( loaderInfo.gif );
+#endif
+ loaderInfo.gif = NULL;
+ loaderInfo.imageNumber = 0;
+ goto open_file;
+ }
+
+ // our current position is the previous frame we decoded from the file
+ imageNumber = loaderInfo.imageNumber;
+
+ // walk through gif records in file to figure out info
+ do
+ {
+ if( DGifGetRecordType( gif, &rec ) == GIF_ERROR )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+
+ if( rec == EXTENSION_RECORD_TYPE )
+ {
+ int ext_code;
+ GifByteType *ext = NULL;
+ DGifGetExtension( gif, &ext_code, &ext );
+
+ while( ext )
+ {
+ ext = NULL;
+ DGifGetExtensionNext( gif, &ext );
+ }
+ }
+ // get image description section
+ else if( rec == IMAGE_DESC_RECORD_TYPE )
+ {
+ int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0;
+ int img_code;
+ GifByteType *img;
+ ImageFrame *previousFrame = NULL;
+ ImageFrame *thisFrame = NULL;
+
+ // get image desc
+ if( DGifGetImageDesc(gif) == GIF_ERROR )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+
+ // get the previous frame entry AND the current one to fill in
+ previousFrame = FindFrame(animated, imageNumber - 1);
+ thisFrame = FindFrame(animated, imageNumber);
+
+ // if we have a frame AND we're animated AND we have no data...
+ if( (thisFrame) && (!thisFrame->data) && (animated.animated) )
+ {
+ bool first = false;
+
+ // allocate it
+ thisFrame->data = new uint32_t[prop.w * prop.h];
+
+ if( !thisFrame->data )
+ {
+ LOADERR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED");
+ }
+
+ // if we have no prior frame OR prior frame data... empty
+ if( (!previousFrame) || (!previousFrame->data) )
+ {
+ first = true;
+ frameInfo = &(thisFrame->info);
+ memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) );
+ }
+ // we have a prior frame to copy data from...
+ else
+ {
+ frameInfo = &( previousFrame->info );
+
+ // fix coords of sub image in case it goes out...
+ ClipCoordinates( prop.w, prop.h, &xin, &yin,
+ frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
+ &x, &y, &w, &h );
+
+ // if dispose mode is not restore - then copy pre frame
+ if( frameInfo->dispose != DISPOSE_PREVIOUS )
+ {
+ memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) );
+ }
+
+ // if dispose mode is "background" then fill with bg
+ if( frameInfo->dispose == DISPOSE_BACKGROUND )
+ {
+ FillFrame( thisFrame->data, prop.w, gif, frameInfo, x, y, w, h );
+ }
+ else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE
+ {
+ int prevIndex = 2;
+ do
+ {
+ // Find last preserved frame.
+ lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex );
+ if( ! lastPreservedFrame )
+ {
+ LOADERR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" );
+ }
+ prevIndex++;
+ } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS );
+
+ if ( lastPreservedFrame )
+ {
+ memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) );
+ }
+ }
+ }
+ // now draw this frame on top
+ frameInfo = &( thisFrame->info );
+ ClipCoordinates( prop.w, prop.h, &xin, &yin,
+ frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
+ &x, &y, &w, &h );
+ if( !DecodeImage( gif, thisFrame->data, prop.w,
+ xin, yin, frameInfo->transparent,
+ x, y, w, h, first) )
+ {
+ LOADERR("LOAD_ERROR_CORRUPT_FILE");
+ }
+
+ // mark as loaded and done
+ thisFrame->loaded = true;
+
+ FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame );
+ }
+ // if we hve a frame BUT the image is not animated... different
+ // path
+ else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) )
+ {
+ // if we don't have the data decoded yet - decode it
+ if( (!thisFrame->loaded) || (!thisFrame->data) )
+ {
+ // use frame info but we WONT allocate frame pixels
+ frameInfo = &( thisFrame->info );
+ ClipCoordinates( prop.w, prop.h, &xin, &yin,
+ frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h,
+ &x, &y, &w, &h );
+
+ // clear out all pixels
+ FillFrame( reinterpret_cast<uint32_t *>(pixels), prop.w, gif, frameInfo, 0, 0, prop.w, prop.h );
+
+ // and decode the gif with overwriting
+ if( !DecodeImage( gif, reinterpret_cast<uint32_t *>(pixels), prop.w,
+ xin, yin, frameInfo->transparent, x, y, w, h, true) )
+ {
+ LOADERR("LOAD_ERROR_CORRUPT_FILE");
+ }
+
+ // mark as loaded and done
+ thisFrame->loaded = true;
+ }
+ // flush mem we don't need (at expense of decode cpu)
+ }
+ else
+ {
+ // skip decoding and just walk image to next
+ if( DGifGetCode( gif, &img_code, &img ) == GIF_ERROR )
+ {
+ LOADERR("LOAD_ERROR_UNKNOWN_FORMAT");
+ }
+
+ while( img )
+ {
+ img = NULL;
+ DGifGetCodeNext( gif, &img );
+ }
+ }
+
+ imageNumber++;
+ // if we found the image we wanted - get out of here
+ if( imageNumber > index )
+ {
+ break;
+ }
+ }
+ } while( rec != TERMINATE_RECORD_TYPE );
+
+ // if we are at the end of the animation or not animated, close file
+ loaderInfo.imageNumber = imageNumber;
+ if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) )
+ {
+#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1))
+ if( loaderInfo.gif )
+ {
+ DGifCloseFile( loaderInfo.gif, NULL );
+ }
+#else
+ if( loaderInfo.gif )
+ {
+ DGifCloseFile( loaderInfo.gif );
+ }
+#endif
+
+ loaderInfo.gif = NULL;
+ loaderInfo.imageNumber = 0;
+ }
+
+on_ok:
+ // no errors in header scan etc. so set err and return value
+ *error = 0;
+ ret = true;
+
+ // if it was an animated image we need to copy the data to the
+ // pixels for the image from the frame holding the data
+ if( animated.animated && frame->data )
+ {
+ memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) );
+ }
+
+on_error: // jump here on any errors to clean up
+ return ret;
+}
+
+} // unnamed namespace
+
+struct GifLoading::Impl
+{
+public:
+ Impl( const std::string& url)
+ : mUrl( url )
+ {
+ loaderInfo.gif = nullptr;
+ int error;
+ loaderInfo.fileData.fileName = mUrl.c_str();
+
+ ReadHeader( loaderInfo, imageProperties, &error );
+ }
+
+ ~Impl()
+ {
+ if( loaderInfo.fileData.globalMap )
+ {
+ munmap( loaderInfo.fileData.globalMap , loaderInfo.fileData.length );
+ loaderInfo.fileData.globalMap = nullptr;
+ }
+ }
+
+ std::string mUrl;
+ LoaderInfo loaderInfo;
+ ImageProperties imageProperties;
+};
+
+std::unique_ptr<GifLoading> GifLoading::New( const std::string &url )
+{
+ return std::unique_ptr<GifLoading>( new GifLoading( url ) );
+}
+
+GifLoading::GifLoading( const std::string &url )
+: mImpl( new GifLoading::Impl( url ) )
+{
+}
+
+GifLoading::~GifLoading()
+{
+ delete mImpl;
+}
+
+bool GifLoading::LoadNextNFrames( int frameStartIndex, int count, std::vector<Dali::PixelData> &pixelData )
+{
+ int error;
+ bool ret = false;
+
+ const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t );
+
+ DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count );
+
+ for( int i = 0; i < count; ++i )
+ {
+ auto pixelBuffer = new unsigned char[ bufferSize ];
+
+ mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount );
+
+ if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) )
+ {
+ if( pixelBuffer )
+ {
+ pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize,
+ mImpl->imageProperties.w, mImpl->imageProperties.h,
+ Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) );
+ ret = true;
+ }
+ }
+ }
+
+ return ret;
+}
+
+bool GifLoading::LoadAllFrames( std::vector<Dali::PixelData> &pixelData, Dali::Vector<uint32_t> &frameDelays )
+{
+ if( LoadFrameDelays( frameDelays ) )
+ {
+ return LoadNextNFrames( 0, mImpl->loaderInfo.animated.frameCount, pixelData );
+ }
+ return false;
+}
+
+ImageDimensions GifLoading::GetImageSize()
+{
+ return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.w );
+}
+
+int GifLoading::GetImageCount()
+{
+ return mImpl->loaderInfo.animated.frameCount;
+}
+
+bool GifLoading::LoadFrameDelays( Dali::Vector<uint32_t> &frameDelays )
+{
+ frameDelays.Clear();
+
+ for( auto &&elem : mImpl->loaderInfo.animated.frames )
+ {
+ // Read frame delay time, multiply 10 to change time unit to milliseconds
+ frameDelays.PushBack( elem.info.delay * 10 );
+ }
+
+ return true;
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/object/property-map.h>
+#include <dali/internal/imaging/common/image-loader.h>
+#include <dali/internal/imaging/common/file-download.h>
+#include <dali/internal/system/common/file-reader.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+
+namespace
+{
+
+// limit maximum image down load size to 50 MB
+const size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024 ;
+
+static unsigned int gMaxTextureSize = 4096;
+
+}
+
+Devel::PixelBuffer LoadImageFromFile( const std::string& url, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection )
+{
+ Integration::BitmapResourceType resourceType( size, fittingMode, samplingMode, orientationCorrection );
+
+ Internal::Platform::FileReader fileReader( url );
+ FILE * const fp = fileReader.GetFile();
+ if( fp != NULL )
+ {
+ Dali::Devel::PixelBuffer bitmap;
+ bool success = TizenPlatform::ImageLoader::ConvertStreamToBitmap( resourceType, url, fp, bitmap );
+ if( success && bitmap )
+ {
+ return bitmap;
+ }
+ }
+ return Dali::Devel::PixelBuffer();
+}
+
+ImageDimensions GetClosestImageSize( const std::string& filename,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection )
+{
+ ImageDimensions dimension = TizenPlatform::ImageLoader::GetClosestImageSize( filename, size, fittingMode, samplingMode, orientationCorrection );
+
+ dimension.SetWidth( std::min( dimension.GetWidth(), static_cast< uint16_t >( GetMaxTextureSize() ) ) );
+ dimension.SetHeight( std::min( dimension.GetHeight(), static_cast< uint16_t >( GetMaxTextureSize() ) ) );
+
+ return dimension;
+}
+
+
+Devel::PixelBuffer DownloadImageSynchronously( const std::string& url, ImageDimensions size, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection )
+{
+ Integration::BitmapResourceType resourceType( size, fittingMode, samplingMode, orientationCorrection );
+
+ bool succeeded;
+ Dali::Vector<uint8_t> dataBuffer;
+ size_t dataSize;
+
+ succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( url, dataBuffer, dataSize,
+ MAXIMUM_DOWNLOAD_IMAGE_SIZE );
+ if( succeeded )
+ {
+ size_t blobSize = dataBuffer.Size();
+
+ DALI_ASSERT_DEBUG( blobSize > 0U );
+
+ if( blobSize > 0U )
+ {
+ // Open a file handle on the memory buffer:
+ Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize );
+ FILE * const fp = fileReader.GetFile();
+ if ( NULL != fp )
+ {
+ Dali::Devel::PixelBuffer bitmap;
+ bool result = TizenPlatform::ImageLoader::ConvertStreamToBitmap(
+ resourceType,
+ url,
+ fp,
+ bitmap );
+
+ if ( result && bitmap )
+ {
+ return bitmap;
+ }
+ else
+ {
+ DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" );
+ }
+ }
+ }
+ }
+ return Dali::Devel::PixelBuffer();
+}
+
+void SetMaxTextureSize( unsigned int size )
+{
+ gMaxTextureSize = size;
+}
+
+unsigned int GetMaxTextureSize()
+{
+ return gMaxTextureSize;
+}
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_IMAGE_LOADING_H
+#define DALI_IMAGE_LOADING_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/images/image-operations.h>
+
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+
+/**
+ * @brief Load an image synchronously from local file.
+ *
+ * @note This method is thread safe, i.e. can be called from any thread.
+ *
+ * @param [in] url The URL of the image file to load.
+ * @param [in] size The width and height to fit the loaded image to, 0.0 means whole image
+ * @param [in] fittingMode The method used to fit the shape of the image before loading to the shape defined by the size parameter.
+ * @param [in] samplingMode The filtering method used when sampling pixels from the input image while fitting it to desired size.
+ * @param [in] orientationCorrection Reorient the image to respect any orientation metadata in its header.
+ * @return handle to the loaded PixelBuffer object or an empty handle in case loading failed.
+ */
+DALI_IMPORT_API Devel::PixelBuffer LoadImageFromFile(
+ const std::string& url,
+ ImageDimensions size = ImageDimensions( 0, 0 ),
+ FittingMode::Type fittingMode = FittingMode::DEFAULT,
+ SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR,
+ bool orientationCorrection = true );
+
+/**
+ * @brief Determine the size of an image that LoadImageFromFile will provide when
+ * given the same image loading parameters.
+ *
+ * This is a synchronous request.
+ * This function is used to determine the size of an image before it has loaded.
+ * @param[in] filename name of the image.
+ * @param[in] size The requested size for the image.
+ * @param[in] fittingMode The method to use to map the source image to the desired
+ * dimensions.
+ * @param[in] samplingMode The image filter to use if the image needs to be
+ * downsampled to the requested size.
+ * @param[in] orientationCorrection Whether to use image metadata to rotate or
+ * flip the image, e.g., from portrait to landscape.
+ * @return dimensions that image will have if it is loaded with given parameters.
+ */
+DALI_IMPORT_API ImageDimensions GetClosestImageSize(
+ const std::string& filename,
+ ImageDimensions size = ImageDimensions(0, 0),
+ FittingMode::Type fittingMode = FittingMode::DEFAULT,
+ SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR ,
+ bool orientationCorrection = true );
+
+/**
+ * @brief Load an image synchronously from a remote resource.
+ *
+ * @param [in] url The URL of the image file to load.
+ * @param [in] size The width and height to fit the loaded image to, 0.0 means whole image
+ * @param [in] fittingMode The method used to fit the shape of the image before loading to the shape defined by the size parameter.
+ * @param [in] samplingMode The filtering method used when sampling pixels from the input image while fitting it to desired size.
+ * @param [in] orientationCorrection Reorient the image to respect any orientation metadata in its header.
+ *
+ * @return handle to the loaded PixelBuffer object or an empty handle in case downloading or decoding failed.
+ */
+DALI_IMPORT_API Devel::PixelBuffer DownloadImageSynchronously(
+ const std::string& url,
+ ImageDimensions size = ImageDimensions( 0, 0 ),
+ FittingMode::Type fittingMode = FittingMode::DEFAULT,
+ SamplingMode::Type samplingMode = SamplingMode::BOX_THEN_LINEAR,
+ bool orientationCorrection = true );
+
+/**
+ * @brief Set the maximum texture size. Then size can be kwown by GL_MAX_TEXTURE_SIZE.
+ *
+ * @param [in] size The maximum texture size to set
+ */
+void SetMaxTextureSize( unsigned int size );
+
+/**
+ * @brief get the maximum texture size.
+ *
+ * @return The maximum texture size
+ */
+DALI_IMPORT_API unsigned int GetMaxTextureSize();
+
+} // Dali
+
+#endif // DALI_IMAGE_LOADING_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/imf-manager-impl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+ImfManager::ImfManager()
+{
+}
+
+ImfManager::~ImfManager()
+{
+}
+
+ImfManager ImfManager::Get()
+{
+ return Internal::Adaptor::ImfManager::Get();
+}
+
+void ImfManager::Activate()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).Activate();
+}
+
+void ImfManager::Deactivate()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).Deactivate();
+}
+
+bool ImfManager::RestoreAfterFocusLost() const
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).RestoreAfterFocusLost();
+}
+
+void ImfManager::SetRestoreAfterFocusLost( bool toggle )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).SetRestoreAfterFocusLost( toggle );
+}
+
+void ImfManager::Reset()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).Reset();
+}
+
+void ImfManager::NotifyCursorPosition()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).NotifyCursorPosition();
+}
+
+void ImfManager::SetCursorPosition( unsigned int SetCursorPosition )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).SetCursorPosition( SetCursorPosition );
+}
+
+unsigned int ImfManager::GetCursorPosition() const
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetCursorPosition();
+}
+
+void ImfManager::SetSurroundingText( const std::string& text )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).SetSurroundingText( text );
+}
+
+const std::string& ImfManager::GetSurroundingText() const
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetSurroundingText();
+}
+
+void ImfManager::NotifyTextInputMultiLine( bool multiLine )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).NotifyTextInputMultiLine( multiLine );
+}
+
+ImfManager::TextDirection ImfManager::GetTextDirection()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetTextDirection();
+}
+
+Rect<int> ImfManager::GetInputMethodArea()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputMethodArea();
+}
+
+void ImfManager::ApplyOptions( const InputMethodOptions& options )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).ApplyOptions( options );
+}
+
+void ImfManager::SetInputPanelData( const std::string& data )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).SetInputPanelData( data );
+}
+
+void ImfManager::GetInputPanelData( std::string& data )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelData( data );
+}
+
+Dali::ImfManager::State ImfManager::GetInputPanelState()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelState();
+}
+
+void ImfManager::SetReturnKeyState( bool visible )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).SetReturnKeyState( visible );
+}
+
+void ImfManager::AutoEnableInputPanel( bool enabled )
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).AutoEnableInputPanel( enabled );
+}
+
+void ImfManager::ShowInputPanel()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).ShowInputPanel();
+}
+
+void ImfManager::HideInputPanel()
+{
+ Internal::Adaptor::ImfManager::GetImplementation(*this).HideInputPanel();
+}
+
+Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetKeyboardType();
+}
+
+std::string ImfManager::GetInputPanelLocale()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).GetInputPanelLocale();
+}
+
+ImfManager::ImfManagerSignalType& ImfManager::ActivatedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).ActivatedSignal();
+}
+
+ImfManager::ImfEventSignalType& ImfManager::EventReceivedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).EventReceivedSignal();
+}
+
+ImfManager::StatusSignalType& ImfManager::StatusChangedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).StatusChangedSignal();
+}
+
+ImfManager::KeyboardResizedSignalType& ImfManager::ResizedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).ResizedSignal();
+}
+
+ImfManager::LanguageChangedSignalType& ImfManager::LanguageChangedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).LanguageChangedSignal();
+}
+
+ImfManager::KeyboardTypeSignalType& ImfManager::KeyboardTypeChangedSignal()
+{
+ return Internal::Adaptor::ImfManager::GetImplementation(*this).KeyboardTypeChangedSignal();
+}
+
+ImfManager::ImfManager(Internal::Adaptor::ImfManager *impl)
+ : BaseHandle(impl)
+{
+}
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_IMF_MANAGER_H__
+#define __DALI_IMF_MANAGER_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-handle.h>
+#include <dali/public-api/signals/dali-signal.h>
+#include <dali/devel-api/adaptor-framework/input-method-options.h>
+
+namespace Dali
+{
+
+namespace Internal DALI_INTERNAL
+{
+namespace Adaptor
+{
+class ImfManager;
+}
+}
+
+/**
+ * @brief The ImfManager class
+ *
+ * Specifically manages the ecore input method framework which enables the virtual or hardware keyboards.
+ */
+class DALI_IMPORT_API ImfManager : public BaseHandle
+{
+public:
+
+ /**
+ * @brief The direction of text.
+ */
+ enum TextDirection
+ {
+ LeftToRight,
+ RightToLeft,
+ };
+
+ /**
+ * @brief Events that are generated by the IMF.
+ */
+ enum ImfEvent
+ {
+ VOID, ///< No event
+ PREEDIT, ///< Pre-Edit changed
+ COMMIT, ///< Commit recieved
+ DELETESURROUNDING, ///< Event to delete a range of characters from the string
+ GETSURROUNDING, ///< Event to query string and cursor position
+ PRIVATECOMMAND ///< Private command sent from the input panel
+ };
+
+ /**
+ * @brief Enumeration for state of the input panel.
+ */
+ enum State
+ {
+ DEFAULT = 0, ///< Unknown state
+ SHOW, ///< Input panel is shown
+ HIDE, ///< Input panel is hidden
+ WILL_SHOW ///< Input panel in process of being shown
+ };
+
+ /**
+ * @brief Enumeration for the type of Keyboard.
+ */
+ enum KeyboardType
+ {
+ SOFTWARE_KEYBOARD, ///< Software keyboard (Virtual keyboard) is default
+ HARDWARE_KEYBOARD ///< Hardware keyboard
+ };
+
+ /**
+ * @brief This structure is used to pass on data from the IMF regarding predictive text.
+ */
+ struct ImfEventData
+ {
+ /**
+ * @brief Default Constructor.
+ */
+ ImfEventData()
+ : predictiveString(),
+ eventName( VOID ),
+ cursorOffset( 0 ),
+ numberOfChars ( 0 )
+ {
+ };
+
+ /**
+ * @brief Constructor
+ *
+ * @param[in] aEventName The name of the event from the IMF.
+ * @param[in] aPredictiveString The pre-edit or commit string.
+ * @param[in] aCursorOffset Start position from the current cursor position to start deleting characters.
+ * @param[in] aNumberOfChars The number of characters to delete from the cursorOffset.
+ */
+ ImfEventData( ImfEvent aEventName, const std::string& aPredictiveString, int aCursorOffset, int aNumberOfChars )
+ : predictiveString( aPredictiveString ),
+ eventName( aEventName ),
+ cursorOffset( aCursorOffset ),
+ numberOfChars( aNumberOfChars )
+ {
+ }
+
+ // Data
+ std::string predictiveString; ///< The pre-edit or commit string.
+ ImfEvent eventName; ///< The name of the event from the IMF.
+ int cursorOffset; ///< Start position from the current cursor position to start deleting characters.
+ int numberOfChars; ///< number of characters to delete from the cursorOffset.
+ };
+
+ /**
+ * @brief Data required by IMF from the callback
+ */
+ struct ImfCallbackData
+ {
+ /**
+ * @brief Constructor
+ */
+ ImfCallbackData()
+ : currentText(),
+ cursorPosition( 0 ),
+ update( false ),
+ preeditResetRequired( false )
+ {
+ }
+
+ /**
+ * @brief Constructor
+ * @param[in] aUpdate True if cursor position needs to be updated
+ * @param[in] aCursorPosition new position of cursor
+ * @param[in] aCurrentText current text string
+ * @param[in] aPreeditResetRequired flag if preedit reset is required.
+ */
+ ImfCallbackData( bool aUpdate, int aCursorPosition, const std::string& aCurrentText, bool aPreeditResetRequired )
+ : currentText( aCurrentText ),
+ cursorPosition( aCursorPosition ),
+ update( aUpdate ),
+ preeditResetRequired( aPreeditResetRequired )
+ {
+ }
+
+ std::string currentText; ///< current text string
+ int cursorPosition; ///< new position of cursor
+ bool update :1; ///< if cursor position needs to be updated
+ bool preeditResetRequired :1; ///< flag if preedit reset is required.
+ };
+
+ typedef Signal< void (ImfManager&) > ImfManagerSignalType; ///< Keyboard actived signal
+ typedef Signal< ImfCallbackData ( ImfManager&, const ImfEventData& ) > ImfEventSignalType; ///< keyboard events
+ typedef Signal< void () > VoidSignalType;
+ typedef Signal< void ( bool ) > StatusSignalType;
+ typedef Signal< void ( KeyboardType ) > KeyboardTypeSignalType; ///< keyboard type
+ typedef Signal< void ( int ) > KeyboardResizedSignalType; ///< Keyboard resized signal
+ typedef Signal< void ( int ) > LanguageChangedSignalType; ///< Language changed signal
+
+public:
+
+ /**
+ * @brief Retrieve a handle to the instance of ImfManager.
+ * @return A handle to the ImfManager.
+ */
+ static ImfManager Get();
+
+ /**
+ * @brief Activate the IMF.
+ *
+ * It means that the text editing is started at somewhere.
+ * If the H/W keyboard isn't connected then it will show the virtual keyboard.
+ */
+ void Activate();
+
+ /**
+ * @brief Deactivate the IMF.
+ *
+ * It means that the text editing is finished at somewhere.
+ */
+ void Deactivate();
+
+ /**
+ * @brief Get the restoration status, which controls if the keyboard is restored after the focus lost then regained.
+ *
+ * If true then keyboard will be restored (activated) after focus is regained.
+ * @return restoration status.
+ */
+ bool RestoreAfterFocusLost() const;
+
+ /**
+ * @brief Set status whether the IMF has to restore the keyboard after losing focus.
+ *
+ * @param[in] toggle True means that keyboard should be restored after focus lost and regained.
+ */
+ void SetRestoreAfterFocusLost( bool toggle );
+
+ /**
+ * @brief Send message reset the pred-edit state / imf module.
+ *
+ * Used to interupt pre-edit state maybe due to a touch input.
+ */
+ void Reset();
+
+ /**
+ * @brief Notifies IMF context that the cursor position has changed, required for features like auto-capitalisation.
+ */
+ void NotifyCursorPosition();
+
+ /**
+ * @brief Sets cursor position stored in VirtualKeyboard, this is required by the IMF context.
+ *
+ * @param[in] cursorPosition position of cursor
+ */
+ void SetCursorPosition( unsigned int cursorPosition );
+
+ /**
+ * @brief Gets cursor position stored in VirtualKeyboard, this is required by the IMF context.
+ *
+ * @return current position of cursor
+ */
+ unsigned int GetCursorPosition() const;
+
+ /**
+ * @brief Method to store the string required by the IMF, this is used to provide predictive word suggestions.
+ *
+ * @param[in] text The text string surrounding the current cursor point.
+ */
+ void SetSurroundingText( const std::string& text );
+
+ /**
+ * @brief Gets current text string set within the IMF manager, this is used to offer predictive suggestions.
+ *
+ * @return current position of cursor
+ */
+ const std::string& GetSurroundingText() const;
+
+ /**
+ * @brief Notifies IMF context that text input is set to multi line or not
+ *
+ * @param[in] multiLine True if multiline text input is used
+ */
+ void NotifyTextInputMultiLine( bool multiLine );
+
+ /**
+ * @brief Returns text direction of the keyboard's current input language.
+ * @return The direction of the text.
+ */
+ TextDirection GetTextDirection();
+
+ /**
+ * @brief Provides size and position of keyboard.
+ *
+ * Position is relative to whether keyboard is visible or not.
+ * If keyboard is not visible then position will be off the screen.
+ * If keyboard is not being shown when this method is called the keyboard is partially setup (IMFContext) to get
+ * the values then taken down. So ideally GetInputMethodArea() should be called after Show().
+ * @return rect which is keyboard panel x, y, width, height
+ */
+ Dali::Rect<int> GetInputMethodArea();
+
+ /**
+ * @brief Set one or more of the Input Method options
+ * @param[in] options The options to be applied
+ */
+ void ApplyOptions( const InputMethodOptions& options );
+
+ /**
+ * @brief Sets up the input-panel specific data.
+ * @param[in] data The specific data to be set to the input panel
+ */
+ void SetInputPanelData( const std::string& data );
+
+ /**
+ * @brief Gets the specific data of the current active input panel.
+ *
+ * Input Panel Data is not always the data which is set by SetInputPanelData().
+ * Data can be changed internally in the input panel.
+ * It is just used to get a specific data from the input panel to an application.
+ * @param[in] data The specific data to be got from the input panel
+ */
+ void GetInputPanelData( std::string& data );
+
+ /**
+ * @brief Gets the state of the current active input panel.
+ * @return The state of the input panel.
+ */
+ State GetInputPanelState();
+
+ /**
+ * @brief Sets the return key on the input panel to be visible or invisible.
+ *
+ * The default is true.
+ * @param[in] visible True if the return key is visible(enabled), false otherwise.
+ */
+ void SetReturnKeyState( bool visible );
+
+ /**
+ * @brief Enable to show the input panel automatically when focused.
+ * @param[in] enabled If true, the input panel will be shown when focused
+ */
+ void AutoEnableInputPanel( bool enabled );
+
+ /**
+ * @brief Shows the input panel.
+ */
+ void ShowInputPanel();
+
+ /**
+ * @brief Hides the input panel.
+ */
+ void HideInputPanel();
+
+ /**
+ * @brief Gets the keyboard type.
+ *
+ * The default keyboard type is SOFTWARE_KEYBOARD.
+ * @return The keyboard type
+ */
+ KeyboardType GetKeyboardType();
+
+ /**
+ * @brief Gets the current language locale of the input panel.
+ *
+ * ex) en_US, en_GB, en_PH, fr_FR, ...
+ * @return The current language locale of the input panel
+ */
+ std::string GetInputPanelLocale();
+
+public:
+
+ // Signals
+
+ /**
+ * @brief This is emitted when the virtual keyboard is connected to or the hardware keyboard is activated.
+ *
+ * @return The IMF Activated signal.
+ */
+ ImfManagerSignalType& ActivatedSignal();
+
+ /**
+ * @brief This is emitted when the IMF manager receives an event from the IMF.
+ *
+ * @return The Event signal containing the event data.
+ */
+ ImfEventSignalType& EventReceivedSignal();
+
+ /**
+ * @brief Connect to this signal to be notified when the virtual keyboard is shown or hidden.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(bool keyboardShown);
+ * @endcode
+ * If the parameter keyboardShown is true, then the keyboard has just shown, if it is false, then it
+ * has just been hidden.
+ * @return The signal to connect to.
+ */
+ StatusSignalType& StatusChangedSignal();
+
+ /**
+ * @brief Connect to this signal to be notified when the virtual keyboard is resized.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName( int resolvedResize );
+ * @endcode
+ * The parameter sends the resolved resize defined by the IMF.
+ *
+ * User can get changed size by using GetInputMethodArea() in the callback
+ * @return The signal to connect to.
+ */
+ KeyboardResizedSignalType& ResizedSignal();
+
+ /**
+ * @brief Connect to this signal to be notified when the virtual keyboard's language is changed.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName( int resolvedLanguage );
+ * @endcode
+ * The parameter sends the resolved language defined by the IMF.
+ *
+ * User can get the text direction of the language by calling GetTextDirection() in the callback.
+ * @return The signal to connect to.
+ */
+ LanguageChangedSignalType& LanguageChangedSignal();
+
+ /**
+ * @brief Connect to this signal to be notified when the keyboard type is changed.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName( KeyboardType keyboard );
+ * @endcode
+ *
+ * @return The signal to connect to.
+ */
+ KeyboardTypeSignalType& KeyboardTypeChangedSignal();
+
+ // Construction & Destruction
+
+ /**
+ * @brief Constructor.
+ */
+ ImfManager();
+
+ /**
+ * @brief Destructor
+ *
+ * This is non-virtual since derived Handle types must not contain data or virtual methods.
+ */
+ ~ImfManager();
+
+ /**
+ * @brief This constructor is used by ImfManager::Get().
+ *
+ * @param[in] imfManager A pointer to the imf Manager.
+ */
+ explicit DALI_INTERNAL ImfManager( Internal::Adaptor::ImfManager* imfManager );
+};
+
+} // namespace Dali
+
+#endif // __DALI_IMF_MANAGER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/input-method-options.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/input-method-devel.h>
+
+using namespace Dali::InputMethod;
+using namespace Dali::InputMethod::Category;
+
+namespace Dali
+{
+
+#define TOKEN_STRING(x) #x
+
+struct InputMethodOptions::Impl
+{
+ Impl()
+ {
+ mPanelLayout = PanelLayout::NORMAL;
+ mAutoCapital = AutoCapital::SENTENCE;
+ mActionButton = ActionButtonTitle::DEFAULT;
+ mVariation = NormalLayout::NORMAL;
+ }
+
+ PanelLayout::Type mPanelLayout;
+ AutoCapital::Type mAutoCapital;
+ ActionButtonTitle::Type mActionButton;
+ int mVariation:4;
+};
+
+InputMethodOptions::InputMethodOptions()
+{
+ mImpl.reset(new Impl());
+}
+
+InputMethodOptions::~InputMethodOptions()
+{
+ // destructor cannot be inlined and must be in a unit
+ // for unique_ptr to work with forward declaration
+}
+
+bool InputMethodOptions::IsPassword()
+{
+ return (mImpl->mPanelLayout == Dali::InputMethod::PanelLayout::PASSWORD);
+}
+
+void InputMethodOptions::ApplyProperty( const Property::Map& settings )
+{
+ for ( unsigned int i = 0, count = settings.Count(); i < count; ++i )
+ {
+ Property::Key key = settings.GetKeyAt( i );
+ if( key.type == Property::Key::INDEX )
+ {
+ continue;
+ }
+
+ Property::Value item = settings.GetValue(i);
+
+ if( key == TOKEN_STRING( PANEL_LAYOUT ) )
+ {
+ if( item.GetType() == Property::INTEGER )
+ {
+ int value = item.Get< int >();
+ mImpl->mPanelLayout = static_cast<InputMethod::PanelLayout::Type>(value);
+ }
+ }
+ else if ( key == TOKEN_STRING( AUTO_CAPITALISE ) )
+ {
+ if ( item.GetType() == Property::INTEGER )
+ {
+ int value = item.Get< int >();
+ mImpl->mAutoCapital = static_cast<InputMethod::AutoCapital::Type>(value);
+ }
+ }
+ else if ( key == TOKEN_STRING( ACTION_BUTTON ) )
+ {
+ if ( item.GetType() == Property::INTEGER )
+ {
+ int value = item.Get< int >();
+ mImpl->mActionButton = static_cast<InputMethod::ActionButtonTitle::Type>(value);
+ }
+ }
+ else if( key == TOKEN_STRING( VARIATION ) )
+ {
+ if( item.GetType() == Property::INTEGER )
+ {
+ int value = item.Get< int >();
+ mImpl->mVariation = value;
+ }
+ }
+ else
+ {
+ }
+ }
+}
+
+void InputMethodOptions::RetrieveProperty( Property::Map& settings )
+{
+ settings[TOKEN_STRING( PANEL_LAYOUT )] = mImpl->mPanelLayout;
+ settings[TOKEN_STRING( AUTO_CAPITALISE )] = mImpl->mAutoCapital;
+ settings[TOKEN_STRING( ACTION_BUTTON )] = mImpl->mActionButton;
+ settings[TOKEN_STRING( VARIATION )] = mImpl->mVariation;
+}
+
+bool InputMethodOptions::CompareAndSet( InputMethod::Category::Type type, const InputMethodOptions& options, int& index)
+{
+ bool updated = false;
+
+ switch (type)
+ {
+ case PANEL_LAYOUT:
+ {
+ if ( options.mImpl->mPanelLayout != mImpl->mPanelLayout )
+ {
+ mImpl->mPanelLayout = options.mImpl->mPanelLayout;
+ index = static_cast<int>(mImpl->mPanelLayout);
+ updated = true;
+ }
+ break;
+ }
+ case AUTO_CAPITALISE:
+ {
+ if ( options.mImpl->mAutoCapital != mImpl->mAutoCapital )
+ {
+ mImpl->mAutoCapital = options.mImpl->mAutoCapital;
+ index = static_cast<int>(mImpl->mAutoCapital);
+ updated = true;
+ }
+ break;
+ }
+ case ACTION_BUTTON_TITLE:
+ {
+ if ( options.mImpl->mActionButton != mImpl->mActionButton )
+ {
+ mImpl->mActionButton = options.mImpl->mActionButton;
+ index = static_cast<int>(mImpl->mActionButton);
+ updated = true;
+ }
+ break;
+ }
+ case VARIATION:
+ {
+ if ( options.mImpl->mVariation != mImpl->mVariation )
+ {
+ mImpl->mVariation = options.mImpl->mVariation;
+ index = static_cast<int>(mImpl->mVariation);
+ updated = true;
+ }
+ break;
+ }
+ }
+ return updated;
+}
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
+#define __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <memory>
+
+#include <dali/public-api/object/property-map.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/input-method-devel.h>
+
+namespace Dali
+{
+
+/**
+ * Class to handle the Input Method options
+ */
+class DALI_IMPORT_API InputMethodOptions
+{
+public:
+
+ /**
+ * Constructor
+ */
+ InputMethodOptions(); /// Default InputMethodOptions options
+
+ /**
+ * Destructor
+ */
+ ~InputMethodOptions();
+
+ /**
+ * @brief Returns whether panel layout type is password or not
+ * @return true if panel layout type is password, false otherwise.
+ */
+ bool IsPassword();
+
+ /**
+ * @brief Apply property map to attribute class, this class will keep the virtualKeyboard settings.
+ * @param[in] settings The property map to be applied
+ */
+ void ApplyProperty( const Property::Map& settings );
+
+ /**
+ * @brief Retrieve property map from current option
+ * @param[out] settings The converted property map
+ */
+ void RetrieveProperty( Property::Map& settings );
+
+public: // Intended for internal use
+ /**
+ * @brief Set option respectively
+ * @param[in] type The type of source option will be updated
+ * @param[in] options The source option to be applied
+ * @param[out] index The updated index after applying source option
+ * @return true if the value of this option is updated by source option
+ */
+ DALI_INTERNAL bool CompareAndSet( InputMethod::Category::Type type, const InputMethodOptions& options, int& index );
+
+private:
+
+ struct Impl;
+ std::unique_ptr<Impl> mImpl;
+};
+
+} // namespace Dali
+
+#endif // __DALI_VIRTUAL_KEYBOARD_OPTIONS_H__
--- /dev/null
+#ifndef DALI_KEY_DEVEL_H
+#define DALI_KEY_DEVEL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/key.h>
+
+namespace Dali
+{
+
+namespace DevelKey
+{
+
+enum Key
+{
+ DALI_KEY_INVALID = Dali::DALI_KEY_INVALID,
+ DALI_KEY_ESCAPE = Dali::DALI_KEY_ESCAPE,
+ DALI_KEY_BACKSPACE = Dali::DALI_KEY_BACKSPACE,
+ DALI_KEY_SHIFT_LEFT = Dali::DALI_KEY_SHIFT_LEFT,
+ DALI_KEY_SHIFT_RIGHT = Dali::DALI_KEY_SHIFT_RIGHT,
+ DALI_KEY_CURSOR_UP = Dali::DALI_KEY_CURSOR_UP,
+ DALI_KEY_CURSOR_LEFT = Dali::DALI_KEY_CURSOR_LEFT,
+ DALI_KEY_CURSOR_RIGHT = Dali::DALI_KEY_CURSOR_RIGHT,
+ DALI_KEY_CURSOR_DOWN = Dali::DALI_KEY_CURSOR_DOWN,
+ DALI_KEY_BACK = Dali::DALI_KEY_BACK,
+ DALI_KEY_CAMERA = Dali::DALI_KEY_CAMERA,
+ DALI_KEY_CONFIG = Dali::DALI_KEY_CONFIG,
+ DALI_KEY_POWER = Dali::DALI_KEY_POWER,
+ DALI_KEY_PAUSE = Dali::DALI_KEY_PAUSE,
+ DALI_KEY_CANCEL = Dali::DALI_KEY_CANCEL,
+ DALI_KEY_PLAY_CD = Dali::DALI_KEY_PLAY_CD,
+ DALI_KEY_STOP_CD = Dali::DALI_KEY_STOP_CD,
+ DALI_KEY_PAUSE_CD = Dali::DALI_KEY_PAUSE_CD,
+ DALI_KEY_NEXT_SONG = Dali::DALI_KEY_NEXT_SONG,
+ DALI_KEY_PREVIOUS_SONG = Dali::DALI_KEY_PREVIOUS_SONG,
+ DALI_KEY_REWIND = Dali::DALI_KEY_REWIND,
+ DALI_KEY_FASTFORWARD = Dali::DALI_KEY_FASTFORWARD,
+ DALI_KEY_MEDIA = Dali::DALI_KEY_MEDIA,
+ DALI_KEY_PLAY_PAUSE = Dali::DALI_KEY_PLAY_PAUSE,
+ DALI_KEY_MUTE = Dali::DALI_KEY_MUTE,
+ DALI_KEY_MENU = Dali::DALI_KEY_MENU,
+ DALI_KEY_HOME = Dali::DALI_KEY_HOME,
+ DALI_KEY_HOMEPAGE = Dali::DALI_KEY_HOMEPAGE,
+ DALI_KEY_WEBPAGE = Dali::DALI_KEY_WEBPAGE,
+ DALI_KEY_MAIL = Dali::DALI_KEY_MAIL,
+ DALI_KEY_SCREENSAVER = Dali::DALI_KEY_SCREENSAVER,
+ DALI_KEY_BRIGHTNESS_UP = Dali::DALI_KEY_BRIGHTNESS_UP,
+ DALI_KEY_BRIGHTNESS_DOWN = Dali::DALI_KEY_BRIGHTNESS_DOWN,
+ DALI_KEY_SOFT_KBD = Dali::DALI_KEY_SOFT_KBD,
+ DALI_KEY_QUICK_PANEL = Dali::DALI_KEY_QUICK_PANEL,
+ DALI_KEY_TASK_SWITCH = Dali::DALI_KEY_TASK_SWITCH,
+ DALI_KEY_APPS = Dali::DALI_KEY_APPS,
+ DALI_KEY_SEARCH = Dali::DALI_KEY_SEARCH,
+ DALI_KEY_VOICE = Dali::DALI_KEY_VOICE,
+ DALI_KEY_LANGUAGE = Dali::DALI_KEY_LANGUAGE,
+ DALI_KEY_VOLUME_UP = Dali::DALI_KEY_VOLUME_UP,
+ DALI_KEY_VOLUME_DOWN = Dali::DALI_KEY_VOLUME_DOWN,
+
+ /**
+ * @brief Delete key.
+ */
+ DALI_KEY_DELETE = 119,
+
+ /**
+ * @brief Control Left key.
+ */
+ DALI_KEY_CONTROL_LEFT = 37,
+
+ /**
+ * @brief Control Right key.
+ */
+ DALI_KEY_CONTROL_RIGHT = 105,
+
+ /**
+ * @brief Control Return key.
+ */
+ DALI_KEY_RETURN = 36
+
+};
+
+} // namespace DevelKey
+
+} // namespace Dali
+
+#endif // DALI_KEY_DEVEL_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/lifecycle-controller.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/lifecycle-controller-impl.h>
+
+namespace Dali
+{
+
+LifecycleController::LifecycleController()
+{
+}
+
+LifecycleController::LifecycleController(const LifecycleController& controller)
+: BaseHandle(controller)
+{
+}
+
+LifecycleController LifecycleController::Get()
+{
+ return Internal::Adaptor::LifecycleController::Get();
+}
+
+LifecycleController::~LifecycleController()
+{
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::InitSignal()
+{
+ return GetImplementation(*this).InitSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::TerminateSignal()
+{
+ return GetImplementation(*this).TerminateSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::PauseSignal()
+{
+ return GetImplementation(*this).PauseSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::ResumeSignal()
+{
+ return GetImplementation(*this).ResumeSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::ResetSignal()
+{
+ return GetImplementation(*this).ResetSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::ResizeSignal()
+{
+ return GetImplementation(*this).ResizeSignal();
+}
+
+LifecycleController::LifecycleSignalType& LifecycleController::LanguageChangedSignal()
+{
+ return GetImplementation(*this).LanguageChangedSignal();
+}
+
+LifecycleController& LifecycleController::operator=(const LifecycleController& monitor)
+{
+ if( *this != monitor )
+ {
+ BaseHandle::operator=(monitor);
+ }
+ return *this;
+}
+
+LifecycleController::LifecycleController(Internal::Adaptor::LifecycleController* internal)
+: BaseHandle(internal)
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/orientation.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/orientation-impl.h>
+
+namespace Dali
+{
+
+Orientation::Orientation()
+{
+}
+
+Orientation::~Orientation()
+{
+}
+
+Orientation::Orientation(const Orientation& handle)
+: BaseHandle(handle)
+{
+}
+
+Orientation& Orientation::operator=(const Orientation& rhs)
+{
+ BaseHandle::operator=(rhs);
+ return *this;
+}
+
+int Orientation::GetDegrees() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetDegrees();
+}
+
+float Orientation::GetRadians() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetRadians();
+}
+
+Orientation::OrientationSignalType& Orientation::ChangedSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).ChangedSignal();
+}
+
+Orientation::Orientation( Internal::Adaptor::Orientation* orientation )
+: BaseHandle(orientation)
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/performance-logger.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-logger-impl.h>
+
+namespace Dali
+{
+
+PerformanceLogger::PerformanceLogger()
+{
+}
+
+PerformanceLogger PerformanceLogger::New( const char* name )
+{
+ Internal::Adaptor::PerformanceLoggerPtr internal = Internal::Adaptor::PerformanceLogger::New( name );
+ return PerformanceLogger(internal.Get());
+}
+
+PerformanceLogger::PerformanceLogger( const PerformanceLogger& performanceLogger )
+: BaseHandle(performanceLogger)
+{
+}
+
+PerformanceLogger& PerformanceLogger::operator=( const PerformanceLogger& performanceLogger )
+{
+ // check self assignment
+ if( *this != performanceLogger )
+ {
+ BaseHandle::operator=(performanceLogger);
+ }
+ return *this;
+}
+
+PerformanceLogger::~PerformanceLogger()
+{
+}
+
+PerformanceLogger PerformanceLogger::DownCast( BaseHandle handle )
+{
+ return PerformanceLogger( dynamic_cast<Internal::Adaptor::PerformanceLogger*>( handle.GetObjectPtr() ) );
+}
+
+void PerformanceLogger::AddMarker( Marker markerType )
+{
+ Internal::Adaptor::GetImplementation(*this).AddMarker( markerType );
+}
+
+void PerformanceLogger::SetLoggingFrequency( unsigned int logFrequency)
+{
+ Internal::Adaptor::GetImplementation(*this).SetLoggingFrequency( logFrequency );
+}
+
+void PerformanceLogger::EnableLogging( bool enable )
+{
+ Internal::Adaptor::GetImplementation(*this).EnableLogging( enable );
+}
+
+PerformanceLogger::PerformanceLogger(Internal::Adaptor::PerformanceLogger* PerformanceLogger)
+: BaseHandle(PerformanceLogger)
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/physical-keyboard.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/physical-keyboard-impl.h>
+
+namespace Dali
+{
+
+PhysicalKeyboard::PhysicalKeyboard()
+{
+}
+
+PhysicalKeyboard::~PhysicalKeyboard()
+{
+}
+
+PhysicalKeyboard PhysicalKeyboard::Get()
+{
+ // Get the physical keyboard handle
+ PhysicalKeyboard handle = Internal::Adaptor::PhysicalKeyboard::Get();
+
+ // If it's not been created then create one
+ if ( !handle )
+ {
+ handle = Internal::Adaptor::PhysicalKeyboard::New();
+ }
+
+ return handle;
+}
+
+bool PhysicalKeyboard::IsAttached() const
+{
+ return GetImplementation( *this ).IsAttached();
+}
+
+PhysicalKeyboard::PhysicalKeyboardSignalType& PhysicalKeyboard::StatusChangedSignal()
+{
+ return GetImplementation( *this ).StatusChangedSignal();
+}
+
+PhysicalKeyboard::PhysicalKeyboard( Internal::Adaptor::PhysicalKeyboard *impl )
+: BaseHandle(impl)
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+// EXTERNAL INLCUDES
+#include <stdlib.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+namespace Devel
+{
+
+PixelBuffer PixelBuffer::New( unsigned int width,
+ unsigned int height,
+ Dali::Pixel::Format pixelFormat )
+{
+ Internal::Adaptor::PixelBufferPtr internal =
+ Internal::Adaptor::PixelBuffer::New( width, height, pixelFormat );
+ return Devel::PixelBuffer( internal.Get() );
+}
+
+Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer )
+{
+ Dali::PixelData pixelData =
+ Internal::Adaptor::PixelBuffer::Convert( GetImplementation(pixelBuffer) );
+ pixelBuffer.Reset();
+ return pixelData;
+}
+
+Dali::PixelData PixelBuffer::CreatePixelData() const
+{
+ return GetImplementation(*this).CreatePixelData();
+}
+
+
+PixelBuffer::PixelBuffer()
+{
+}
+
+PixelBuffer::~PixelBuffer()
+{
+}
+
+PixelBuffer::PixelBuffer( Internal::Adaptor::PixelBuffer* internal )
+: BaseHandle( internal )
+{
+}
+
+PixelBuffer::PixelBuffer(const PixelBuffer& handle)
+: BaseHandle( handle )
+{
+}
+
+PixelBuffer& PixelBuffer::operator=(const PixelBuffer& rhs)
+{
+ BaseHandle::operator=(rhs);
+ return *this;
+}
+
+unsigned int PixelBuffer::GetWidth() const
+{
+ return GetImplementation(*this).GetWidth();
+}
+
+unsigned int PixelBuffer::GetHeight() const
+{
+ return GetImplementation(*this).GetHeight();
+}
+
+Pixel::Format PixelBuffer::GetPixelFormat() const
+{
+ return GetImplementation(*this).GetPixelFormat();
+}
+
+unsigned char* PixelBuffer::GetBuffer()
+{
+ return GetImplementation(*this).GetBuffer();
+}
+
+void PixelBuffer::ApplyMask( PixelBuffer mask, float contentScale, bool cropToMask )
+{
+ GetImplementation(*this).ApplyMask( GetImplementation( mask ), contentScale, cropToMask );
+}
+
+void PixelBuffer::ApplyGaussianBlur( const float blurRadius )
+{
+ GetImplementation(*this).ApplyGaussianBlur( blurRadius );
+}
+
+void PixelBuffer::Crop( uint16_t x, uint16_t y, uint16_t width, uint16_t height )
+{
+ GetImplementation(*this).Crop( x, y, ImageDimensions( width, height ) );
+}
+
+void PixelBuffer::Resize( uint16_t width, uint16_t height )
+{
+ GetImplementation(*this).Resize( ImageDimensions( width, height ) );
+}
+
+void PixelBuffer::MultiplyColorByAlpha()
+{
+ GetImplementation(*this).MultiplyColorByAlpha();
+}
+
+bool PixelBuffer::GetMetadata( Property::Map& metadata ) const
+{
+ return GetImplementation(*this).GetMetadata(metadata);
+}
+
+} // namespace Devel
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/singleton-service.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+SingletonService::SingletonService()
+{
+}
+
+SingletonService SingletonService::New()
+{
+ return Internal::Adaptor::SingletonService::New();
+}
+
+SingletonService SingletonService::Get()
+{
+ return Internal::Adaptor::SingletonService::Get();
+}
+
+SingletonService::~SingletonService()
+{
+}
+
+void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
+{
+ GetImplementation( *this ).Register( info, singleton );
+}
+
+void SingletonService::UnregisterAll()
+{
+ GetImplementation( *this ).UnregisterAll();
+}
+
+BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
+{
+ return GetImplementation( *this ).GetSingleton( info );
+}
+
+SingletonService::SingletonService( Internal::Adaptor::SingletonService* singletonService )
+: BaseHandle( singletonService )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/sound-player.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/sound-player-impl.h>
+
+namespace Dali
+{
+
+SoundPlayer::SoundPlayer()
+{
+}
+
+SoundPlayer SoundPlayer::Get()
+{
+ return Internal::Adaptor::SoundPlayer::Get();
+}
+
+SoundPlayer::~SoundPlayer()
+{
+}
+
+int SoundPlayer::PlaySound(const std::string fileName)
+{
+ return GetImplementation(*this).PlaySound(fileName);
+}
+
+void SoundPlayer::Stop(int handle)
+{
+ GetImplementation(*this).Stop(handle);
+}
+
+SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal()
+{
+ return GetImplementation(*this).SoundPlayFinishedSignal();
+}
+
+SoundPlayer::SoundPlayer( Internal::Adaptor::SoundPlayer* player )
+: BaseHandle( player )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/styling/common/style-monitor-impl.h>
+
+namespace Dali
+{
+
+StyleMonitor::StyleMonitor()
+{
+}
+
+StyleMonitor::StyleMonitor(const StyleMonitor& monitor)
+: BaseHandle(monitor)
+{
+}
+
+StyleMonitor StyleMonitor::StyleMonitor::Get()
+{
+ return Internal::Adaptor::StyleMonitor::Get();
+}
+
+StyleMonitor::~StyleMonitor()
+{
+}
+
+StyleMonitor StyleMonitor::DownCast( BaseHandle handle )
+{
+ return StyleMonitor( dynamic_cast<Internal::Adaptor::StyleMonitor*>( handle.GetObjectPtr() ) );
+}
+
+std::string StyleMonitor::GetDefaultFontFamily() const
+{
+ return GetImplementation(*this).GetDefaultFontFamily();
+}
+
+std::string StyleMonitor::GetDefaultFontStyle() const
+{
+ return GetImplementation(*this).GetDefaultFontStyle();
+}
+
+int StyleMonitor::GetDefaultFontSize() const
+{
+ return GetImplementation(*this).GetDefaultFontSize();
+}
+
+const std::string& StyleMonitor::GetTheme() const
+{
+ return GetImplementation(*this).GetTheme();
+}
+
+void StyleMonitor::SetTheme(const std::string& themFilePath)
+{
+ return GetImplementation(*this).SetTheme(themFilePath);
+}
+
+bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
+{
+ return GetImplementation(*this).LoadThemeFile( filename, output );
+}
+
+StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
+{
+ return GetImplementation(*this).StyleChangeSignal();
+}
+
+StyleMonitor& StyleMonitor::operator=(const StyleMonitor& monitor)
+{
+ if( *this != monitor )
+ {
+ BaseHandle::operator=(monitor);
+ }
+ return *this;
+}
+
+StyleMonitor::StyleMonitor(Internal::Adaptor::StyleMonitor* internal)
+: BaseHandle(internal)
+{
+}
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_STYLE_MONITOR_H__
+#define __DALI_STYLE_MONITOR_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+#include <dali/public-api/object/base-handle.h>
+#include <dali/public-api/signals/dali-signal.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/style-change.h>
+
+namespace Dali
+{
+
+namespace Internal DALI_INTERNAL
+{
+namespace Adaptor
+{
+class StyleMonitor;
+}
+}
+
+/**
+ * @brief Monitors the platform for style changes.
+ *
+ * This is a handle to the adaptor's style monitor which holds the platform's style information.
+ * It provides a signal when any aspect of the default style changes on the device.
+ * @see Adaptor::GetStyleMonitor
+ */
+class DALI_IMPORT_API StyleMonitor : public BaseHandle
+{
+public: // Typedefs
+
+ typedef Signal< void ( StyleMonitor, StyleChange::Type ) > StyleChangeSignalType; ///< StyleChange Signal type
+
+public: // Creation & Destruction
+
+ /**
+ * @brief Create an uninitialized StyleMonitor handle.
+ *
+ * Tthis can be set by retrieving the style monitor from the Adaptor
+ * or the Application classes. Calling member functions when
+ * uninitialized is not allowed.
+ */
+ StyleMonitor();
+
+ /**
+ * @brief Creates a copy of the handle.
+ *
+ * The copy will point to the same implementation as the original.
+ * @param[in] monitor The Style Monitor to copy from.
+ */
+ StyleMonitor(const StyleMonitor& monitor);
+
+ /**
+ * @brief Retrieve the initialized instance of the StyleMonitor.
+ * @return Handle to StyleMonitor.
+ */
+ static StyleMonitor Get();
+
+ /**
+ * @brief Destructor
+ *
+ * This is non-virtual since derived Handle types must not contain data or virtual methods.
+ */
+ ~StyleMonitor();
+
+ /**
+ * @brief Downcast an Object handle to StyleMonitor handle.
+ *
+ * If handle points to a StyleMonitor object the downcast produces a
+ * valid handle. If not the returned handle is left uninitialized.
+ *
+ * @param[in] handle to An object @return handle to a Timer object
+ * or an uninitialized handle
+ */
+ static StyleMonitor DownCast( BaseHandle handle );
+
+public: // Style Information
+
+ /**
+ * @brief Retrieves the default font family.
+ * @return The default font family.
+ */
+ std::string GetDefaultFontFamily() const;
+
+ /**
+ * @brief Retrieves the default font style.
+ * @return The default font style.
+ */
+ std::string GetDefaultFontStyle() const;
+
+ /**
+ * @brief Retrieves the default font size.
+ *
+ * This is an logical size, which is mapped to a UI Control specific point-size in stylesheets.
+ * For example if zero the smallest size, this could potentially map to TextLabel point-size 8.
+ * @return The default font size, or a negative value if not set.
+ */
+ int GetDefaultFontSize() const;
+
+ /**
+ * @brief Retrieves the user defined Theme.
+ * @return The user defined Theme.
+ */
+ const std::string& GetTheme() const;
+
+ /**
+ * @brief Sets an user defined Theme.
+ * @param[in] themeFilePath Path of the user defined theme
+ */
+ void SetTheme(const std::string& themeFilePath);
+
+ /**
+ * @brief Utility to load a theme file
+ * @param filename of the theme
+ * @param output to write the contents to
+ * @return true if the load is successful
+ */
+ bool LoadThemeFile( const std::string& filename, std::string& output );
+
+public: // Signals
+
+ /**
+ * @brief This signal is emitted whenever the style changes on the device.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(StyleMonitor styleMonitor, StyleChange change);
+ * @endcode
+ * @return The signal to connect to.
+ */
+ StyleChangeSignalType& StyleChangeSignal();
+
+public: // Operators
+
+ /**
+ * @brief Assignment operator.
+ *
+ * The handle points to the same implementation as the one being copied from.
+ * @param[in] monitor The Style Monitor to copy from.
+ * @return reference to this object
+ */
+ StyleMonitor& operator=(const StyleMonitor& monitor);
+
+public: // Not intended for application developers
+ /**
+ * @brief This constructor is used internally to create a handle from an object pointer.
+ * @param [in] styleMonitor A pointer the internal style monitor.
+ */
+ explicit DALI_INTERNAL StyleMonitor(Internal::Adaptor::StyleMonitor* styleMonitor);
+};
+
+} // namespace Dali
+
+#endif // __DALI_STYLE_MONITOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/tilt-sensor.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/sensor/common/tilt-sensor-factory.h>
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+const float TiltSensor::DEFAULT_UPDATE_FREQUENCY = 60.0f;
+
+TiltSensor::TiltSensor()
+{
+}
+
+TiltSensor TiltSensor::Get()
+{
+ return Internal::Adaptor::TiltSensorFactory::Get();
+}
+
+TiltSensor::~TiltSensor()
+{
+}
+
+bool TiltSensor::Start()
+{
+ return GetImplementation(*this).Start();
+}
+
+void TiltSensor::Stop()
+{
+ GetImplementation(*this).Stop();
+}
+
+bool TiltSensor::IsStarted() const
+{
+ return GetImplementation(*this).IsStarted();
+}
+
+float TiltSensor::GetRoll() const
+{
+ return GetImplementation(*this).GetRoll();
+}
+
+float TiltSensor::GetPitch() const
+{
+ return GetImplementation(*this).GetPitch();
+}
+
+Quaternion TiltSensor::GetRotation() const
+{
+ return GetImplementation(*this).GetRotation();
+}
+
+TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal()
+{
+ return GetImplementation(*this).TiltedSignal();
+}
+
+void TiltSensor::SetUpdateFrequency( float frequencyHertz )
+{
+ GetImplementation(*this).SetUpdateFrequency( frequencyHertz );
+}
+
+float TiltSensor::GetUpdateFrequency() const
+{
+ return GetImplementation(*this).GetUpdateFrequency();
+}
+
+void TiltSensor::SetRotationThreshold(Radian rotationThreshold)
+{
+ GetImplementation(*this).SetRotationThreshold( rotationThreshold );
+}
+
+Radian TiltSensor::GetRotationThreshold() const
+{
+ return GetImplementation(*this).GetRotationThreshold();
+}
+
+TiltSensor::TiltSensor( Internal::Adaptor::TiltSensor* sensor )
+: BaseHandle( sensor )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/video-player.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/any.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/video/common/video-player-impl.h>
+
+namespace Dali
+{
+
+VideoPlayer::VideoPlayer()
+{
+}
+
+VideoPlayer::VideoPlayer( Internal::Adaptor::VideoPlayer* internal )
+: BaseHandle( internal )
+{
+}
+
+VideoPlayer::~VideoPlayer()
+{
+}
+
+VideoPlayer VideoPlayer::New()
+{
+ Internal::Adaptor::VideoPlayerPtr player = Internal::Adaptor::VideoPlayer::New();
+
+ if( player )
+ {
+ player->Initialize();
+ }
+
+ return VideoPlayer( player.Get() );
+}
+
+VideoPlayer::VideoPlayer( const VideoPlayer& player )
+: BaseHandle( player )
+{
+}
+
+VideoPlayer& VideoPlayer::operator=( const VideoPlayer& player )
+{
+ if( *this != player )
+ {
+ BaseHandle::operator=( player );
+ }
+ return *this;
+}
+
+VideoPlayer VideoPlayer::DownCast( BaseHandle handle )
+{
+ return VideoPlayer( dynamic_cast< Internal::Adaptor::VideoPlayer* >( handle.GetObjectPtr() ) );
+}
+
+void VideoPlayer::SetUrl( const std::string& url )
+{
+ GetImplementation( *this ).SetUrl( url );
+}
+
+std::string VideoPlayer::GetUrl()
+{
+ return GetImplementation( *this ).GetUrl();
+}
+
+void VideoPlayer::SetLooping(bool looping)
+{
+ GetImplementation( *this ).SetLooping( looping );
+}
+
+bool VideoPlayer::IsLooping()
+{
+ return GetImplementation( *this ).IsLooping();
+}
+
+void VideoPlayer::Play()
+{
+ GetImplementation( *this ).Play();
+}
+
+void VideoPlayer::Pause()
+{
+ GetImplementation( *this ).Pause();
+}
+
+void VideoPlayer::Stop()
+{
+ GetImplementation( *this ).Stop();
+}
+
+void VideoPlayer::SetMute( bool mute )
+{
+ GetImplementation( *this ).SetMute( mute );
+}
+
+bool VideoPlayer::IsMuted()
+{
+ return GetImplementation( *this ).IsMuted();
+}
+
+void VideoPlayer::SetVolume( float left, float right )
+{
+ GetImplementation( *this ).SetVolume( left, right );
+}
+
+void VideoPlayer::GetVolume( float& left, float& right )
+{
+ GetImplementation( *this ).GetVolume( left, right );
+}
+
+void VideoPlayer::SetRenderingTarget( Any target )
+{
+ GetImplementation( *this ).SetRenderingTarget( target );
+}
+
+void VideoPlayer::SetPlayPosition( int millisecond )
+{
+ GetImplementation( *this ).SetPlayPosition( millisecond );
+}
+
+int VideoPlayer::GetPlayPosition()
+{
+ return GetImplementation( *this ).GetPlayPosition();
+}
+
+void VideoPlayer::SetDisplayArea( DisplayArea area )
+{
+ GetImplementation( *this ).SetDisplayArea( area );
+}
+
+void VideoPlayer::SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation )
+{
+ GetImplementation( *this ).SetDisplayRotation( rotation );
+}
+
+Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation()
+{
+ return GetImplementation( *this ).GetDisplayRotation();
+}
+
+Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal()
+{
+ return GetImplementation( *this ).FinishedSignal();
+}
+
+void VideoPlayer::Forward( int millisecond )
+{
+ GetImplementation( *this ).Forward( millisecond );
+}
+
+void VideoPlayer::Backward( int millisecond )
+{
+ GetImplementation( *this ).Backward( millisecond );
+}
+
+bool VideoPlayer::IsVideoTextureSupported() const
+{
+ return GetImplementation( *this ).IsVideoTextureSupported();
+}
+
+} // namespace Dali;
+
--- /dev/null
+#ifndef __DALI_VIDEO_PLAYER_H__
+#define __DALI_VIDEO_PLAYER_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-handle.h>
+
+//INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/video-player-plugin.h>
+
+namespace Dali
+{
+
+class Any;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+ class VideoPlayer;
+} // namespace Adaptor
+
+} // namespace Internal
+
+/**
+ * @brief VideoPlayer class is used for video playback.
+ * @SINCE_1_1.38
+ */
+class DALI_IMPORT_API VideoPlayer: public BaseHandle
+{
+public:
+
+ /**
+ * @brief Constructor.
+ * @SINCE_1_1.38
+ */
+ VideoPlayer();
+
+ /**
+ * @brief Destructor.
+ * @SINCE_1_1.38
+ */
+ ~VideoPlayer();
+
+ /**
+ * @brief Creates a new instance of a VideoPlayer.
+ * @SINCE_1_1.38
+ */
+ static VideoPlayer New();
+
+ /**
+ * @brief Copy constructor.
+ *
+ * @SINCE_1_1.38
+ * @param[in] player VideoPlayer to copy. The copied player will point at the same implementation
+ */
+ VideoPlayer( const VideoPlayer& player );
+
+ /**
+ * @brief Assignment operator.
+ *
+ * @SINCE_1_1.38
+ * @param[in] player The VideoPlayer to assign from.
+ * @return The updated VideoPlayer.
+ */
+ VideoPlayer& operator=( const VideoPlayer& player );
+
+ /**
+ * @brief Downcast a handle to VideoPlayer handle.
+ *
+ * If handle points to a VideoPlayer the downcast produces valid
+ * handle. If not the returned handle is left uninitialized.
+ *
+ * @SINCE_1_1.38
+ * @param[in] handle Handle to an object
+ * @return Handle to a VideoPlayer or an uninitialized handle
+ */
+ static VideoPlayer DownCast( BaseHandle handle );
+
+ /**
+ * @brief Sets a URL of the video file to play.
+ *
+ * @SINCE_1_1.38
+ * @param [in] url The url of video file
+ */
+ void SetUrl( const std::string& url );
+
+ /**
+ * @brief Returns the URL of the video file.
+ * @SINCE_1_1.38
+ * @return Url of string type
+ */
+ std::string GetUrl();
+
+ /**
+ * @brief Sets the player looping status.
+ * @SINCE_1_1.38
+ *
+ * @param [in] looping The new looping status: true or false
+ */
+ void SetLooping(bool looping);
+
+ /**
+ * @brief Returns the player looping status.
+ * @SINCE_1_1.38
+ *
+ * @return True if player is looping, false otherwise.
+ */
+ bool IsLooping();
+
+ /**
+ * @brief Starts the video playback.
+ * @SINCE_1_1.38
+ */
+ void Play();
+
+ /**
+ * @brief Pauses the video playback.
+ * @SINCE_1_1.38
+ */
+ void Pause();
+
+ /**
+ * @brief Stops the video playback.
+ * @SINCE_1_1.38
+ */
+ void Stop();
+
+ /**
+ * @brief Sets the player mute status.
+ * @SINCE_1_1.38
+ * @param[in] mute The new mute status, true is mute.
+ */
+ void SetMute( bool mute );
+
+ /**
+ * @brief Returns the player mute status.
+ * @SINCE_1_1.38
+ * @return True if player is mute.
+ */
+ bool IsMuted();
+
+ /**
+ * @brief Sets the player volume.
+ * @SINCE_1_1.38
+ * @param[in] left The left volume scalar
+ * @param[in] right The right volume scalar
+ */
+ void SetVolume( float left, float right );
+
+ /**
+ * @brief Returns current volume factor.
+ * @SINCE_1_1.38
+ * @param[out] left The current left volume scalar
+ * @param[out] right The current right volume scalar
+ */
+ void GetVolume( float& left, float& right );
+
+ /**
+ * @brief Sets video rendering target.
+ * @SINCE_1_1.38
+ * @param[in] target The target for video rendering, window surface or native image source
+ */
+ void SetRenderingTarget( Any target );
+
+ /**
+ * @brief Sets the position for playback.
+ * @SINCE_1_1.38
+ *
+ * @param[in] millisecond The position for playback
+ */
+ void SetPlayPosition( int millisecond );
+
+ /**
+ * @brief Gets the current position in milliseconds.
+ * @SINCE_1_1.38
+ *
+ * @return The current position of playback
+ */
+ int GetPlayPosition();
+
+ /**
+ * @brief Sets the area of video display.
+ * @SINCE_1_2.46
+ * param[in] area The left-top position and size of the video display area
+ */
+ void SetDisplayArea( DisplayArea area );
+
+ /**
+ * @brief Sets video display rotation
+ * @SINCE_1_1.38
+ * @param[in] rotation The rotation of display
+ */
+ void SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation );
+
+ /**
+ * @brief Returns rotation of current video display
+ * @SINCE_1_1.38
+ * @return The rotation of current display
+ */
+ Dali::VideoPlayerPlugin::DisplayRotation GetDisplayRotation();
+
+ /**
+ * @brief Connect to this signal to be notified when a video playback have finished.
+ *
+ * @SINCE_1_1.38
+ * @return A signal object to connect with.
+ */
+ Dali::VideoPlayerPlugin::VideoPlayerSignalType& FinishedSignal();
+
+ /**
+ * @brief Seeks forward by the specified number of milliseconds.
+ *
+ * @SINCE_1_2.46
+ * @param[in] millisecond The position for forward playback
+ */
+ void Forward( int millisecond );
+
+ /**
+ * @brief Seeks backward by the specified number of milliseconds.
+ *
+ * @SINCE_1_2.46
+ * @param[in] millisecond The position for backward playback
+ */
+ void Backward( int millisecond );
+
+ /**
+ * @brief Checks whether the video texture is supported
+ * @return True if supported, otherwise false.
+ */
+ bool IsVideoTextureSupported() const;
+
+private: // Not intended for application developers
+
+ /**
+ * @brief Internal constructor
+ * @SINCE_1_1.38
+ */
+ explicit DALI_INTERNAL VideoPlayer( Internal::Adaptor::VideoPlayer* internal );
+};
+
+} // namespace Dali;
+
+#endif
+
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/adaptor-framework/virtual-keyboard.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/virtual-keyboard-impl.h>
+
+namespace Dali
+{
+
+namespace VirtualKeyboard
+{
+
+void Show()
+{
+ Internal::Adaptor::VirtualKeyboard::Show();
+}
+
+void Hide()
+{
+ Internal::Adaptor::VirtualKeyboard::Hide();
+}
+
+bool IsVisible()
+{
+ return Internal::Adaptor::VirtualKeyboard::IsVisible();
+}
+
+void ApplySettings( const Property::Map& settingsMap )
+{
+ Internal::Adaptor::VirtualKeyboard::ApplySettings( settingsMap );
+}
+
+void SetReturnKeyType( const InputMethod::ActionButton type )
+{
+ Internal::Adaptor::VirtualKeyboard::SetReturnKeyType( type );
+}
+
+InputMethod::ActionButton GetReturnKeyType()
+{
+ return Internal::Adaptor::VirtualKeyboard::GetReturnKeyType();
+}
+
+void EnablePrediction(const bool enable)
+{
+ Internal::Adaptor::VirtualKeyboard::EnablePrediction(enable);
+}
+
+bool IsPredictionEnabled()
+{
+ return Internal::Adaptor::VirtualKeyboard::IsPredictionEnabled();
+}
+
+Rect<int> GetSizeAndPosition()
+{
+ return Internal::Adaptor::VirtualKeyboard::GetSizeAndPosition();
+}
+
+void RotateTo(int angle)
+{
+ Internal::Adaptor::VirtualKeyboard::RotateTo(angle);
+}
+
+StatusSignalType& StatusChangedSignal()
+{
+ return Internal::Adaptor::VirtualKeyboard::StatusChangedSignal();
+}
+
+KeyboardResizedSignalType& ResizedSignal()
+{
+ return Internal::Adaptor::VirtualKeyboard::ResizedSignal();
+}
+
+LanguageChangedSignalType& LanguageChangedSignal()
+{
+ return Internal::Adaptor::VirtualKeyboard::LanguageChangedSignal();
+}
+
+TextDirection GetTextDirection()
+{
+ return Internal::Adaptor::VirtualKeyboard::GetTextDirection();
+}
+
+} // namespace VirtualKeyboard
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_VIRTUAL_KEYBOARD_H__
+#define __DALI_VIRTUAL_KEYBOARD_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/dali-signal.h>
+#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/math/rect.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/input-method.h>
+
+namespace Dali
+{
+
+/**
+ * @brief This namespace is provided for application developers to be able to show and hide the on-screen keyboard.
+ *
+ * Key events are sent to the actor in focus. Focus is set through the actor Public API.
+ */
+namespace VirtualKeyboard
+{
+
+// Types
+
+typedef Signal< void () > VoidSignalType;
+typedef Signal< void ( bool ) > StatusSignalType;
+typedef Signal< void ( int ) > KeyboardResizedSignalType;
+typedef Signal< void ( int ) > LanguageChangedSignalType;
+
+// Enumerations
+
+/**
+ * @brief The direction of text.
+ */
+enum TextDirection
+{
+ LeftToRight,
+ RightToLeft,
+};
+
+/**
+ * @brief The meaning of the return key.
+ */
+enum ReturnKeyType
+{
+ DEFAULT,
+ DONE,
+ GO,
+ JOIN,
+ LOGIN,
+ NEXT,
+ SEARCH,
+ SEND,
+ SIGNIN
+};
+
+// Functions
+/**
+ * @brief Show the virtual keyboard.
+ */
+DALI_IMPORT_API void Show();
+
+/**
+ * @brief Hide the virtual keyboard.
+ */
+DALI_IMPORT_API void Hide();
+
+/**
+ * @brief Returns whether the virtual keyboard is visible or not.
+ * @return true if visible, false otherwise.
+ */
+DALI_IMPORT_API bool IsVisible();
+
+/**
+ * @brief Set one or more of the Input Method Settings
+ * @param[in] settingsMap Map of Settings to be applied.
+ */
+DALI_IMPORT_API void ApplySettings( const Property::Map& settingsMap );
+
+/**
+ * @brief Set the specific return key into the virtual keyboard.
+ * @param[in] type the kind of return key types.
+ */
+DALI_IMPORT_API void SetReturnKeyType( const InputMethod::ActionButton type );
+
+/**
+ * @brief Retrieve the current return key type.
+ * @return the type of retun key.
+ */
+DALI_IMPORT_API InputMethod::ActionButton GetReturnKeyType();
+
+/**
+ * @brief Enable/disable prediction (predictive text).
+ *
+ * By default prediction text is enabled.
+ * @param[in] enable true or false to enable or disable
+ * Prediction can not be changed while the keyboard is visible. It must be set in advance of showing keyboard.
+ */
+DALI_IMPORT_API void EnablePrediction(const bool enable);
+
+/**
+ * @brief Returns whether prediction is enabled in the virtual keyboard
+ * @return true if predictive text enabled, false otherwise.
+ */
+DALI_IMPORT_API bool IsPredictionEnabled();
+
+/**
+ * @brief Provides size and position of keyboard.
+ *
+ * Position is relative to whether keyboard is visible or not.
+ * If keyboard is not visible then position will be off the screen.
+ * If keyboard is not being shown when this method is called the keyboard is partially setup (IMFContext) to get
+ * the values then taken down. So ideally GetSizeAndPosition() should be called after Show().
+ * @return rect which is keyboard panel x, y, width, height
+ */
+DALI_IMPORT_API Dali::Rect<int> GetSizeAndPosition();
+
+/**
+ * @brief Rotates the keyboard orientation to the given angle.
+ *
+ * A value of 0 indicates the portrait orientation.
+ * Other valid values are 90, 180, 270.
+ * @param angle the angle is in degrees.
+ */
+DALI_IMPORT_API void RotateTo(int angle);
+
+/**
+ * @brief Returns text direction of the keyboard's current input language.
+ * @return The direction of the text.
+ */
+DALI_IMPORT_API TextDirection GetTextDirection();
+
+/**
+ * @brief Connect to this signal to be notified when the virtual keyboard is shown or hidden.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(bool keyboardShown);
+ * @endcode
+ * If the parameter keyboardShown is true, then the keyboard has just shown, if it is false, then it
+ * has just been hidden.
+ * @return The signal to connect to.
+ */
+DALI_IMPORT_API StatusSignalType& StatusChangedSignal();
+
+/**
+ * @brief Connect to this signal to be notified when the virtual keyboard is resized.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName( int resolvedResize );
+ * @endcode
+ * The parameter sends the resolved resize defined by the IMF.
+ *
+ * User can get changed size by using GetSizeAndPosition() in the callback
+ * @return The signal to connect to.
+ */
+DALI_IMPORT_API KeyboardResizedSignalType& ResizedSignal();
+
+/**
+ * @brief Connect to this signal to be notified when the virtual keyboard's language is changed.
+ *
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName( int resolvedLanguage );
+ * @endcode
+ * The parameter sends the resolved language defined by the IMF.
+ *
+ * User can get the text direction of the language by calling GetTextDirection() in the callback.
+ * @return The signal to connect to.
+ */
+DALI_IMPORT_API LanguageChangedSignalType& LanguageChangedSignal();
+
+} // namespace VirtualKeyboard
+
+} // namespace Dali
+
+#endif // __DALI_VIRTUAL_KEYBOARD_H__
--- /dev/null
+devel_api_src_files = \
+ $(adaptor_devel_api_dir)/adaptor-framework/accessibility-adaptor.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/application-devel.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/application-extensions.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/bitmap-saver.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/clipboard.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/clipboard-event-notifier.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/color-controller.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/drag-and-drop-detector.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/environment-variable.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/event-feeder.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/event-thread-callback.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/feedback-player.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/file-loader.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/image-loading.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/gif-loading.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/imf-manager.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/input-method-options.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/orientation.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/performance-logger.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/physical-keyboard.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/pixel-buffer.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/singleton-service.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/sound-player.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/style-monitor.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/tilt-sensor.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/lifecycle-controller.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/video-player.cpp \
+ $(adaptor_devel_api_dir)/adaptor-framework/virtual-keyboard.cpp
+
+
+devel_api_adaptor_framework_header_files = \
+ $(adaptor_devel_api_dir)/adaptor-framework/accessibility-adaptor.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/accessibility-action-handler.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/accessibility-gesture-handler.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/application-devel.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/application-extensions.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/bitmap-saver.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/clipboard-event-notifier.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/clipboard.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/color-controller.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/drag-and-drop-detector.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/environment-variable.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/event-feeder.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/event-thread-callback.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/feedback-plugin.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/feedback-player.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/file-loader.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/image-loading.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/gif-loading.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/imf-manager.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/input-method-devel.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/input-method-options.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/lifecycle-controller.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/orientation.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/performance-logger.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/pixel-buffer.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/render-surface.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/singleton-service.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/sound-player.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/style-monitor.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/tilt-sensor.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/video-player.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/video-player-plugin.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/key-extension-plugin.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/virtual-keyboard.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/physical-keyboard.h \
+ $(adaptor_devel_api_dir)/adaptor-framework/key-devel.h
+
+devel_api_text_abstraction_src_files = \
+ $(adaptor_devel_api_dir)/text-abstraction/bidirectional-support.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/font-client.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/font-list.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/font-metrics.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/glyph-info.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/script.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/segmentation.cpp \
+ $(adaptor_devel_api_dir)/text-abstraction/shaping.cpp
+
+text_abstraction_header_files = \
+ $(adaptor_devel_api_dir)/text-abstraction/bidirectional-support.h \
+ $(adaptor_devel_api_dir)/text-abstraction/font-client.h \
+ $(adaptor_devel_api_dir)/text-abstraction/font-list.h \
+ $(adaptor_devel_api_dir)/text-abstraction/font-metrics.h \
+ $(adaptor_devel_api_dir)/text-abstraction/glyph-info.h \
+ $(adaptor_devel_api_dir)/text-abstraction/script.h \
+ $(adaptor_devel_api_dir)/text-abstraction/segmentation.h \
+ $(adaptor_devel_api_dir)/text-abstraction/shaping.h \
+ $(adaptor_devel_api_dir)/text-abstraction/text-abstraction.h \
+ $(adaptor_devel_api_dir)/text-abstraction/text-abstraction-definitions.h
+
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/text-abstraction/bidirectional-support.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/text/text-abstraction/bidirectional-support-impl.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+BidirectionalSupport::BidirectionalSupport()
+{
+}
+
+BidirectionalSupport::~BidirectionalSupport()
+{
+}
+
+BidirectionalSupport::BidirectionalSupport( Internal::BidirectionalSupport* implementation )
+: BaseHandle( implementation )
+{
+}
+
+BidirectionalSupport BidirectionalSupport::Get()
+{
+ return Internal::BidirectionalSupport::Get();
+}
+
+BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
+ Length numberOfCharacters )
+{
+ return GetImplementation( *this ).CreateInfo( paragraph,
+ numberOfCharacters );
+}
+
+void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
+{
+ GetImplementation( *this ).DestroyInfo( bidiInfoIndex );
+}
+
+void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
+ CharacterIndex firstCharacterIndex,
+ Length numberOfCharacters,
+ CharacterIndex* visualToLogicalMap )
+{
+ GetImplementation( *this ).Reorder( bidiInfoIndex,
+ firstCharacterIndex,
+ numberOfCharacters,
+ visualToLogicalMap );
+}
+
+bool BidirectionalSupport::GetMirroredText( Character* text,
+ CharacterDirection* directions,
+ Length numberOfCharacters )
+{
+ return GetImplementation( *this ).GetMirroredText( text,
+ directions,
+ numberOfCharacters );
+}
+
+bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
+{
+ return GetImplementation( *this ).GetParagraphDirection( bidiInfoIndex );
+}
+
+void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
+ CharacterDirection* directions,
+ Length numberOfCharacters )
+{
+ GetImplementation( *this ).GetCharactersDirection( bidiInfoIndex,
+ directions,
+ numberOfCharacters );
+}
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/text-abstraction/font-client.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/text/text-abstraction/font-client-impl.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+const PointSize26Dot6 FontClient::DEFAULT_POINT_SIZE = 768u; // 12*64
+
+FontClient::GlyphBufferData::GlyphBufferData()
+: buffer( NULL ),
+ width( 0u ),
+ height( 0u ),
+ format( Pixel::A8 )
+{
+}
+
+FontClient::GlyphBufferData::~GlyphBufferData()
+{
+}
+
+FontClient FontClient::Get()
+{
+ return Internal::FontClient::Get();
+}
+
+FontClient::FontClient()
+{
+}
+
+FontClient::~FontClient()
+{
+}
+
+FontClient::FontClient( const FontClient& handle )
+: BaseHandle( handle )
+{
+}
+
+FontClient& FontClient::operator=( const FontClient& handle )
+{
+ BaseHandle::operator=( handle );
+ return *this;
+}
+
+void FontClient::SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi )
+{
+ GetImplementation(*this).SetDpi( horizontalDpi, verticalDpi );
+}
+
+void FontClient::GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi )
+{
+ GetImplementation(*this).GetDpi( horizontalDpi, verticalDpi );
+}
+
+int FontClient::GetDefaultFontSize()
+{
+ return GetImplementation(*this).GetDefaultFontSize();
+}
+
+void FontClient::ResetSystemDefaults()
+{
+ GetImplementation(*this).ResetSystemDefaults();
+}
+
+void FontClient::GetDefaultFonts( FontList& defaultFonts )
+{
+ GetImplementation(*this).GetDefaultFonts( defaultFonts );
+}
+
+void FontClient::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
+{
+ GetImplementation(*this).GetDefaultPlatformFontDescription( fontDescription );
+}
+
+void FontClient::GetSystemFonts( FontList& systemFonts )
+{
+ GetImplementation(*this).GetSystemFonts( systemFonts );
+}
+
+void FontClient::GetDescription( FontId id, FontDescription& fontDescription )
+{
+ GetImplementation(*this).GetDescription( id, fontDescription );
+}
+
+PointSize26Dot6 FontClient::GetPointSize( FontId id )
+{
+ return GetImplementation(*this).GetPointSize( id );
+}
+
+bool FontClient::IsCharacterSupportedByFont( FontId fontId, Character character )
+{
+ return GetImplementation(*this).IsCharacterSupportedByFont( fontId, character );
+}
+
+FontId FontClient::FindDefaultFont( Character charcode,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ return GetImplementation(*this).FindDefaultFont( charcode,
+ requestedPointSize,
+ preferColor );
+}
+
+FontId FontClient::FindFallbackFont( Character charcode,
+ const FontDescription& preferredFontDescription,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ return GetImplementation(*this).FindFallbackFont( charcode, preferredFontDescription, requestedPointSize, preferColor );
+}
+
+FontId FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
+{
+ return GetImplementation(*this).GetFontId( path, requestedPointSize, faceIndex );
+}
+
+FontId FontClient::GetFontId( const FontDescription& fontDescription,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex )
+{
+ return GetImplementation(*this).GetFontId( fontDescription,
+ requestedPointSize,
+ faceIndex );
+}
+
+bool FontClient::IsScalable( const FontPath& path )
+{
+ return GetImplementation(*this).IsScalable( path );
+}
+
+bool FontClient::IsScalable( const FontDescription& fontDescription )
+{
+ return GetImplementation(*this).IsScalable( fontDescription );
+}
+
+void FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes )
+{
+ GetImplementation(*this).GetFixedSizes( path, sizes );
+}
+
+void FontClient::GetFixedSizes( const FontDescription& fontDescription,
+ Dali::Vector< PointSize26Dot6 >& sizes )
+{
+ GetImplementation(*this).GetFixedSizes( fontDescription, sizes );
+}
+
+void FontClient::GetFontMetrics( FontId fontId, FontMetrics& metrics )
+{
+ GetImplementation(*this).GetFontMetrics( fontId, metrics );
+}
+
+GlyphIndex FontClient::GetGlyphIndex( FontId fontId, Character charcode )
+{
+ return GetImplementation(*this).GetGlyphIndex( fontId, charcode );
+}
+
+bool FontClient::GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal )
+{
+ return GetImplementation(*this).GetGlyphMetrics( array, size, type, horizontal );
+}
+
+void FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, GlyphBufferData& data, int outlineWidth )
+{
+ GetImplementation(*this).CreateBitmap( fontId, glyphIndex, data, outlineWidth );
+}
+
+PixelData FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
+{
+ return GetImplementation(*this).CreateBitmap( fontId, glyphIndex, outlineWidth );
+}
+
+void FontClient::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
+{
+ GetImplementation(*this).CreateVectorBlob( fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
+}
+
+const GlyphInfo& FontClient::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
+{
+ return GetImplementation(*this).GetEllipsisGlyph( requestedPointSize );
+}
+
+bool FontClient::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
+{
+ return GetImplementation(*this).IsColorGlyph( fontId, glyphIndex );
+}
+
+FontClient::FontClient( Internal::FontClient* internal )
+: BaseHandle( internal )
+{
+}
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/text-abstraction/segmentation.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/text/text-abstraction/segmentation-impl.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+Segmentation::Segmentation()
+{
+}
+
+Segmentation::~Segmentation()
+{
+}
+
+Segmentation::Segmentation( Internal::Segmentation* implementation )
+: BaseHandle( implementation )
+{
+}
+
+Segmentation Segmentation::Get()
+{
+ return Internal::Segmentation::Get();
+}
+
+void Segmentation::GetLineBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ LineBreakInfo* breakInfo )
+{
+ GetImplementation( *this ).GetLineBreakPositions( text,
+ numberOfCharacters,
+ breakInfo );
+}
+
+void Segmentation::GetWordBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ WordBreakInfo* breakInfo )
+{
+ GetImplementation( *this ).GetWordBreakPositions( text,
+ numberOfCharacters,
+ breakInfo );
+}
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/devel-api/text-abstraction/shaping.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/text/text-abstraction/shaping-impl.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+Shaping::Shaping()
+{
+}
+
+Shaping::~Shaping()
+{
+}
+
+Shaping::Shaping( Internal::Shaping *impl )
+: BaseHandle( impl )
+{
+}
+
+Shaping Shaping::Get()
+{
+ return Internal::Shaping::Get();
+}
+
+Length Shaping::Shape( const Character* const text,
+ Length numberOfCharacters,
+ FontId fontId,
+ Script script )
+{
+ return GetImplementation( *this ).Shape( text,
+ numberOfCharacters,
+ fontId,
+ script );
+}
+
+void Shaping::GetGlyphs( GlyphInfo* glyphInfo,
+ CharacterIndex* glyphToCharacterMap )
+{
+ GetImplementation( *this ).GetGlyphs( glyphInfo,
+ glyphToCharacterMap );
+}
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTEGRATION_ADAPTOR_H__
+#define __DALI_INTEGRATION_ADAPTOR_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/callback.h>
+#include <dali/public-api/signals/dali-signal.h>
+#include <dali/public-api/math/rect.h>
+#include <dali/public-api/events/touch-event.h>
+#include <dali/public-api/common/view-mode.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/window.h>
+#include <dali/public-api/adaptor-framework/application-configuration.h>
+
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+namespace Adaptor
+{
+class Adaptor;
+}
+}
+
+/**
+ * @brief An Adaptor object is used to initialize and control how Dali runs.
+ *
+ * It provides a lifecycle interface that allows the application
+ * writer to provide their own main loop and other platform related
+ * features.
+ *
+ * The Adaptor class provides a means for initialising the resources required by the Dali::Core.
+ *
+ * When dealing with platform events, the application writer MUST ensure that Dali is called in a
+ * thread-safe manner.
+ *
+ * As soon as the Adaptor class is created and started, the application writer can initialise their
+ * Dali::Actor objects straight away or as required by the main loop they intend to use (there is no
+ * need to wait for an initialise signal as per the Dali::Application class).
+ *
+ * The Adaptor does emit a Resize signal which informs the user when the surface is resized.
+ * Tizen and Linux Adaptors should follow the example below:
+ *
+ * @code
+ * void CreateProgram(DaliAdaptor& adaptor)
+ * {
+ * // Create Dali components...
+ * // Can instantiate adaptor here instead, if required
+ * }
+ *
+ * int main ()
+ * {
+ * // Initialise platform
+ * MyPlatform.Init();
+ *
+ * // Create an 800 by 1280 window positioned at (0,0).
+ * Dali::PositionSize positionSize(0, 0, 800, 1280);
+ * Dali::Window window = Dali::Window::New( positionSize, "My Application" );
+ *
+ * // Create an adaptor which uses that window for rendering
+ * Dali::Adaptor adaptor = Dali::Adaptor::New( window );
+ * adaptor.Start();
+ *
+ * CreateProgram(adaptor);
+ * // Or use this as a callback function depending on the platform initialisation sequence.
+ *
+ * // Start Main Loop of your platform
+ * MyPlatform.StartMainLoop();
+ *
+ * return 0;
+ * }
+ * @endcode
+ *
+ * If required, you can also connect class member functions to a signal:
+ *
+ * @code
+ * MyApplication application;
+ * adaptor.ResizedSignal().Connect(&application, &MyApplication::Resize);
+ * @endcode
+ *
+ * @see RenderSurface
+ */
+class DALI_IMPORT_API Adaptor
+{
+public:
+
+ typedef Signal< void (Adaptor&) > AdaptorSignalType; ///< Generic Type for adaptor signals
+
+public:
+ /**
+ * @brief Create a new adaptor using the window.
+ *
+ * @param[in] window The window to draw onto
+ * @return a reference to the adaptor handle
+ */
+ static Adaptor& New( Window window );
+
+ /**
+ * @brief Create a new adaptor using the window.
+ *
+ * @param[in] window The window to draw onto
+ * @param[in] configuration The context loss configuration.
+ * @return a reference to the adaptor handle
+ */
+ static Adaptor& New( Window window, Configuration::ContextLoss configuration );
+
+ /**
+ * @brief Create a new adaptor using render surface.
+ *
+ * @param[in] nativeWindow native window handle
+ * @param[in] surface The surface to draw onto
+ * @return a reference to the adaptor handle
+ */
+ static Adaptor& New( Any nativeWindow, const Dali::RenderSurface& surface );
+
+ /**
+ * @brief Create a new adaptor using render surface.
+ *
+ * @param[in] nativeWindow native window handle
+ * @param[in] surface The surface to draw onto
+ * @param[in] configuration The context loss configuration.
+ * @return a reference to the adaptor handle
+ */
+ static Adaptor& New( Any nativeWindow, const Dali::RenderSurface& surface, Configuration::ContextLoss configuration = Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS);
+
+ /**
+ * @brief Virtual Destructor.
+ */
+ virtual ~Adaptor();
+
+public:
+
+ /**
+ * @brief Starts the Adaptor.
+ */
+ void Start();
+
+ /**
+ * @brief Pauses the Adaptor.
+ */
+ void Pause();
+
+ /**
+ * @brief Resumes the Adaptor, if previously paused.
+ *
+ * @note If the adaptor is not paused, this does not do anything.
+ */
+ void Resume();
+
+ /**
+ * @brief Stops the Adaptor.
+ */
+ void Stop();
+
+ /**
+ * @brief Ensures that the function passed in is called from the main loop when it is idle.
+ * @note Function must be called from the main event thread only.
+ *
+ * A callback of the following type may be used:
+ * @code
+ * void MyFunction();
+ * @endcode
+ *
+ * @param[in] callback The function to call.
+ * @return true if added successfully, false otherwise
+ *
+ * @note Ownership of the callback is passed onto this class.
+ */
+ bool AddIdle( CallbackBase* callback );
+
+ /**
+ * @brief Removes a previously added @p callback.
+ * @note Function must be called from the main event thread only.
+ *
+ * Does nothing if the @p callback doesn't exist.
+ *
+ * @param[in] callback The callback to be removed.
+ */
+ void RemoveIdle( CallbackBase* callback );
+
+ /**
+ * @brief Replaces the rendering surface
+ *
+ * @param[in] nativeWindow native window handle
+ * @param[in] surface to use
+ */
+ void ReplaceSurface( Any nativeWindow, Dali::RenderSurface& surface );
+
+ /**
+ * @brief Get the render surface the adaptor is using to render to.
+ *
+ * @return reference to current render surface
+ */
+ RenderSurface& GetSurface();
+
+ /**
+ * @brief Gets native window handle
+ *
+ * @return Native window handle
+ */
+ Any GetNativeWindowHandle();
+
+ /**
+ * @brief Release any locks the surface may hold.
+ *
+ * For example, after compositing an offscreen surface, use this method to allow
+ * rendering to continue.
+ */
+ void ReleaseSurfaceLock();
+
+ /**
+ * @brief Set the number of frames per render.
+ *
+ * This enables an application to deliberately render with a reduced FPS.
+ * @param[in] numberOfVSyncsPerRender The number of vsyncs between successive renders.
+ * Suggest this is a power of two:
+ * 1 - render each vsync frame
+ * 2 - render every other vsync frame
+ * 4 - render every fourth vsync frame
+ * 8 - render every eighth vsync frame
+ */
+ void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender );
+
+ /**
+ * @brief Set whether the frame count per render is managed using the hardware VSync or
+ * manually timed.
+ *
+ * @param[in] useHardware True if the hardware VSync should be used
+ */
+ void SetUseHardwareVSync(bool useHardware);
+
+ /**
+ * @brief Returns a reference to the instance of the adaptor used by the current thread.
+ *
+ * @return A reference to the adaptor.
+ * @pre The adaptor has been initialised.
+ * @note This is only valid in the main thread.
+ */
+ static Adaptor& Get();
+
+ /**
+ * @brief Checks whether the adaptor is available.
+ *
+ * @return true, if it is available, false otherwise.
+ */
+ static bool IsAvailable();
+
+ /**
+ * @brief Call this method to notify Dali when scene is created and initialized.
+ *
+ * Notify Adaptor that the scene has been created.
+ */
+ void NotifySceneCreated();
+
+ /**
+ * @brief Call this method to notify Dali when the system language changes.
+ *
+ * Use this only when NOT using Dali::Application, As Application created using
+ * Dali::Application will automatically receive notification of language change.
+ * When Dali::Application is not used, the application developer should
+ * use app-core to receive language change notifications and should update Dali
+ * by calling this method.
+ */
+ void NotifyLanguageChanged();
+
+ /**
+ * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
+ * trigger a pinch gesture
+ *
+ * @param[in] distance The minimum pinch distance in pixels
+ */
+ void SetMinimumPinchDistance(float distance);
+
+ /**
+ * @brief Feed a touch point to the adaptor.
+ *
+ * @param[in] point touch point
+ * @param[in] timeStamp time value of event
+ */
+ void FeedTouchPoint( TouchPoint& point, int timeStamp );
+
+ /**
+ * @brief Feed a wheel event to the adaptor.
+ *
+ * @param[in] wheelEvent wheel event
+ */
+ void FeedWheelEvent( WheelEvent& wheelEvent );
+
+ /**
+ * @brief Feed a key event to the adaptor.
+ *
+ * @param[in] keyEvent The key event holding the key information.
+ */
+ void FeedKeyEvent( KeyEvent& keyEvent );
+
+ /**
+ * @copydoc Dali::Core::SceneCreated();
+ */
+ void SceneCreated();
+
+ /**
+ * @copydoc Dali::Application::SetViewMode();
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::Application::SetStereoBase();
+ */
+ void SetStereoBase( float stereoBase );
+
+ /**
+ * @brief Renders once more even if we're paused
+ * @note Will not work if the window is hidden.
+ */
+ void RenderOnce();
+
+public: // Signals
+
+ /**
+ * @brief The user should connect to this signal if they need to perform any
+ * special activities when the surface Dali is being rendered on is resized.
+ *
+ * @return The signal to connect to
+ */
+ AdaptorSignalType& ResizedSignal();
+
+ /**
+ * @brief This signal is emitted when the language is changed on the device.
+ *
+ * @return The signal to connect to
+ */
+ AdaptorSignalType& LanguageChangedSignal();
+
+private:
+
+ // Undefined
+ Adaptor(const Adaptor&);
+ Adaptor& operator=(Adaptor&);
+
+private:
+
+ /**
+ * @brief Create an uninitialized Adaptor.
+ */
+ Adaptor();
+
+ Internal::Adaptor::Adaptor* mImpl; ///< Implementation object
+ friend class Internal::Adaptor::Adaptor;
+};
+
+} // namespace Dali
+
+#endif // __DALI_INTEGRATION_ADAPTOR_H__
--- /dev/null
+adaptor_integration_api_header_files = \
+ $(adaptor_integration_api_dir)/adaptor.h \
+ $(adaptor_integration_api_dir)/egl-interface.h \
+ $(adaptor_integration_api_dir)/thread-synchronization-interface.h \
+ $(adaptor_integration_api_dir)/trigger-event-interface.h \
+ $(adaptor_integration_api_dir)/trigger-event-factory-interface.h \
+ $(adaptor_integration_api_dir)/trigger-event-factory.h
+
+adaptor_integration_wayland_api_header_files = \
+ $(adaptor_integration_api_dir)/wayland/wl-types.h \
+ $(adaptor_integration_api_dir)/wayland/ecore-wl-render-surface.h \
+ $(adaptor_integration_api_dir)/wayland/native-render-surface.h \
+ $(adaptor_integration_api_dir)/native-render-surface-factory.h
+
+adaptor_integration_ecore_wayland_api_header_files = \
+ $(adaptor_integration_api_dir)/../internal/input/common/imf-manager-impl.h
+
+adaptor_integration_x11_api_header_files = \
+ $(adaptor_integration_api_dir)/x11/ecore-x-types.h \
+ $(adaptor_integration_api_dir)/x11/ecore-x-render-surface.h \
+ $(adaptor_integration_api_dir)/x11/pixmap-render-surface.h \
+ $(adaptor_integration_api_dir)/x11/imf-manager-impl.h \
+ $(adaptor_integration_api_dir)/pixmap-render-surface-factory.h
--- /dev/null
+#ifndef __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
+#define __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/callback.h>
+
+// INTERNAL INCLUDES
+#ifdef DALI_ADAPTOR_COMPILATION
+#include <dali/integration-api/trigger-event-interface.h>
+#else
+#include <dali/integration-api/adaptors/trigger-event-interface.h>
+#endif
+
+namespace Dali
+{
+
+/**
+ * @brief Trigger interface factory class for creating a TriggerEvents
+ *
+ */
+class TriggerEventFactoryInterface
+{
+public:
+
+
+ /**
+ * @brief Create a new concrete implementation of the event trigger interface.
+ * @param callback called when interface->Trigger() is called
+ * @param options TriggerEventInterface option
+ * @return pointer to a new trigger event
+ * @note Ownership of callback should be taken over by deriving classes
+ */
+ virtual TriggerEventInterface* CreateTriggerEvent( CallbackBase* callback,
+ TriggerEventInterface::Options options ) = 0;
+ /**
+ * @brief destroy a trigger event
+ * @param triggerEventInterface event to destroy
+ */
+ virtual void DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface ) = 0;
+
+protected:
+
+ /**
+ * @brief Constructor
+ */
+ TriggerEventFactoryInterface()
+ {
+ }
+
+ /**
+ * @brief Virtual Destructor
+ */
+ virtual ~TriggerEventFactoryInterface()
+ {
+ }
+
+private:
+
+
+ // Undefined copy constructor.
+ TriggerEventFactoryInterface( const TriggerEventFactoryInterface& );
+
+ // Undefined assignment operator.
+ TriggerEventFactoryInterface& operator=( const TriggerEventFactoryInterface& );
+
+};
+
+} // namespace Dali
+
+#endif // __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_INTERFACE_H__
--- /dev/null
+#ifndef __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
+#define __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+#ifdef DALI_ADAPTOR_COMPILATION
+#include <dali/integration-api/trigger-event-factory-interface.h>
+#else
+#include <dali/integration-api/adaptors/trigger-event-factory-interface.h>
+#endif
+
+namespace Dali
+{
+
+/**
+ * @brief Trigger interface factory class
+ *
+ */
+class DALI_IMPORT_API TriggerEventFactory : public TriggerEventFactoryInterface
+{
+
+public:
+
+ /**
+ * @brief Constructor
+ */
+ TriggerEventFactory()
+ {
+ }
+
+ /**
+ * @brief Destructor
+ */
+ virtual ~TriggerEventFactory()
+ {
+ }
+
+ /**
+ * @copydoc TriggerEventFactoryInterface::CreateTriggerEvent
+ */
+ virtual TriggerEventInterface* CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options );
+
+
+ /**
+ * @copydoc TriggerEventFactoryInterface::DestroyTriggerEvent
+ */
+ virtual void DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface );
+
+};
+
+} // namespace Dali
+
+#endif // __DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H__
--- /dev/null
+#ifndef __DALI_ECORE_WL_RENDER_SURFACE_H__
+#define __DALI_ECORE_WL_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_Wayland.h>
+#include <dali/public-api/common/dali-common.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/integration-api/egl-interface.h>
+
+namespace Dali
+{
+
+class TriggerEventInterface;
+
+namespace ECore
+{
+
+/**
+ * Ecore Wayland implementation of render surface.
+ * @todo change namespace to ECore_Wayland as the class
+ * is no longer pure Wayland.
+ */
+class DALI_IMPORT_API EcoreWlRenderSurface : public Dali::RenderSurface
+{
+public:
+ /**
+ * Uses an Wayland surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ EcoreWlRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent = false);
+
+ /**
+ * Destructor.
+ * Will delete the display, if it has ownership.
+ * Will delete the window/pixmap if it has owner ship
+ */
+ virtual ~EcoreWlRenderSurface();
+
+protected:
+ /**
+ * Second stage construction
+ * Creates the surface (window, pixmap or native buffer)
+ */
+ void Init( Any surface );
+
+public: // API
+
+ /**
+ * @brief Sets the render notification trigger to call when render thread is completed a frame
+ *
+ * @param renderNotification to use
+ */
+ void SetRenderNotification(TriggerEventInterface* renderNotification);
+
+ /**
+ * @brief Get window handle
+ *
+ * @return the Ecore X window handle
+ */
+ virtual Ecore_Wl_Window* GetWlWindow();
+
+ /**
+ * Get the surface as an Ecore_Wl_Window
+ */
+ virtual Ecore_Wl_Window* GetDrawable();
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::GetPositionSize()
+ */
+ virtual PositionSize GetPositionSize() const;
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::MoveResize()
+ */
+ virtual void MoveResize( Dali::PositionSize positionSize);
+
+ /**
+ * @copydoc Dali::RenderSurface::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender() = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::ReleaseLock()
+ */
+ virtual void ReleaseLock() = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::GetSurfaceType()
+ */
+ virtual RenderSurface::Type GetSurfaceType();
+
+private:
+
+ /**
+ * Get the surface id if the surface parameter is not empty
+ * @param surface Any containing a surface id, or can be empty
+ * @return surface id, or zero if surface is empty
+ */
+ unsigned int GetSurfaceId( Any surface ) const;
+
+protected:
+
+ /**
+ * Create XRenderable
+ */
+ virtual void CreateWlRenderable() = 0;
+
+ /**
+ * Use an existing render surface
+ * @param surfaceId the id of the surface
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId ) = 0;
+
+protected: // Data
+
+ PositionSize mPositionSize; ///< Position
+ std::string mTitle; ///< Title of window which shows from "xinfo -topvwins" command
+ TriggerEventInterface* mRenderNotification; ///< Render notification trigger
+ ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit)
+ bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it)
+};
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_ECORE_WL_RENDER_SURFACE_H__
--- /dev/null
+#ifndef __DALI_NATIVE_RENDER_SURFACE_H__
+#define __DALI_NATIVE_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <tbm_surface.h>
+#include <dali/public-api/common/dali-common.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#ifdef DALI_ADAPTOR_COMPILATION
+#include <dali/integration-api/egl-interface.h>
+#else
+#include <dali/integration-api/adaptors/egl-interface.h>
+#endif
+
+namespace Dali
+{
+
+class TriggerEventInterface;
+
+/**
+ * Ecore X11 implementation of render surface.
+ */
+class DALI_IMPORT_API NativeRenderSurface : public Dali::RenderSurface
+{
+public:
+
+ /**
+ * Uses an Wayland surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ NativeRenderSurface( Dali::PositionSize positionSize,
+ const std::string& name,
+ bool isTransparent = false );
+
+ /**
+ * @copydoc Dali::RenderSurface::~RenderSurface
+ */
+ virtual ~NativeRenderSurface();
+
+public: // API
+
+ /**
+ * @brief Sets the render notification trigger to call when render thread is completed a frame
+ *
+ * @param renderNotification to use
+ */
+ void SetRenderNotification( TriggerEventInterface* renderNotification );
+
+ /**
+ * @brief Gets the tbm surface for offscreen rendering
+ */
+ virtual tbm_surface_h GetDrawable();
+
+ /**
+ * @brief Gets the surface
+ *
+ * @return TBM surface
+ */
+ virtual Any GetSurface();
+
+ /**
+ * @brief Waits until surface is replaced
+ * After tbm surface is acquired in PostRender, this function is finished.
+ */
+ void WaitUntilSurfaceReplaced();
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::GetPositionSize()
+ */
+ virtual PositionSize GetPositionSize() const;
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::MoveResize()
+ */
+ virtual void MoveResize( Dali::PositionSize positionSize);
+
+ /**
+ * @copydoc Dali::RenderSurface::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::StopRender()
+ */
+ virtual void StopRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::SetThreadSynchronization
+ */
+ virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
+
+ /**
+ * @copydoc Dali::RenderSurface::GetSurfaceType()
+ */
+ virtual RenderSurface::Type GetSurfaceType();
+
+private:
+
+ /**
+ * Release any locks.
+ */
+ void ReleaseLock();
+
+ /**
+ * Create tbm surface
+ */
+ virtual void CreateNativeRenderable();
+
+ /**
+ * Release tbm surface
+ */
+ void ReleaseDrawable();
+
+private: // Data
+
+ struct Impl;
+
+ Impl* mImpl;
+
+};
+
+} // namespace Dali
+
+#endif // __DALI_NATIVE_RENDER_SURFACE_H__
--- /dev/null
+#ifndef __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+#define __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/ecore-wl-render-surface.h>
+
+namespace Dali
+{
+
+namespace ECore
+{
+
+/**
+ * Ecore X11 implementation of render surface.
+ */
+class PixmapRenderSurface : public EcoreWlRenderSurface
+{
+public:
+
+ /**
+ * Uses an Wayland surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a Wayland-window (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ PixmapRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent = false);
+
+ /**
+ * @copydoc Dali::RenderSurface::~RenderSurface
+ */
+ virtual ~PixmapRenderSurface();
+
+public: // API
+
+ /**
+ * @copydoc Dali::ECore::EcoreWlRenderSurface::GetDrawable()
+ */
+ virtual Ecore_Wl_Window* GetDrawable();
+
+ /**
+ * @brief GetSurface
+ *
+ * @return pixmap
+ */
+ virtual Any GetSurface();
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::StopRender()
+ */
+ virtual void StopRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::SetThreadSynchronization
+ */
+ virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
+
+private:
+ enum SyncMode
+ {
+ SYNC_MODE_NONE,
+ SYNC_MODE_WAIT
+ };
+
+ /**
+ * Set the sync mode.
+ * @param[in] syncMode The sync mode
+ */
+ void SetSyncMode( SyncMode syncMode );
+
+ /**
+ * If sync mode is WAIT, then acquire a lock. This prevents render thread from
+ * continuing until the pixmap has been drawn by the compositor.
+ * It must be released for rendering to continue.
+ */
+ void AcquireLock();
+
+ /**
+ * Release any locks.
+ */
+ void ReleaseLock();
+
+ /**
+ * Create XPixmap
+ */
+ virtual void CreateWlRenderable();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::ECore::RenderSurface::UseExistingRenderable
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId );
+
+private: // Data
+
+};
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
--- /dev/null
+#ifndef __DALI_ECORE_X_RENDER_SURFACE_H__
+#define __DALI_ECORE_X_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_X.h>
+#include <dali/public-api/common/dali-common.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/integration-api/x11/ecore-x-types.h>
+#include <dali/integration-api/egl-interface.h>
+
+namespace Dali
+{
+
+class TriggerEventInterface;
+
+namespace ECore
+{
+
+/**
+ * Ecore X11 implementation of render surface.
+ * @todo change namespace to ECore_X11 as the class
+ * is no longer pure X11.
+ */
+class DALI_IMPORT_API EcoreXRenderSurface : public Dali::RenderSurface
+{
+public:
+ /**
+ * Uses an X11 surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ EcoreXRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent = false);
+
+ /**
+ * Destructor.
+ * Will delete the display, if it has ownership.
+ * Will delete the window/pixmap if it has owner ship
+ */
+ virtual ~EcoreXRenderSurface();
+
+protected:
+ /**
+ * Second stage construction
+ * Creates the surface (window, pixmap or native buffer)
+ */
+ void Init( Any surface );
+
+public: // API
+
+ /**
+ * @brief Sets the render notification trigger to call when render thread is completed a frame
+ *
+ * @param renderNotification to use
+ */
+ void SetRenderNotification(TriggerEventInterface* renderNotification);
+
+ /**
+ * @brief Get window handle
+ *
+ * @return the Ecore X window handle
+ */
+ Ecore_X_Window GetXWindow();
+
+ /**
+ * Get the surface as an Ecore_X_drawable
+ */
+ virtual Ecore_X_Drawable GetDrawable();
+
+ /**
+ * @brief Get the render surface the adaptor is using to render to.
+ *
+ * @return reference to current render surface (eg, pixmap / window)
+ */
+ virtual Any GetSurface() = 0;
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::GetPositionSize()
+ */
+ virtual PositionSize GetPositionSize() const;
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::MoveResize()
+ */
+ virtual void MoveResize( Dali::PositionSize positionSize);
+
+ /**
+ * @copydoc Dali::RenderSurface::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender() = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface ) = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::ReleaseLock()
+ */
+ virtual void ReleaseLock() = 0;
+
+ /**
+ * @copydoc Dali::RenderSurface::GetSurfaceType()
+ */
+ virtual RenderSurface::Type GetSurfaceType();
+
+private:
+
+ /**
+ * Get the surface id if the surface parameter is not empty
+ * @param surface Any containing a surface id, or can be empty
+ * @return surface id, or zero if surface is empty
+ */
+ unsigned int GetSurfaceId( Any surface ) const;
+
+protected:
+
+ /**
+ * Create XRenderable
+ */
+ virtual void CreateXRenderable() = 0;
+
+ /**
+ * Use an existing render surface
+ * @param surfaceId the id of the surface
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId ) = 0;
+
+protected: // Data
+
+ PositionSize mPosition; ///< Position
+ std::string mTitle; ///< Title of window which shows from "xinfo -topvwins" command
+ TriggerEventInterface* mRenderNotification; ///< Render notification trigger
+ ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit)
+ bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it)
+};
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_ECORE_X_RENDER_SURFACE_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_IMF_MANAGER_H
+#define __DALI_INTERNAL_IMF_MANAGER_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_IMF.h>
+#include <Ecore_X.h>
+
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class DALI_IMPORT_API ImfManager : public Dali::BaseObject
+{
+public:
+ typedef Dali::ImfManager::ImfManagerSignalType ImfManagerSignalType;
+ typedef Dali::ImfManager::ImfEventSignalType ImfEventSignalType;
+ typedef Dali::ImfManager::StatusSignalType ImfStatusSignalType;
+ typedef Dali::ImfManager::VoidSignalType ImfVoidSignalType;
+ typedef Dali::ImfManager::KeyboardTypeSignalType ImfKeyboardTypeSignalType;
+ typedef Dali::ImfManager::KeyboardResizedSignalType KeyboardResizedSignalType;
+ typedef Dali::ImfManager::LanguageChangedSignalType LanguageChangedSignalType;
+
+public:
+
+ /**
+ * Check whether the ImfManager is available.
+ * @return true if available, false otherwise
+ */
+ static bool IsAvailable();
+
+ /**
+ * Get the IMF manager instance, it creates the instance if it has not already been created.
+ * Internally, a check should be made using IsAvailable() before this is called as we do not want
+ * to create an instance if not needed by applications.
+ * @see IsAvailable()
+ */
+ static Dali::ImfManager Get();
+
+ /**
+ * Constructor
+ * @param[in] ecoreXwin, The window is created by application.
+ */
+ ImfManager( Ecore_X_Window ecoreXwin );
+
+ /**
+ * Connect Callbacks required for IMF.
+ * If you don't connect imf callbacks, you can't get the key events.
+ * The events are PreeditChanged, Commit and DeleteSurrounding.
+ */
+ void ConnectCallbacks();
+
+ /**
+ * Disconnect Callbacks attached to imf context.
+ */
+ void DisconnectCallbacks();
+
+ /**
+ * @copydoc Dali::ImfManager::Activate()
+ */
+ void Activate();
+
+ /**
+ * @copydoc Dali::ImfManager::Deactivate()
+ */
+ void Deactivate();
+
+ /**
+ * @copydoc Dali::ImfManager::Reset()
+ */
+ void Reset();
+
+ /**
+ * @copydoc Dali::ImfManager::GetContext()
+ */
+ Ecore_IMF_Context* GetContext();
+
+ /**
+ * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
+ */
+ bool RestoreAfterFocusLost() const;
+
+ /**
+ * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
+ */
+ void SetRestoreAfterFocusLost( bool toggle );
+
+ /**
+ * @copydoc Dali::ImfManager::PreEditChanged()
+ */
+ void PreEditChanged( void* data, Ecore_IMF_Context* imfContext, void* event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void CommitReceived( void* data, Ecore_IMF_Context* imfContext, void* event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ Eina_Bool RetrieveSurrounding( void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition );
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteSurrounding()
+ */
+ void DeleteSurrounding( void* data, Ecore_IMF_Context* imfContext, void* event_info );
+
+ // Cursor related
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void NotifyCursorPosition();
+
+ /**
+ * @copydoc Dali::ImfManager::SetCursorPosition()
+ */
+ void SetCursorPosition( unsigned int cursorPosition );
+
+ /**
+ * @copydoc Dali::ImfManager::GetCursorPosition()
+ */
+ unsigned int GetCursorPosition() const;
+
+ /**
+ * @copydoc Dali::ImfManager::SetSurroundingText()
+ */
+ void SetSurroundingText( const std::string& text );
+
+ /**
+ * @copydoc Dali::ImfManager::GetSurroundingText()
+ */
+ const std::string& GetSurroundingText() const;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
+ */
+ void NotifyTextInputMultiLine( bool multiLine );
+
+ /**
+ * @copydoc Dali::ImfManager::GetTextDirection()
+ */
+ Dali::ImfManager::TextDirection GetTextDirection();
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputMethodArea()
+ */
+ Dali::Rect<int> GetInputMethodArea();
+
+ /**
+ * @copydoc Dali::ImfManager::ApplyOptions()
+ */
+ void ApplyOptions( const InputMethodOptions& options );
+
+ /**
+ * @copydoc Dali::ImfManager::SetInputPanelData()
+ */
+ void SetInputPanelData( const std::string& data );
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelData()
+ */
+ void GetInputPanelData( std::string& data );
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelState()
+ */
+ Dali::ImfManager::State GetInputPanelState();
+
+ /**
+ * @copydoc Dali::ImfManager::SetReturnKeyState()
+ */
+ void SetReturnKeyState( bool visible );
+
+ /**
+ * @copydoc Dali::ImfManager::AutoEnableInputPanel()
+ */
+ void AutoEnableInputPanel( bool enabled );
+
+ /**
+ * @copydoc Dali::ImfManager::ShowInputPanel()
+ */
+ void ShowInputPanel();
+
+ /**
+ * @copydoc Dali::ImfManager::HideInputPanel()
+ */
+ void HideInputPanel();
+
+ /**
+ * @copydoc Dali::ImfManager::GetKeyboardType()
+ */
+ Dali::ImfManager::KeyboardType GetKeyboardType();
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelLocale()
+ */
+ std::string GetInputPanelLocale();
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::ImfManager::ActivatedSignal()
+ */
+ ImfManagerSignalType& ActivatedSignal() { return mActivatedSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::EventReceivedSignal()
+ */
+ ImfEventSignalType& EventReceivedSignal() { return mEventSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::StatusChangedSignal()
+ */
+ ImfStatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::ResizedSignal()
+ */
+ KeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::LanguageChangedSignal()
+ */
+ LanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::KeyboardTypeChangedSignal()
+ */
+ ImfKeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; }
+protected:
+
+ /**
+ * Destructor.
+ */
+ virtual ~ImfManager();
+
+private:
+ /**
+ * Context created the first time and kept until deleted.
+ * @param[in] ecoreXwin, The window is created by application.
+ */
+ void CreateContext( Ecore_X_Window ecoreXwin );
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteContext()
+ */
+ void DeleteContext();
+
+private:
+ // Undefined
+ ImfManager( const ImfManager& );
+ ImfManager& operator=( ImfManager& );
+
+private:
+ Ecore_IMF_Context* mIMFContext;
+ int mIMFCursorPosition;
+ std::string mSurroundingText;
+
+ bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
+ bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected.
+ InputMethodOptions mOptions;
+
+ ImfManagerSignalType mActivatedSignal;
+ ImfEventSignalType mEventSignal;
+ ImfStatusSignalType mKeyboardStatusSignal;
+ KeyboardResizedSignalType mKeyboardResizeSignal;
+ LanguageChangedSignalType mKeyboardLanguageChangedSignal;
+ ImfKeyboardTypeSignalType mKeyboardTypeChangedSignal;
+
+public:
+
+DALI_IMPORT_API inline static Internal::Adaptor::ImfManager& GetImplementation(Dali::ImfManager& imfManager)
+{
+ DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
+
+ BaseObject& handle = imfManager.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::ImfManager&>(handle);
+}
+
+DALI_IMPORT_API inline static const Internal::Adaptor::ImfManager& GetImplementation(const Dali::ImfManager& imfManager)
+{
+ DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
+
+ const BaseObject& handle = imfManager.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::ImfManager&>(handle);
+}
+
+};
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_IMF_MANAGER_H
--- /dev/null
+#ifndef __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+#define __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/x11/ecore-x-render-surface.h>
+
+namespace Dali
+{
+
+namespace ECore
+{
+
+/**
+ * Ecore X11 implementation of render surface.
+ */
+class PixmapRenderSurface : public EcoreXRenderSurface
+{
+public:
+
+ /**
+ * Uses an X11 surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ PixmapRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent = false);
+
+ /**
+ * @copydoc Dali::RenderSurface::~RenderSurface
+ */
+ virtual ~PixmapRenderSurface();
+
+public: // API
+
+ /**
+ * @copydoc Dali::ECore::EcoreXRenderSurface::GetDrawable()
+ */
+ virtual Ecore_X_Drawable GetDrawable();
+
+ /**
+ * @brief GetSurface
+ *
+ * @return pixmap
+ */
+ virtual Any GetSurface();
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::StopRender()
+ */
+ virtual void StopRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::SetThreadSynchronization
+ */
+ virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
+
+ virtual RenderSurface::Type GetSurfaceType();
+
+private:
+
+ /**
+ * Release any locks.
+ */
+ void ReleaseLock();
+
+ /**
+ * Create XPixmap
+ */
+ virtual void CreateXRenderable();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::ECore::RenderSurface::UseExistingRenderable
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId );
+
+private: // Data
+
+ struct Impl;
+ Impl* mImpl;
+};
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+#include <dali/integration-api/events/hover-event-integ.h>
+#include <dali/integration-api/events/gesture-requests.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
+#endif
+
+} // unnamed namespace
+
+AccessibilityAdaptor::AccessibilityAdaptor()
+: mReadPosition(),
+ mActionHandler( NULL ),
+ mIndicator( NULL ),
+ mIsEnabled( false ),
+ mIndicatorFocused( false )
+{
+ mAccessibilityGestureDetector = new AccessibilityGestureDetector();
+}
+
+void AccessibilityAdaptor::EnableAccessibility()
+{
+ if(mIsEnabled == false)
+ {
+ mIsEnabled = true;
+
+ if( mActionHandler )
+ {
+ mActionHandler->ChangeAccessibilityStatus();
+ }
+ }
+}
+
+void AccessibilityAdaptor::DisableAccessibility()
+{
+ if(mIsEnabled == true)
+ {
+ mIsEnabled = false;
+
+ if( mActionHandler )
+ {
+ mActionHandler->ChangeAccessibilityStatus();
+ }
+
+ // Destroy the TtsPlayer if exists.
+ if ( Adaptor::IsAvailable() )
+ {
+ Dali::Adaptor& adaptor = Dali::Adaptor::Get();
+ Adaptor& adaptorImpl = Adaptor::GetImplementation( adaptor );
+ adaptorImpl.DestroyTtsPlayer( Dali::TtsPlayer::SCREEN_READER );
+ }
+ }
+}
+
+bool AccessibilityAdaptor::IsEnabled() const
+{
+ return mIsEnabled;
+}
+
+Vector2 AccessibilityAdaptor::GetReadPosition() const
+{
+ return mReadPosition;
+}
+
+void AccessibilityAdaptor::SetActionHandler(AccessibilityActionHandler& handler)
+{
+ mActionHandler = &handler;
+}
+
+void AccessibilityAdaptor::SetGestureHandler(AccessibilityGestureHandler& handler)
+{
+ if( mAccessibilityGestureDetector )
+ {
+ mAccessibilityGestureDetector->SetGestureHandler(handler);
+ }
+}
+
+void AccessibilityAdaptor::SetIndicator(IndicatorInterface* indicator)
+{
+ mIndicator = indicator;
+}
+
+bool AccessibilityAdaptor::HandleActionNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionActivateEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionActivate();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
+{
+ bool ret = false;
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
+
+ mReadPosition.x = x;
+ mReadPosition.y = y;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionRead( allowReadAgain );
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+ }
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionUpEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionDownEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionClearFocusEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->ClearAccessibilityFocus();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp)
+{
+ bool ret = false;
+
+ // We always need to emit a scroll signal, whether it's only a hover or not,
+ // so always send the action to the action handler.
+ if( mActionHandler )
+ {
+ Dali::TouchEvent event(timeStamp);
+ event.points.push_back(point);
+ ret = mActionHandler->AccessibilityActionScroll( event );
+ }
+
+ Integration::TouchEvent touchEvent;
+ Integration::HoverEvent hoverEvent;
+ Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent( Integration::Point( point ), timeStamp, touchEvent, hoverEvent );
+ if( type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth ) // hover event is ignored
+ {
+ // Process the touch event in accessibility gesture detector
+ if( mAccessibilityGestureDetector )
+ {
+ mAccessibilityGestureDetector->SendEvent( touchEvent );
+ ret = true;
+ }
+ }
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp)
+{
+ bool ret = false;
+
+ Dali::TouchEvent touchEvent(timeStamp);
+ touchEvent.points.push_back(point);
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionTouch(touchEvent);
+ }
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionBackEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionBack();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+void AccessibilityAdaptor::HandleActionEnableEvent()
+{
+ EnableAccessibility();
+}
+
+void AccessibilityAdaptor::HandleActionDisableEvent()
+{
+ DisableAccessibility();
+}
+
+bool AccessibilityAdaptor::HandleActionScrollUpEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionScrollUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+
+bool AccessibilityAdaptor::HandleActionScrollDownEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionScrollDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionPageLeftEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionPageLeft();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionPageRightEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionPageRight();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionPageUpEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionPageUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionPageDownEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionPageDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionMoveToFirstEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionMoveToFirst();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionMoveToLastEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionMoveToLast();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadFromTopEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadFromTop();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadFromNextEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadFromNext();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionZoomEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionZoom();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadIndicatorInformation();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionReadPauseResume();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptor::HandleActionStartStopEvent()
+{
+ bool ret = false;
+
+ if( mActionHandler )
+ {
+ ret = mActionHandler->AccessibilityActionStartStop();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+AccessibilityAdaptor::~AccessibilityAdaptor()
+{
+ // Do any platform specific clean-up in OnDestroy()
+ OnDestroy();
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
+#define __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/math/vector2.h>
+#include <dali/public-api/events/touch-point.h>
+#include <dali/integration-api/events/touch-event-combiner.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/accessibility-adaptor.h>
+#include <dali/devel-api/adaptor-framework/accessibility-action-handler.h>
+#include <dali/devel-api/adaptor-framework/accessibility-gesture-handler.h>
+#include <dali/internal/window-system/common/indicator-interface.h>
+#include <dali/internal/accessibility/common/accessibility-gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * This class detects to accessibility action
+ */
+class AccessibilityAdaptor : public Dali::BaseObject
+{
+public:
+
+ /**
+ * Constructor.
+ */
+ AccessibilityAdaptor();
+
+ /**
+ * @brief Get an instance of the AccessibilityAdaptor.
+ *
+ * @note This singleton-style getter can be reimplemented for different platforms.
+ * @return The instance of the AccessibilityAdaptor.
+ */
+ static Dali::AccessibilityAdaptor Get();
+
+ /**
+ * Turn on accessibility action
+ * This method should be called by vconf callback
+ */
+ void EnableAccessibility();
+
+ /**
+ * Turn off accessibility action
+ * This method should be called by vconf callback
+ */
+ void DisableAccessibility();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::IsEnabled()
+ */
+ bool IsEnabled() const;
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::GetReadPosition() const
+ */
+ Vector2 GetReadPosition() const;
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::SetActionHandler()
+ */
+ void SetActionHandler(AccessibilityActionHandler& handler);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::SetGestureHandler()
+ */
+ void SetGestureHandler(AccessibilityGestureHandler& handler);
+
+ /**
+ * @brief Set the Indicator
+ * @param[in] Indiciator interface
+ */
+ void SetIndicator( IndicatorInterface* indicator );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionNextEvent()
+ */
+ virtual bool HandleActionNextEvent( bool allowEndFeedback = true);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPreviousEvent()
+ */
+ virtual bool HandleActionPreviousEvent( bool allowEndFeedback = true);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionActivateEvent()
+ */
+ virtual bool HandleActionActivateEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadEvent()
+ */
+ virtual bool HandleActionReadEvent( unsigned int x, unsigned int y, bool allowReadAgain );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadNextEvent()
+ */
+ virtual bool HandleActionReadNextEvent( bool allowEndFeedback = true);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPreviousEvent()
+ */
+ virtual bool HandleActionReadPreviousEvent( bool allowEndFeedback = true);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionUpEvent()
+ */
+ virtual bool HandleActionUpEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionDownEvent()
+ */
+ virtual bool HandleActionDownEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionClearFocusEvent()
+ */
+ bool HandleActionClearFocusEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollEvent()
+ */
+ bool HandleActionScrollEvent(const TouchPoint& point, unsigned long timeStamp);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionTouchEvent()
+ */
+ bool HandleActionTouchEvent(const TouchPoint& point, unsigned long timeStamp);
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionBackEvent()
+ */
+ bool HandleActionBackEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionEnableEvent()
+ */
+ void HandleActionEnableEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionDisableEvent()
+ */
+ void HandleActionDisableEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollUpEvent()
+ */
+ bool HandleActionScrollUpEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionScrollDownEvent()
+ */
+ bool HandleActionScrollDownEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPageLeftEvent()
+ */
+ bool HandleActionPageLeftEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPageRightEvent()
+ */
+ bool HandleActionPageRightEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPageUpEvent()
+ */
+ bool HandleActionPageUpEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPageDownEvent()
+ */
+ bool HandleActionPageDownEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionMoveToFirstEvent()
+ */
+ bool HandleActionMoveToFirstEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionMoveToLastEvent()
+ */
+ bool HandleActionMoveToLastEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadFromTopEvent()
+ */
+ bool HandleActionReadFromTopEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadFromNextEvent()
+ */
+ bool HandleActionReadFromNextEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionZoomEvent()
+ */
+ bool HandleActionZoomEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadIndicatorInformationEvent()
+ */
+ bool HandleActionReadIndicatorInformationEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPauseResumeEvent()
+ */
+ bool HandleActionReadPauseResumeEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionStartStopEvent()
+ */
+ bool HandleActionStartStopEvent();
+
+protected:
+
+ /**
+ * Destructor.
+ */
+ virtual ~AccessibilityAdaptor();
+
+private:
+
+ /**
+ * @brief Called when the singleton is destroyed.
+ *
+ * @note This can be reimplemented for different platforms.
+ * @return The instance of the AccessibilityAdaptor.
+ */
+ static void OnDestroy();
+
+ // Undefined
+ AccessibilityAdaptor( const AccessibilityAdaptor& );
+ AccessibilityAdaptor& operator=( AccessibilityAdaptor& );
+
+protected:
+
+ Dali::Integration::TouchEventCombiner mCombiner; ///< Combines multi-touch events.
+
+ Vector2 mReadPosition; ///< ActionRead position
+
+ AccessibilityActionHandler* mActionHandler; ///< The pointer of accessibility action handler
+
+ AccessibilityGestureDetectorPtr mAccessibilityGestureDetector; ///< The accessibility gesture detector
+
+ IndicatorInterface* mIndicator; ///< The indicator
+
+ bool mIsEnabled : 1; ///< enable/disable the accessibility action
+ bool mIndicatorFocused : 1; ///< Whether the Indicator is focused
+
+public:
+
+ // Helpers for public-api forwarding methods
+
+ inline static Internal::Adaptor::AccessibilityAdaptor& GetImplementation(Dali::AccessibilityAdaptor& adaptor)
+ {
+ DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptor handle is empty" );
+
+ BaseObject& handle = adaptor.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::AccessibilityAdaptor&>(handle);
+ }
+
+ inline static const Internal::Adaptor::AccessibilityAdaptor& GetImplementation(const Dali::AccessibilityAdaptor& adaptor)
+ {
+ DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptor handle is empty" );
+
+ const BaseObject& handle = adaptor.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::AccessibilityAdaptor&>(handle);
+ }
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/common/accessibility-gesture-detector.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/events/gesture-requests.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+AccessibilityGestureDetector::AccessibilityGestureDetector()
+: PanGestureDetectorBase(Vector2::ZERO, Integration::PanGestureRequest(), NULL),
+ mGestureHandler(NULL),
+ mPanning(false)
+{
+}
+
+AccessibilityGestureDetector::~AccessibilityGestureDetector()
+{
+}
+
+void AccessibilityGestureDetector::SetGestureHandler(AccessibilityGestureHandler& handler)
+{
+ mGestureHandler = &handler;
+}
+
+void AccessibilityGestureDetector::EmitPan(const Integration::PanGestureEvent gesture)
+{
+ if( mGestureHandler )
+ {
+ if(gesture.state == Gesture::Started)
+ {
+ mPanning = true;
+ }
+
+ if( mPanning )
+ {
+ mGestureHandler->HandlePanGesture(gesture);
+
+ if( (gesture.state == Gesture::Finished) ||
+ (gesture.state == Gesture::Cancelled) )
+ {
+ mPanning = false;
+ }
+ }
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
+#define __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/pan-gesture-detector-base.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/devel-api/adaptor-framework/accessibility-gesture-handler.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+class Core;
+struct TouchEvent;
+struct PanGestureRequest;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Detects an accessibility pan gesture and sends it to the gesture handler.
+ */
+class AccessibilityGestureDetector : public PanGestureDetectorBase
+{
+public:
+
+ /**
+ * Constructor
+ */
+ AccessibilityGestureDetector();
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~AccessibilityGestureDetector();
+
+ /**
+ * Set the handler to handle accessibility gestures.
+ * @param[in] handler The Accessibility gesture handler.
+ * @note Handlers should remove themselves when they are destroyed.
+ */
+ void SetGestureHandler(AccessibilityGestureHandler& handler);
+
+private:
+
+ /**
+ * Emits the pan gesture event to the gesture handler.
+ * @param[in] gesture The pan gesture event.
+ */
+ virtual void EmitPan(const Integration::PanGestureEvent gesture);
+
+private:
+
+ AccessibilityGestureHandler* mGestureHandler; ///< The pointer of accessibility gesture handler
+ bool mPanning; ///< Keep track of panning state, when panning is occuring, this is true.
+};
+
+typedef IntrusivePtr<AccessibilityGestureDetector> AccessibilityGestureDetectorPtr;
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ACCESSIBILITY_GESTURE_DETECTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/accessibility/common/tts-player-factory.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class TtsPlayer;
+namespace TtsPlayerFactory
+{
+/**
+ * Factory function that ought to be overriden by platform implementation.
+ * @return dummy implementation of Tts Player
+ */
+__attribute__((weak))
+std::unique_ptr<TtsPlayer> New(Dali::TtsPlayer::Mode mode)
+{
+ return std::unique_ptr<TtsPlayer>(new Internal::Adaptor::TtsPlayer());
+}
+}
+
+}
+
+}
+
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_FACTORY_H
+#define DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_FACTORY_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+#include <memory>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class TtsPlayer;
+namespace TtsPlayerFactory
+{
+
+/**
+ * Factory function that ought to be overriden by platform implementation.
+ * @return
+ */
+__attribute__((weak)) std::unique_ptr<TtsPlayer> New(Dali::TtsPlayer::Mode mode);
+
+} // namespace TtsPlayerFactory
+
+} // namespaceAdaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_FACTORY_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+#include <dali/internal/accessibility/common/tts-player-factory.h>
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::TtsPlayer TtsPlayer::New(Dali::TtsPlayer::Mode mode)
+{
+ return Dali::TtsPlayer(TtsPlayerFactory::New(mode).release());
+}
+
+void TtsPlayer::Play(const std::string &text)
+{
+
+}
+
+void TtsPlayer::Stop()
+{
+
+}
+
+void TtsPlayer::Pause()
+{
+
+}
+
+void TtsPlayer::Resume()
+{
+
+}
+
+Dali::TtsPlayer::State TtsPlayer::GetState()
+{
+ return Dali::TtsPlayer::State();
+}
+
+Dali::TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal()
+{
+ static Dali::TtsPlayer::StateChangedSignalType signal;
+ return signal;
+}
+
+}
+}
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_IMPL_H
+#define DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_IMPL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/tts-player.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Text-to-speech player
+ */
+class TtsPlayer : public Dali::BaseObject
+{
+
+public:
+
+ /**
+ * Create a TtsPlayer with the given mode.
+ * This should only be called once by the Adaptor class for each given mode.
+ * @param mode the mode of tts-player
+ * @return A newly created TtsPlayer.
+ */
+ static Dali::TtsPlayer New(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * @copydoc TtsPlayer::Play()
+ */
+ virtual void Play(const std::string& text);
+
+ /**
+ * @copydoc TtsPlayer::Stop()
+ */
+ virtual void Stop();
+
+ /**
+ * @copydoc TtsPlayer::Pause()
+ */
+ virtual void Pause();
+
+ /**
+ * @copydoc TtsPlayer::Resume()
+ */
+ virtual void Resume();
+
+ /**
+ * @copydoc TtsPlayer::GetState()
+ */
+ virtual Dali::TtsPlayer::State GetState();
+
+ /**
+ * @copydoc TtsPlayer::StateChangedSignal()
+ */
+ virtual Dali::TtsPlayer::StateChangedSignalType& StateChangedSignal();
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::TtsPlayer& GetImplementation(Dali::TtsPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
+
+ BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::TtsPlayer&>(handle);
+}
+
+inline const Internal::Adaptor::TtsPlayer& GetImplementation(const Dali::TtsPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" );
+
+ const BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::TtsPlayer&>(handle);
+}
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_IMPL_H
--- /dev/null
+
+
+# module: accessibility, backend: common
+adaptor_accessibility_common_src_files=\
+ ${adaptor_accessibility_dir}/common/tts-player-factory.cpp \
+ ${adaptor_accessibility_dir}/common/tts-player-impl.cpp \
+ ${adaptor_accessibility_dir}/common/accessibility-adaptor-impl.cpp \
+ ${adaptor_accessibility_dir}/common/accessibility-gesture-detector.cpp
+
+# module: accessibility, backend: tizen-common
+adaptor_accessibility_tizen_common_src_files=\
+ ${adaptor_accessibility_dir}/tizen-common/accessibility-adaptor-impl-tizen.cpp \
+ ${adaptor_accessibility_dir}/tizen-common/tts-player-factory-tizen.cpp \
+ ${adaptor_accessibility_dir}/tizen-common/tts-player-impl-tizen.cpp
+
+# module: accessibility, backend: tizen-ivi
+adaptor_accessibility_tizen_ivi_src_files=\
+ ${adaptor_accessibility_dir}/tizen-ivi/accessibility-adaptor-impl-ivi.cpp
+
+# module: accessibility, backend: tizen-mobile
+adaptor_accessibility_tizen_mobile_src_files=\
+ ${adaptor_accessibility_dir}/tizen-mobile/accessibility-adaptor-impl-mobile.cpp
+
+# module: accessibility, backend: tizen-tv
+adaptor_accessibility_tizen_tv_src_files=\
+ ${adaptor_accessibility_dir}/tizen-tv/accessibility-adaptor-impl-tv.cpp
+
+# module: accessibility, backend: tizen-wearable
+adaptor_accessibility_tizen_wearable_src_files=\
+ ${adaptor_accessibility_dir}/tizen-wearable/accessibility-adaptor-impl-wearable.cpp
+
+# module: accessibility, backend: ubuntu
+adaptor_accessibility_ubuntu_src_files=\
+ ${adaptor_accessibility_dir}/ubuntu/accessibility-adaptor-impl-ubuntu.cpp \
+ ${adaptor_accessibility_dir}/ubuntu/tts-player-factory-ubuntu.cpp \
+ ${adaptor_accessibility_dir}/ubuntu/tts-player-impl-ubuntu.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <vconf.h>
+
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
+
+// Disabled Accessibility temporarily in Tizen platform
+bool GetEnabledVConf()
+{
+ int isEnabled = 0;
+ //vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
+
+ if( isEnabled == 0 )
+ {
+ //vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
+ }
+
+ return static_cast<bool>(isEnabled);
+}
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR" );
+#endif
+
+void AccessibilityOnOffNotification(keynode_t* node, void* data)
+{
+ AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
+
+ bool isEnabled = GetEnabledVConf();
+
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ if( isEnabled )
+ {
+ adaptor->EnableAccessibility();
+ }
+ else
+ {
+ adaptor->DisableAccessibility();
+ }
+}
+
+} // unnamed namespace
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptor() );
+ AccessibilityAdaptor& adaptorImpl = AccessibilityAdaptor::GetImplementation( adaptor );
+
+ bool isEnabled = GetEnabledVConf();
+
+ if( isEnabled )
+ {
+ adaptorImpl.EnableAccessibility();
+ }
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/accessibility/common/tts-player-factory.h>
+#include <dali/internal/accessibility/tizen-common/tts-player-impl-tizen.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class TtsPlayer;
+namespace TtsPlayerFactory
+{
+
+std::unique_ptr<TtsPlayer> New(Dali::TtsPlayer::Mode mode)
+{
+ return TtsPlayerTizen::New(mode);
+}
+
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/tizen-common/tts-player-impl-tizen.h>
+
+// EXTERNAL INCLUDES
+#include <tts.h>
+
+#include <dali/public-api/object/type-registry.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+/**
+ * Helper function to convert Tizen-specific TTS state to external state.
+ * @param state The Tizen TTS state.
+ * @return The external TTS state.
+ */
+Dali::TtsPlayer::State InternalToExternalState( tts_state_e state )
+{
+ switch( state )
+ {
+ case TTS_STATE_CREATED:
+ {
+ return Dali::TtsPlayer::UNAVAILABLE;
+ }
+ case TTS_STATE_READY:
+ {
+ return Dali::TtsPlayer::READY;
+ }
+ case TTS_STATE_PLAYING:
+ {
+ return Dali::TtsPlayer::PLAYING;
+ }
+ case TTS_STATE_PAUSED:
+ {
+ return Dali::TtsPlayer::PAUSED;
+ }
+ }
+
+ return Dali::TtsPlayer::UNAVAILABLE;
+}
+
+} // unnamed namespace
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* TtsPlayerTizen::gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TTS_PLAYER");
+#endif
+
+std::unique_ptr<TtsPlayerTizen> TtsPlayerTizen::New(Dali::TtsPlayer::Mode mode)
+{
+ return std::unique_ptr<TtsPlayerTizen>(new TtsPlayerTizen(mode));
+}
+
+TtsPlayerTizen::TtsPlayerTizen(Dali::TtsPlayer::Mode mode)
+: mInitialized(false),
+ mUnplayedString(""),
+ mUtteranceId(0),
+ mTtsMode(mode)
+{
+ Initialize();
+}
+
+TtsPlayerTizen::~TtsPlayerTizen()
+{
+ // If it is playing, stop it
+ Stop();
+
+ // Unset the callback funtion for TTS state change
+ int retVal = tts_unset_state_changed_cb(mTtsHandle);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+
+ // Destroy the TTS handle and disconnects the daemon
+ retVal = tts_destroy(mTtsHandle);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+}
+
+void TtsPlayerTizen::Initialize()
+{
+ // Create the TTS handle
+ int retVal = tts_create(&mTtsHandle);
+
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else
+ {
+ // Set the callback funtion for TTS state change
+ retVal = tts_set_state_changed_cb(mTtsHandle, &StateChangedCallback, this);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+
+ // Check tts mode
+ tts_mode_e ttsMode = TTS_MODE_DEFAULT;
+ switch (mTtsMode)
+ {
+ case Dali::TtsPlayer::DEFAULT:
+ ttsMode = TTS_MODE_DEFAULT;
+ break;
+ case Dali::TtsPlayer::NOTIFICATION:
+ ttsMode = TTS_MODE_NOTIFICATION;
+ break;
+ case Dali::TtsPlayer::SCREEN_READER:
+ ttsMode = TTS_MODE_SCREEN_READER;
+ break;
+ default:
+ break;
+ }
+
+ // Set mode
+ retVal = tts_set_mode(mTtsHandle, ttsMode);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+
+ // Connect the TTS daemon asynchronously
+ retVal = tts_prepare(mTtsHandle);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ }
+}
+
+void TtsPlayerTizen::Play(const std::string& text)
+{
+ if(mInitialized)
+ {
+ Stop();
+
+ // Add text to the queue, and use normal speed, default language and default voice set by the user
+ int retVal = tts_add_text(mTtsHandle, text.c_str(), NULL, TTS_VOICE_TYPE_AUTO, TTS_SPEED_AUTO, &mUtteranceId);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else
+ {
+ // Start synthesizing voice from text in the queue and play synthesized audio data
+ retVal = tts_play(mTtsHandle);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ }
+ }
+ else
+ {
+ mUnplayedString = text;
+ }
+}
+
+void TtsPlayerTizen::Stop()
+{
+ if(mInitialized)
+ {
+ // Check the current TTS state
+ tts_state_e state;
+ int retVal = tts_get_state(mTtsHandle, &state);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else if(state == TTS_STATE_PLAYING || state == TTS_STATE_PAUSED)
+ {
+ // If it is playing or paused, stop playing and clear the queue
+ retVal = tts_stop(mTtsHandle);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ }
+ }
+}
+
+void TtsPlayerTizen::Pause()
+{
+ if(mInitialized)
+ {
+ // Check the current TTS state
+ tts_state_e state;
+ int retVal = tts_get_state(mTtsHandle, &state);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else if(state == TTS_STATE_PLAYING)
+ {
+ // If the player is playing, pause it.
+ retVal = tts_pause(mTtsHandle);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ }
+ }
+}
+
+void TtsPlayerTizen::Resume()
+{
+ if(mInitialized)
+ {
+ // Check the current TTS state
+ tts_state_e state;
+ int retVal = tts_get_state(mTtsHandle, &state);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else if(state == TTS_STATE_PAUSED)
+ {
+ // If the player is paused, resume it.
+ retVal = tts_play(mTtsHandle);
+ if( retVal != TTS_ERROR_NONE )
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ }
+ }
+}
+
+Dali::TtsPlayer::State TtsPlayerTizen::GetState()
+{
+ Dali::TtsPlayer::State ttsState = Dali::TtsPlayer::UNAVAILABLE;
+
+ if(mInitialized)
+ {
+ // Check the current TTS state
+ tts_state_e state;
+ int retVal = tts_get_state(mTtsHandle, &state);
+ if(retVal != TTS_ERROR_NONE)
+ {
+ LogErrorCode(static_cast<tts_error_e>(retVal));
+ }
+ else
+ {
+ ttsState = InternalToExternalState( state );
+ }
+ }
+
+ return ttsState;
+}
+
+Dali::TtsPlayer::StateChangedSignalType& TtsPlayerTizen::StateChangedSignal()
+{
+ return mStateChangedSignal;
+}
+
+void TtsPlayerTizen::EmitStateChangedSignal( tts_state_e previous, tts_state_e current )
+{
+ // Convert the previous and current states to external states and emit them as a signal.
+ if( !mStateChangedSignal.Empty() )
+ {
+ mStateChangedSignal.Emit( InternalToExternalState( previous ), InternalToExternalState( current ) );
+ }
+}
+
+void TtsPlayerTizen::StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData)
+{
+ // Get the implementation (this is a static function).
+ TtsPlayerTizen* obj = static_cast<TtsPlayerTizen*>(userData);
+
+ // Emit the signal.
+ obj->EmitStateChangedSignal( previous, current );
+
+ if(!obj->mInitialized && current == TTS_STATE_READY)
+ {
+ obj->mInitialized = true;
+
+ // if there is queued text before initialization, play it
+ if(obj->mUnplayedString != "")
+ {
+ obj->Play(obj->mUnplayedString);
+ obj->mUnplayedString = "";
+ }
+ }
+}
+
+void TtsPlayerTizen::LogErrorCode(tts_error_e reason)
+{
+ std::string error_string;
+
+ switch (reason)
+ {
+ case TTS_ERROR_NONE:
+ {
+ break;
+ }
+ case TTS_ERROR_OUT_OF_MEMORY:
+ {
+ error_string = "TTS: Out of Memory\n";
+ break;
+ }
+ case TTS_ERROR_IO_ERROR:
+ {
+ error_string = "TTS: I/O error\n";
+ break;
+ }
+ case TTS_ERROR_INVALID_PARAMETER:
+ {
+ error_string = "TTS: Invalid parameter\n";
+ break;
+ }
+ case TTS_ERROR_OUT_OF_NETWORK:
+ {
+ error_string = "TTS: Out of network\n";
+ break;
+ }
+ case TTS_ERROR_INVALID_STATE:
+ {
+ error_string = "TTS: Invalid state\n";
+ break;
+ }
+ case TTS_ERROR_INVALID_VOICE:
+ {
+ error_string = "TTS: Invalid voice\n";
+ break;
+ }
+ case TTS_ERROR_ENGINE_NOT_FOUND:
+ {
+ error_string = "TTS: No available engine\n";
+ break;
+ }
+ case TTS_ERROR_TIMED_OUT:
+ {
+ error_string = "TTS: No answer from the daemon\n";
+ break;
+ }
+ case TTS_ERROR_OPERATION_FAILED:
+ {
+ error_string = "TTS: Operation failed\n";
+ break;
+ }
+ default:
+ {
+ error_string = "Invalid TTS error code\n";
+ break;
+ }
+ }
+
+ if(reason != TTS_ERROR_NONE)
+ {
+ DALI_LOG_WARNING("[%s:%d] tts error : %s\n", __FUNCTION__, __LINE__, error_string.c_str());
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ACCESSIBILITY_TIZEN_TTS_PLAYER_IMPL_TIZEN_H
+#define DALI_INTERNAL_ACCESSIBILITY_TIZEN_TTS_PLAYER_IMPL_TIZEN_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <tts.h>
+#include <string>
+#include <memory>
+
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/tts-player.h>
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Text-to-speech player
+ */
+class TtsPlayerTizen : public Dali::Internal::Adaptor::TtsPlayer
+{
+
+public:
+
+ /**
+ * Create a TtsPlayer with the given mode.
+ * This should only be called once by the Adaptor class for each given mode.
+ * @param mode the mode of tts-player
+ * @return A newly created TtsPlayer.
+ */
+ static std::unique_ptr<TtsPlayerTizen> New(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * @copydoc TtsPlayer::Play()
+ */
+ void Play(const std::string& text) override;
+
+ /**
+ * @copydoc TtsPlayer::Stop()
+ */
+ void Stop() override;
+
+ /**
+ * @copydoc TtsPlayer::Pause()
+ */
+ void Pause() override;
+
+ /**
+ * @copydoc TtsPlayer::Resume()
+ */
+ void Resume() override;
+
+ /**
+ * @copydoc TtsPlayer::GetState()
+ */
+ Dali::TtsPlayer::State GetState() override;
+
+ /**
+ * @copydoc TtsPlayer::StateChangedSignal()
+ */
+ Dali::TtsPlayer::StateChangedSignalType& StateChangedSignal() override;
+
+ /**
+ * Destructor
+ */
+ ~TtsPlayerTizen() override;
+
+private:
+
+ /**
+ * Private Constructor; see also TtsPlayer::New()
+ * @param mode the mode of tts-player
+ */
+ TtsPlayerTizen(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * Initializes the player.
+ */
+ void Initialize();
+
+ /**
+ * Logs the error code.
+ * @param[in] reason The error code
+ */
+ void LogErrorCode(tts_error_e reason);
+
+ /**
+ * Used to emit the state changed signal from outside the object (EG. A static function).
+ * @param[in] previous The previous state
+ * @param[in] current The current state
+ */
+ void EmitStateChangedSignal( tts_state_e previous, tts_state_e current );
+
+ /**
+ * Called when the state of TTS is changed.
+ *
+ * @param[in] tts The handle for TTS
+ * @param[in] previous A previous state
+ * @param[in] current A current state
+ * @param[in] userData The user data passed from the callback registration function.
+ */
+ static void StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData);
+
+ // Undefined
+ TtsPlayerTizen(const TtsPlayerTizen&);
+
+ // Undefined
+ TtsPlayerTizen& operator=(TtsPlayerTizen&);
+
+private:
+
+ Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes
+ bool mInitialized; ///< Whether the TTS player is initialised successfully or not
+ std::string mUnplayedString; ///< The text that can not be played because tts engine is not yet initialized
+ tts_h mTtsHandle; ///< The handle of TTS
+ int mUtteranceId; ///< The utterance ID
+
+ Dali::TtsPlayer::Mode mTtsMode; ///< The current mode of tts engine
+
+#if defined(DEBUG_ENABLED)
+public:
+ static Debug::Filter* gLogFilter;
+#endif
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_ACCESSIBILITY_TIZEN_TTS_PLAYER_IMPL_TIZEN_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/tizen-mobile/accessibility-adaptor-impl-mobile.h>
+
+// EXTERNAL INCLUDES
+#include <vconf.h>
+
+#ifndef WAYLAND
+#include <Ecore_X.h>
+#include <Elementary.h>
+#endif
+
+#include <vconf.h>
+
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/gesture-requests.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/system/generic/system-settings.h>
+
+#ifndef WAYLAND
+#define MSG_DOMAIN_CONTROL_ACCESS static_cast< int >( ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL )
+#endif
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
+#endif
+
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
+
+bool GetEnabledVConf()
+{
+ int isEnabled = 0;
+ vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
+
+ if( isEnabled == 0 )
+ {
+ vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
+ }
+
+ return bool( isEnabled );
+}
+
+
+void AccessibilityOnOffNotification(keynode_t* node, void* data)
+{
+ AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
+
+ bool isEnabled = GetEnabledVConf();
+
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ if( isEnabled )
+ {
+ adaptor->EnableAccessibility();
+ }
+ else
+ {
+ adaptor->DisableAccessibility();
+ }
+}
+
+} // unnamed namespace
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptorMobile() );
+ AccessibilityAdaptorMobile& adaptorImpl = AccessibilityAdaptorMobile::GetImplementation( adaptor );
+
+ bool isEnabled = GetEnabledVConf();
+
+ if( isEnabled )
+ {
+ adaptorImpl.EnableAccessibility();
+ }
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
+}
+
+AccessibilityAdaptorMobile::AccessibilityAdaptorMobile()
+{
+}
+
+bool AccessibilityAdaptorMobile::HandleActionNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionActivateEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_ACTIVATE;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionActivate();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
+{
+ bool ret = false;
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
+
+ mReadPosition.x = x;
+ mReadPosition.y = y;
+
+ Dali::AccessibilityAdaptor handle( this );
+
+ bool indicatorFocused = false;
+
+ // Check whether the Indicator is focused
+ if( mIndicator && mIndicator->IsConnected() )
+ {
+ // Check the position and size of Indicator actor
+ Dali::Actor indicatorActor = mIndicator->GetActor();
+ Vector3 position = Vector3(0.0f, 0.0f, 0.0f);
+ Vector3 size = indicatorActor.GetCurrentSize();
+
+ if(mReadPosition.x >= position.x &&
+ mReadPosition.x <= position.x + size.width &&
+ mReadPosition.y >= position.y &&
+ mReadPosition.y <= position.y + size.height)
+ {
+ indicatorFocused = true;
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Indicator area!!!!\n", __FUNCTION__, __LINE__);
+ }
+ }
+
+ if( mIndicator )
+ {
+ if( !mIndicatorFocused && indicatorFocused )
+ {
+ // If Indicator is focused, the focus should be cleared in Dali focus chain.
+ if( mActionHandler )
+ {
+ mActionHandler->ClearAccessibilityFocus();
+ }
+ }
+ else if( mIndicatorFocused && !indicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UNHIGHLIGHT;
+
+ // Indicator should be unhighlighted
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send unhighlight message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+
+ mIndicatorFocused = indicatorFocused;
+
+ // Send accessibility READ action information to Indicator
+ if( mIndicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.x = mReadPosition.x;
+ actionInfo.y = mReadPosition.y;
+
+ if(allowReadAgain)
+ {
+ actionInfo.action_type = ELM_ACCESS_ACTION_READ;
+ }
+ else
+ {
+ actionInfo.action_type = static_cast<Elm_Access_Action_Type>( GetElmAccessActionOver() );
+ }
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send READ message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+ }
+
+ if( mActionHandler && !mIndicatorFocused)
+ {
+ // If Indicator is not focused, the accessibility actions should be handled by the registered
+ // accessibility action handler (e.g. focus manager)
+ ret = mActionHandler->AccessibilityActionRead(allowReadAgain);
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+ }
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionUpEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UP;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionDownEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_DOWN;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+AccessibilityAdaptorMobile::~AccessibilityAdaptorMobile()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/tizen-mobile/accessibility-adaptor-impl-mobile.h>
+
+// EXTERNAL INCLUDES
+#include <vconf.h>
+
+#ifndef WAYLAND
+#include <Ecore_X.h>
+#include <Elementary.h>
+#endif
+
+#include <vconf.h>
+
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/gesture-requests.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/system/generic/system-settings.h>
+
+#ifndef WAYLAND
+#define MSG_DOMAIN_CONTROL_ACCESS static_cast< int >( ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL )
+#endif
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
+#endif
+
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
+
+bool GetEnabledVConf()
+{
+ int isEnabled = 0;
+ vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
+
+ if( isEnabled == 0 )
+ {
+ vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
+ }
+
+ return bool( isEnabled );
+}
+
+
+void AccessibilityOnOffNotification(keynode_t* node, void* data)
+{
+ AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
+
+ bool isEnabled = GetEnabledVConf();
+
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ if( isEnabled )
+ {
+ adaptor->EnableAccessibility();
+ }
+ else
+ {
+ adaptor->DisableAccessibility();
+ }
+}
+
+} // unnamed namespace
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptorMobile() );
+ AccessibilityAdaptorMobile& adaptorImpl = AccessibilityAdaptorMobile::GetImplementation( adaptor );
+
+ bool isEnabled = GetEnabledVConf();
+
+ if( isEnabled )
+ {
+ adaptorImpl.EnableAccessibility();
+ }
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
+}
+
+AccessibilityAdaptorMobile::AccessibilityAdaptorMobile()
+{
+}
+
+bool AccessibilityAdaptorMobile::HandleActionNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionActivateEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_ACTIVATE;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionActivate();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
+{
+ bool ret = false;
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
+
+ mReadPosition.x = x;
+ mReadPosition.y = y;
+
+ Dali::AccessibilityAdaptor handle( this );
+
+ bool indicatorFocused = false;
+
+ // Check whether the Indicator is focused
+ if( mIndicator && mIndicator->IsConnected() )
+ {
+ // Check the position and size of Indicator actor
+ Dali::Actor indicatorActor = mIndicator->GetActor();
+ Vector3 position = Vector3(0.0f, 0.0f, 0.0f);
+ Vector3 size = indicatorActor.GetCurrentSize();
+
+ if(mReadPosition.x >= position.x &&
+ mReadPosition.x <= position.x + size.width &&
+ mReadPosition.y >= position.y &&
+ mReadPosition.y <= position.y + size.height)
+ {
+ indicatorFocused = true;
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Indicator area!!!!\n", __FUNCTION__, __LINE__);
+ }
+ }
+
+ if( mIndicator )
+ {
+ if( !mIndicatorFocused && indicatorFocused )
+ {
+ // If Indicator is focused, the focus should be cleared in Dali focus chain.
+ if( mActionHandler )
+ {
+ mActionHandler->ClearAccessibilityFocus();
+ }
+ }
+ else if( mIndicatorFocused && !indicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UNHIGHLIGHT;
+
+ // Indicator should be unhighlighted
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send unhighlight message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+
+ mIndicatorFocused = indicatorFocused;
+
+ // Send accessibility READ action information to Indicator
+ if( mIndicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.x = mReadPosition.x;
+ actionInfo.y = mReadPosition.y;
+
+ if(allowReadAgain)
+ {
+ actionInfo.action_type = ELM_ACCESS_ACTION_READ;
+ }
+ else
+ {
+ actionInfo.action_type = static_cast<Elm_Access_Action_Type>( GetElmAccessActionOver() );
+ }
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send READ message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+ }
+
+ if( mActionHandler && !mIndicatorFocused)
+ {
+ // If Indicator is not focused, the accessibility actions should be handled by the registered
+ // accessibility action handler (e.g. focus manager)
+ ret = mActionHandler->AccessibilityActionRead(allowReadAgain);
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+ }
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionUpEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UP;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionDownEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_DOWN;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+AccessibilityAdaptorMobile::~AccessibilityAdaptorMobile()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
+#define __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/accessibility-adaptor.h>
+#include <dali/devel-api/adaptor-framework/accessibility-action-handler.h>
+#include <dali/devel-api/adaptor-framework/accessibility-gesture-handler.h>
+#include <dali/internal/window-system/common/indicator-interface.h>
+#include <dali/internal/accessibility/common/accessibility-gesture-detector.h>
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * This mobile version is different since it forwards events to the indicator.
+ */
+class AccessibilityAdaptorMobile : public AccessibilityAdaptor
+{
+public:
+
+ /**
+ * Constructor.
+ */
+ AccessibilityAdaptorMobile();
+
+ // From AccessibilityAdaptor base class
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionNextEvent()
+ */
+ virtual bool HandleActionNextEvent( bool allowEndFeedback );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionPreviousEvent()
+ */
+ virtual bool HandleActionPreviousEvent( bool allowEndFeedback );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionActivateEvent()
+ */
+ virtual bool HandleActionActivateEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadEvent()
+ */
+ virtual bool HandleActionReadEvent( unsigned int x, unsigned int y, bool allowReadAgain );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadNextEvent()
+ */
+ virtual bool HandleActionReadNextEvent( bool allowEndFeedback );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionReadPreviousEvent()
+ */
+ virtual bool HandleActionReadPreviousEvent( bool allowEndFeedback );
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionUpEvent()
+ */
+ virtual bool HandleActionUpEvent();
+
+ /**
+ * @copydoc Dali::AccessibilityAdaptor::HandleActionDownEvent()
+ */
+ virtual bool HandleActionDownEvent();
+
+private:
+
+ /**
+ * Destructor.
+ */
+ virtual ~AccessibilityAdaptorMobile();
+
+ // Undefined
+ AccessibilityAdaptorMobile( const AccessibilityAdaptorMobile& );
+ AccessibilityAdaptorMobile& operator=( AccessibilityAdaptorMobile& );
+
+public:
+
+ // Helpers for public-api forwarding methods
+
+ inline static Internal::Adaptor::AccessibilityAdaptorMobile& GetImplementation(Dali::AccessibilityAdaptor& adaptor)
+ {
+ DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptorMobile handle is empty" );
+
+ BaseObject& handle = adaptor.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::AccessibilityAdaptorMobile&>(handle);
+ }
+
+ inline static const Internal::Adaptor::AccessibilityAdaptorMobile& GetImplementation(const Dali::AccessibilityAdaptor& adaptor)
+ {
+ DALI_ASSERT_ALWAYS( adaptor && "AccessibilityAdaptorMobile handle is empty" );
+
+ const BaseObject& handle = adaptor.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::AccessibilityAdaptorMobile&>(handle);
+ }
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ACCESSIBILITY_ADAPTOR_MOBILE_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <vconf.h>
+
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
+
+// Disabled Accessibility temporarily in Tizen platform
+bool GetEnabledVConf()
+{
+ int isEnabled = 0;
+ //vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
+
+ if( isEnabled == 0 )
+ {
+ //vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
+ }
+
+ return static_cast<bool>(isEnabled);
+}
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR" );
+#endif
+
+void AccessibilityOnOffNotification(keynode_t* node, void* data)
+{
+ AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
+
+ bool isEnabled = GetEnabledVConf();
+
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ if( isEnabled )
+ {
+ adaptor->EnableAccessibility();
+ }
+ else
+ {
+ adaptor->DisableAccessibility();
+ }
+}
+
+} // unnamed namespace
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptor() );
+ AccessibilityAdaptor& adaptorImpl = AccessibilityAdaptor::GetImplementation( adaptor );
+
+ bool isEnabled = GetEnabledVConf();
+
+ if( isEnabled )
+ {
+ adaptorImpl.EnableAccessibility();
+ }
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/tizen-mobile/accessibility-adaptor-impl-mobile.h>
+
+// EXTERNAL INCLUDES
+#include <vconf.h>
+
+#ifndef WAYLAND
+#include <Ecore_X.h>
+#include <Elementary.h>
+#endif
+
+#include <vconf.h>
+
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/gesture-requests.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/system/generic/system-settings.h>
+
+#ifndef WAYLAND
+#define MSG_DOMAIN_CONTROL_ACCESS static_cast< int >( ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL )
+#endif
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gAccessibilityAdaptorLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ACCESSIBILITY_ADAPTOR");
+#endif
+
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS = "db/setting/accessibility/atspi";
+
+bool GetEnabledVConf()
+{
+ int isEnabled = 0;
+ vconf_get_bool( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, &isEnabled );
+
+ if( isEnabled == 0 )
+ {
+ vconf_get_bool( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &isEnabled );
+ }
+
+ return bool( isEnabled );
+}
+
+
+void AccessibilityOnOffNotification(keynode_t* node, void* data)
+{
+ AccessibilityAdaptor* adaptor = static_cast<AccessibilityAdaptor*>( data );
+
+ bool isEnabled = GetEnabledVConf();
+
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ if( isEnabled )
+ {
+ adaptor->EnableAccessibility();
+ }
+ else
+ {
+ adaptor->DisableAccessibility();
+ }
+}
+
+} // unnamed namespace
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptorMobile() );
+ AccessibilityAdaptorMobile& adaptorImpl = AccessibilityAdaptorMobile::GetImplementation( adaptor );
+
+ bool isEnabled = GetEnabledVConf();
+
+ if( isEnabled )
+ {
+ adaptorImpl.EnableAccessibility();
+ }
+ DALI_LOG_INFO( gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, isEnabled ? "ENABLED" : "DISABLED" );
+
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification, &adaptorImpl );
+
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, AccessibilityOnOffNotification );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_DBUS_TTS, AccessibilityOnOffNotification );
+}
+
+AccessibilityAdaptorMobile::AccessibilityAdaptorMobile()
+{
+}
+
+bool AccessibilityAdaptorMobile::HandleActionNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionActivateEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_ACTIVATE;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionActivate();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadEvent(unsigned int x, unsigned int y, bool allowReadAgain)
+{
+ bool ret = false;
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %d , %d\n", __FUNCTION__, __LINE__, x, y);
+
+ mReadPosition.x = x;
+ mReadPosition.y = y;
+
+ Dali::AccessibilityAdaptor handle( this );
+
+ bool indicatorFocused = false;
+
+ // Check whether the Indicator is focused
+ if( mIndicator && mIndicator->IsConnected() )
+ {
+ // Check the position and size of Indicator actor
+ Dali::Actor indicatorActor = mIndicator->GetActor();
+ Vector3 position = Vector3(0.0f, 0.0f, 0.0f);
+ Vector3 size = indicatorActor.GetCurrentSize();
+
+ if(mReadPosition.x >= position.x &&
+ mReadPosition.x <= position.x + size.width &&
+ mReadPosition.y >= position.y &&
+ mReadPosition.y <= position.y + size.height)
+ {
+ indicatorFocused = true;
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Indicator area!!!!\n", __FUNCTION__, __LINE__);
+ }
+ }
+
+ if( mIndicator )
+ {
+ if( !mIndicatorFocused && indicatorFocused )
+ {
+ // If Indicator is focused, the focus should be cleared in Dali focus chain.
+ if( mActionHandler )
+ {
+ mActionHandler->ClearAccessibilityFocus();
+ }
+ }
+ else if( mIndicatorFocused && !indicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UNHIGHLIGHT;
+
+ // Indicator should be unhighlighted
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send unhighlight message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+
+ mIndicatorFocused = indicatorFocused;
+
+ // Send accessibility READ action information to Indicator
+ if( mIndicatorFocused )
+ {
+#ifndef WAYLAND
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.x = mReadPosition.x;
+ actionInfo.y = mReadPosition.y;
+
+ if(allowReadAgain)
+ {
+ actionInfo.action_type = ELM_ACCESS_ACTION_READ;
+ }
+ else
+ {
+ actionInfo.action_type = static_cast<Elm_Access_Action_Type>( GetElmAccessActionOver() );
+ }
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] Send READ message to indicator!!!!\n", __FUNCTION__, __LINE__);
+#endif
+ }
+ }
+
+ if( mActionHandler && !mIndicatorFocused)
+ {
+ // If Indicator is not focused, the accessibility actions should be handled by the registered
+ // accessibility action handler (e.g. focus manager)
+ ret = mActionHandler->AccessibilityActionRead(allowReadAgain);
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+ }
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadNextEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_NEXT;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadNext(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionReadPreviousEvent(bool allowEndFeedback)
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_HIGHLIGHT_PREV;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionReadPrevious(allowEndFeedback);
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionUpEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_UP;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionUp();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+bool AccessibilityAdaptorMobile::HandleActionDownEvent()
+{
+ bool ret = false;
+
+#ifndef WAYLAND
+ if( mIndicator && mIndicatorFocused )
+ {
+ Elm_Access_Action_Info actionInfo;
+ actionInfo.action_type = ELM_ACCESS_ACTION_DOWN;
+
+ ret = mIndicator->SendMessage(MSG_DOMAIN_CONTROL_ACCESS, actionInfo.action_type, &actionInfo, sizeof(actionInfo));
+ }
+ else if( mActionHandler )
+#else
+ if( mActionHandler )
+#endif
+ {
+ ret = mActionHandler->AccessibilityActionDown();
+ }
+
+ DALI_LOG_INFO(gAccessibilityAdaptorLogFilter, Debug::General, "[%s:%d] %s\n", __FUNCTION__, __LINE__, ret?"TRUE":"FALSE");
+
+ return ret;
+}
+
+AccessibilityAdaptorMobile::~AccessibilityAdaptorMobile()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::AccessibilityAdaptor AccessibilityAdaptor::Get()
+{
+ Dali::AccessibilityAdaptor adaptor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::AccessibilityAdaptor ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ adaptor = Dali::AccessibilityAdaptor( dynamic_cast< AccessibilityAdaptor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ adaptor = Dali::AccessibilityAdaptor( new AccessibilityAdaptor() );
+ service.Register( typeid( adaptor ), adaptor );
+ }
+ }
+
+ return adaptor;
+}
+
+void AccessibilityAdaptor::OnDestroy()
+{
+ // Nothing to do here
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/accessibility/common/tts-player-factory.h>
+#include <dali/internal/accessibility/ubuntu/tts-player-impl-ubuntu.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class TtsPlayer;
+namespace TtsPlayerFactory
+{
+
+std::unique_ptr<TtsPlayer> New(Dali::TtsPlayer::Mode mode)
+{
+ return TtsPlayerUbuntu::New(mode);
+}
+
+} // namespace TtsPlayerFactory
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/accessibility/ubuntu/tts-player-impl-ubuntu.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+
+#include <memory>
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* TtsPlayerUbuntu::gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TTS_PLAYER");
+#endif
+
+std::unique_ptr<TtsPlayerUbuntu> TtsPlayerUbuntu::New(Dali::TtsPlayer::Mode mode)
+{
+ return std::unique_ptr<TtsPlayerUbuntu>(new TtsPlayerUbuntu(mode));
+}
+
+TtsPlayerUbuntu::TtsPlayerUbuntu(Dali::TtsPlayer::Mode mode)
+: mStateChangedSignal()
+{
+ DALI_LOG_ERROR("TTS is not implemented in UBUNTU profile.\n");
+}
+
+TtsPlayerUbuntu::~TtsPlayerUbuntu()
+{
+}
+
+void TtsPlayerUbuntu::Play(const std::string& text)
+{
+}
+
+void TtsPlayerUbuntu::Stop()
+{
+}
+
+void TtsPlayerUbuntu::Pause()
+{
+}
+
+void TtsPlayerUbuntu::Resume()
+{
+}
+
+Dali::TtsPlayer::State TtsPlayerUbuntu::GetState()
+{
+ return Dali::TtsPlayer::UNAVAILABLE;
+}
+
+Dali::TtsPlayer::StateChangedSignalType& TtsPlayerUbuntu::StateChangedSignal()
+{
+ return mStateChangedSignal;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ACCESSIBILITY_UBUNTU_TTS_PLAYER_IMPL_UBUNTU_H
+#define DALI_INTERNAL_ACCESSIBILITY_UBUNTU_TTS_PLAYER_IMPL_UBUNTU_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+
+#include <string>
+#include <memory>
+
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/base-object.h>
+
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+
+// INTERNAL INCLUDES
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Text-to-speech player
+ */
+class TtsPlayerUbuntu : public Dali::Internal::Adaptor::TtsPlayer
+{
+
+public:
+
+ /**
+ * Create a TtsPlayer with the given mode.
+ * This should only be called once by the Adaptor class for each given mode.
+ * @param mode the mode of tts-player
+ * @return A newly created TtsPlayer.
+ */
+ static std::unique_ptr<TtsPlayerUbuntu> New(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * @copydoc TtsPlayer::Play()
+ */
+ void Play(const std::string& text) override;
+
+ /**
+ * @copydoc TtsPlayer::Stop()
+ */
+ void Stop() override;
+
+ /**
+ * @copydoc TtsPlayer::Pause()
+ */
+ void Pause() override;
+
+ /**
+ * @copydoc TtsPlayer::Resume()
+ */
+ void Resume() override;
+
+ /**
+ * @copydoc TtsPlayer::GetState()
+ */
+ Dali::TtsPlayer::State GetState() override;
+
+ /**
+ * @copydoc TtsPlayer::StateChangedSignal()
+ */
+ Dali::TtsPlayer::StateChangedSignalType& StateChangedSignal() override;
+
+ /**
+ * Private Constructor; see also TtsPlayer::New()
+ * @param mode the mode of tts-player
+ */
+ TtsPlayerUbuntu(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * Destructor
+ */
+ virtual ~TtsPlayerUbuntu();
+
+private:
+
+ Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes (non-functional, for interface compatibility).
+
+#if defined(DEBUG_ENABLED)
+public:
+ static Debug::Filter* gLogFilter;
+#endif
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_ACCESSIBILITY_UBUNTU_TTS_PLAYER_IMPL_UBUNTU_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/common/stage.h>
+#include <dali/public-api/actors/layer.h>
+#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/core.h>
+#include <dali/integration-api/context-notifier.h>
+#include <dali/integration-api/profiling.h>
+#include <dali/integration-api/input-options.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/thread-controller.h>
+#include <dali/internal/system/common/performance-interface-factory.h>
+#include <dali/internal/adaptor/common/lifecycle-observer.h>
+
+#include <dali/devel-api/text-abstraction/font-client.h>
+
+#include <dali/internal/system/common/callback-manager.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+#include <dali/internal/input/common/gesture-manager.h>
+#include <dali/internal/window-system/common/event-handler.h>
+#include <dali/internal/graphics/gles20/gl-proxy-implementation.h>
+#include <dali/internal/graphics/gles20/gl-implementation.h>
+#include <dali/internal/graphics/gles20/egl-sync-implementation.h>
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+#include <dali/internal/graphics/gles20/egl-factory.h>
+#include <dali/internal/input/common/imf-manager-impl.h>
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+#include <dali/internal/graphics/common/vsync-monitor.h>
+#include <dali/internal/system/common/object-profiler.h>
+#include <dali/internal/window-system/common/display-connection.h>
+#include <dali/internal/window-system/common/window-impl.h>
+
+#include <dali/internal/system/common/logging.h>
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+
+#include <dali/internal/system/common/locale-utils.h>
+
+using Dali::TextAbstraction::FontClient;
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+thread_local Adaptor* gThreadLocalAdaptor = NULL; // raw thread specific pointer to allow Adaptor::Get
+} // unnamed namespace
+
+Dali::Adaptor* Adaptor::New( Any nativeWindow, RenderSurface *surface, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions )
+{
+ Dali::Adaptor* adaptor = new Dali::Adaptor;
+ Adaptor* impl = new Adaptor( nativeWindow, *adaptor, surface, environmentOptions );
+ adaptor->mImpl = impl;
+
+ impl->Initialize(configuration);
+
+ return adaptor;
+}
+
+Dali::Adaptor* Adaptor::New( Dali::Window window, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions )
+{
+ Any winId = window.GetNativeHandle();
+
+ Window& windowImpl = Dali::GetImplementation(window);
+ Dali::Adaptor* adaptor = New( winId, windowImpl.GetSurface(), configuration, environmentOptions );
+ windowImpl.SetAdaptor(*adaptor);
+ return adaptor;
+}
+
+void Adaptor::Initialize( Dali::Configuration::ContextLoss configuration )
+{
+ // all threads here (event, update, and render) will send their logs to TIZEN Platform's LogMessage handler.
+ Dali::Integration::Log::LogFunction logFunction( Dali::TizenPlatform::LogMessage );
+ mEnvironmentOptions->SetLogFunction( logFunction );
+ mEnvironmentOptions->InstallLogFunction(); // install logging for main thread
+
+ mPlatformAbstraction = new TizenPlatform::TizenPlatformAbstraction;
+
+ std::string path;
+ GetDataStoragePath( path );
+ mPlatformAbstraction->SetDataStoragePath( path );
+
+ ResourcePolicy::DataRetention dataRetentionPolicy = ResourcePolicy::DALI_DISCARDS_ALL_DATA;
+ if( configuration == Dali::Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS )
+ {
+ dataRetentionPolicy = ResourcePolicy::DALI_DISCARDS_ALL_DATA;
+ }
+ // Note, Tizen does not use DALI_RETAINS_ALL_DATA, as it can reload images from
+ // files automatically.
+
+ if( mEnvironmentOptions->PerformanceServerRequired() )
+ {
+ mPerformanceInterface = PerformanceInterfaceFactory::CreateInterface( *this, *mEnvironmentOptions );
+ }
+
+ mCallbackManager = CallbackManager::New();
+
+ PositionSize size = mSurface->GetPositionSize();
+
+ mGestureManager = new GestureManager(*this, Vector2(size.width, size.height), mCallbackManager, *mEnvironmentOptions);
+
+ if( mEnvironmentOptions->GetGlesCallTime() > 0 )
+ {
+ mGLES = new GlProxyImplementation( *mEnvironmentOptions );
+ }
+ else
+ {
+ mGLES = new GlImplementation();
+ }
+
+ const Integration::DepthBufferAvailable depthBufferAvailable = static_cast< Integration::DepthBufferAvailable >( mEnvironmentOptions->DepthBufferRequired() );
+ const Integration::StencilBufferAvailable stencilBufferAvailable = static_cast< Integration::StencilBufferAvailable >( mEnvironmentOptions->StencilBufferRequired() );
+
+ mEglFactory = new EglFactory( mEnvironmentOptions->GetMultiSamplingLevel(), depthBufferAvailable, stencilBufferAvailable );
+
+ EglSyncImplementation* eglSyncImpl = mEglFactory->GetSyncImplementation();
+
+ mCore = Integration::Core::New( *this,
+ *mPlatformAbstraction,
+ *mGLES,
+ *eglSyncImpl,
+ *mGestureManager,
+ dataRetentionPolicy ,
+ ( 0u != mEnvironmentOptions->GetRenderToFboInterval() ) ? Integration::RenderToFrameBuffer::TRUE : Integration::RenderToFrameBuffer::FALSE,
+ depthBufferAvailable,
+ stencilBufferAvailable );
+
+ const unsigned int timeInterval = mEnvironmentOptions->GetObjectProfilerInterval();
+ if( 0u < timeInterval )
+ {
+ mObjectProfiler = new ObjectProfiler( timeInterval );
+ }
+
+ mNotificationTrigger = mTriggerEventFactory.CreateTriggerEvent( MakeCallback( this, &Adaptor::ProcessCoreEvents ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER);
+
+ mVSyncMonitor = new VSyncMonitor;
+
+ mThreadController = new ThreadController( *this, *mEnvironmentOptions );
+
+ // Should be called after Core creation
+ if( mEnvironmentOptions->GetPanGestureLoggingLevel() )
+ {
+ Integration::EnableProfiling( Dali::Integration::PROFILING_TYPE_PAN_GESTURE );
+ }
+ if( mEnvironmentOptions->GetPanGesturePredictionMode() >= 0 )
+ {
+ Integration::SetPanGesturePredictionMode(mEnvironmentOptions->GetPanGesturePredictionMode());
+ }
+ if( mEnvironmentOptions->GetPanGesturePredictionAmount() >= 0 )
+ {
+ Integration::SetPanGesturePredictionAmount(mEnvironmentOptions->GetPanGesturePredictionAmount());
+ }
+ if( mEnvironmentOptions->GetPanGestureMaximumPredictionAmount() >= 0 )
+ {
+ Integration::SetPanGestureMaximumPredictionAmount(mEnvironmentOptions->GetPanGestureMaximumPredictionAmount());
+ }
+ if( mEnvironmentOptions->GetPanGestureMinimumPredictionAmount() >= 0 )
+ {
+ Integration::SetPanGestureMinimumPredictionAmount(mEnvironmentOptions->GetPanGestureMinimumPredictionAmount());
+ }
+ if( mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment() >= 0 )
+ {
+ Integration::SetPanGesturePredictionAmountAdjustment(mEnvironmentOptions->GetPanGesturePredictionAmountAdjustment());
+ }
+ if( mEnvironmentOptions->GetPanGestureSmoothingMode() >= 0 )
+ {
+ Integration::SetPanGestureSmoothingMode(mEnvironmentOptions->GetPanGestureSmoothingMode());
+ }
+ if( mEnvironmentOptions->GetPanGestureSmoothingAmount() >= 0.0f )
+ {
+ Integration::SetPanGestureSmoothingAmount(mEnvironmentOptions->GetPanGestureSmoothingAmount());
+ }
+ if( mEnvironmentOptions->GetPanGestureUseActualTimes() >= 0 )
+ {
+ Integration::SetPanGestureUseActualTimes( mEnvironmentOptions->GetPanGestureUseActualTimes() == 0 ? true : false );
+ }
+ if( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() >= 0 )
+ {
+ Integration::SetPanGestureInterpolationTimeRange( mEnvironmentOptions->GetPanGestureInterpolationTimeRange() );
+ }
+ if( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() >= 0 )
+ {
+ Integration::SetPanGestureScalarOnlyPredictionEnabled( mEnvironmentOptions->GetPanGestureScalarOnlyPredictionEnabled() == 0 ? true : false );
+ }
+ if( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() >= 0 )
+ {
+ Integration::SetPanGestureTwoPointPredictionEnabled( mEnvironmentOptions->GetPanGestureTwoPointPredictionEnabled() == 0 ? true : false );
+ }
+ if( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() >= 0 )
+ {
+ Integration::SetPanGestureTwoPointInterpolatePastTime( mEnvironmentOptions->GetPanGestureTwoPointInterpolatePastTime() );
+ }
+ if( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() >= 0.0f )
+ {
+ Integration::SetPanGestureTwoPointVelocityBias( mEnvironmentOptions->GetPanGestureTwoPointVelocityBias() );
+ }
+ if( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() >= 0.0f )
+ {
+ Integration::SetPanGestureTwoPointAccelerationBias( mEnvironmentOptions->GetPanGestureTwoPointAccelerationBias() );
+ }
+ if( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() >= 0 )
+ {
+ Integration::SetPanGestureMultitapSmoothingRange( mEnvironmentOptions->GetPanGestureMultitapSmoothingRange() );
+ }
+
+ // Set max texture size
+ if( mEnvironmentOptions->GetMaxTextureSize() > 0 )
+ {
+ Dali::SetMaxTextureSize( mEnvironmentOptions->GetMaxTextureSize() );
+ }
+
+ SetupSystemInformation();
+}
+
+Adaptor::~Adaptor()
+{
+ // Ensure stop status
+ Stop();
+
+ // set to NULL first as we do not want any access to Adaptor as it is being destroyed.
+ gThreadLocalAdaptor = NULL;
+
+ for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
+ {
+ (*iter)->OnDestroy();
+ }
+
+ delete mThreadController; // this will shutdown render thread, which will call Core::ContextDestroyed before exit
+ delete mVSyncMonitor;
+ delete mEventHandler;
+ delete mObjectProfiler;
+
+ delete mCore;
+ delete mEglFactory;
+ delete mGLES;
+ delete mGestureManager;
+ delete mPlatformAbstraction;
+ delete mCallbackManager;
+ delete mPerformanceInterface;
+
+ // uninstall it on this thread (main actor thread)
+ Dali::Integration::Log::UninstallLogFunction();
+
+ // Delete environment options if we own it
+ if( mEnvironmentOptionsOwned )
+ {
+ delete mEnvironmentOptions;
+ }
+}
+
+void Adaptor::Start()
+{
+ // it doesn't support restart after stop at this moment
+ // to support restarting, need more testing
+ if( READY != mState )
+ {
+ return;
+ }
+
+ // Start the callback manager
+ mCallbackManager->Start();
+
+ // create event handler
+ mEventHandler = new EventHandler( mSurface, *this, *mGestureManager, *this, mDragAndDropDetector );
+
+ if( mDeferredRotationObserver != NULL )
+ {
+ mEventHandler->SetRotationObserver(mDeferredRotationObserver);
+ mDeferredRotationObserver = NULL;
+ }
+
+ unsigned int dpiHor, dpiVer;
+ dpiHor = dpiVer = 0;
+ Dali::DisplayConnection::GetDpi(dpiHor, dpiVer);
+
+ // tell core about the DPI value
+ mCore->SetDpi(dpiHor, dpiVer);
+
+ // set the DPI value for font rendering
+ FontClient fontClient = FontClient::Get();
+ fontClient.SetDpi( dpiHor, dpiVer );
+
+ // Tell the core the size of the surface just before we start the render-thread
+ PositionSize size = mSurface->GetPositionSize();
+ mCore->SurfaceResized( size.width, size.height );
+
+ // Initialize the thread controller
+ mThreadController->Initialize();
+
+ ProcessCoreEvents(); // Ensure any startup messages are processed.
+
+ for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
+ {
+ (*iter)->OnStart();
+ }
+}
+
+// Dali::Internal::Adaptor::Adaptor::Pause
+void Adaptor::Pause()
+{
+ // Only pause the adaptor if we're actually running.
+ if( RUNNING == mState )
+ {
+ // Inform observers that we are about to be paused.
+ for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
+ {
+ (*iter)->OnPause();
+ }
+
+ // Reset the event handler when adaptor paused
+ if( mEventHandler )
+ {
+ mEventHandler->Pause();
+ }
+
+ mThreadController->Pause();
+ mState = PAUSED;
+
+ // Ensure any messages queued during pause callbacks are processed by doing another update.
+ RequestUpdateOnce();
+ }
+}
+
+// Dali::Internal::Adaptor::Adaptor::Resume
+void Adaptor::Resume()
+{
+ // Only resume the adaptor if we are in the suspended state.
+ if( PAUSED == mState )
+ {
+ mState = RUNNING;
+
+ // Reset the event handler when adaptor resumed
+ if( mEventHandler )
+ {
+ mEventHandler->Resume();
+ }
+
+ // Inform observers that we have resumed.
+ for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
+ {
+ (*iter)->OnResume();
+ }
+
+ // trigger processing of events queued up while paused
+ mCore->ProcessEvents();
+
+ // Do at end to ensure our first update/render after resumption includes the processed messages as well
+ mThreadController->Resume();
+ }
+}
+
+void Adaptor::Stop()
+{
+ if( RUNNING == mState ||
+ PAUSED == mState ||
+ PAUSED_WHILE_HIDDEN == mState )
+ {
+ for( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter )
+ {
+ (*iter)->OnStop();
+ }
+
+ mThreadController->Stop();
+
+ // Delete the TTS player
+ for(int i =0; i < Dali::TtsPlayer::MODE_NUM; i++)
+ {
+ if(mTtsPlayers[i])
+ {
+ mTtsPlayers[i].Reset();
+ }
+ }
+
+ delete mEventHandler;
+ mEventHandler = NULL;
+
+ delete mNotificationTrigger;
+ mNotificationTrigger = NULL;
+
+ mCallbackManager->Stop();
+
+ mState = STOPPED;
+ }
+}
+
+void Adaptor::ContextLost()
+{
+ mCore->GetContextNotifier()->NotifyContextLost(); // Inform stage
+}
+
+void Adaptor::ContextRegained()
+{
+ // Inform core, so that texture resources can be reloaded
+ mCore->RecoverFromContextLoss();
+
+ mCore->GetContextNotifier()->NotifyContextRegained(); // Inform stage
+}
+
+void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp )
+{
+ mEventHandler->FeedTouchPoint( point, timeStamp );
+}
+
+void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent )
+{
+ mEventHandler->FeedWheelEvent( wheelEvent );
+}
+
+void Adaptor::FeedKeyEvent( KeyEvent& keyEvent )
+{
+ mEventHandler->FeedKeyEvent( keyEvent );
+}
+
+void Adaptor::ReplaceSurface( Any nativeWindow, RenderSurface& surface )
+{
+ PositionSize positionSize = surface.GetPositionSize();
+
+ // let the core know the surface size has changed
+ mCore->SurfaceResized( positionSize.width, positionSize.height );
+
+ mResizedSignal.Emit( mAdaptor );
+
+ mNativeWindow = nativeWindow;
+ mSurface = &surface;
+
+ // flush the event queue to give the update-render thread chance
+ // to start processing messages for new camera setup etc as soon as possible
+ ProcessCoreEvents();
+
+ // this method blocks until the render thread has completed the replace.
+ mThreadController->ReplaceSurface(mSurface);
+}
+
+RenderSurface& Adaptor::GetSurface() const
+{
+ return *mSurface;
+}
+
+void Adaptor::ReleaseSurfaceLock()
+{
+ mSurface->ReleaseLock();
+}
+
+Dali::TtsPlayer Adaptor::GetTtsPlayer(Dali::TtsPlayer::Mode mode)
+{
+ if(!mTtsPlayers[mode])
+ {
+ // Create the TTS player when it needed, because it can reduce launching time.
+ mTtsPlayers[mode] = TtsPlayer::New(mode);
+ }
+
+ return mTtsPlayers[mode];
+}
+
+bool Adaptor::AddIdle( CallbackBase* callback, bool forceAdd )
+{
+ bool idleAdded(false);
+
+ // Only add an idle if the Adaptor is actually running
+ if( RUNNING == mState || READY == mState || forceAdd )
+ {
+ idleAdded = mCallbackManager->AddIdleCallback( callback );
+ }
+
+ return idleAdded;
+}
+
+void Adaptor::RemoveIdle( CallbackBase* callback )
+{
+ mCallbackManager->RemoveIdleCallback( callback );
+}
+
+Dali::Adaptor& Adaptor::Get()
+{
+ DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" );
+ return gThreadLocalAdaptor->mAdaptor;
+}
+
+bool Adaptor::IsAvailable()
+{
+ return gThreadLocalAdaptor != NULL;
+}
+
+void Adaptor::SceneCreated()
+{
+ mCore->SceneCreated();
+}
+
+Dali::Integration::Core& Adaptor::GetCore()
+{
+ return *mCore;
+}
+
+void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender )
+{
+ mThreadController->SetRenderRefreshRate( numberOfVSyncsPerRender );
+}
+
+void Adaptor::SetUseHardwareVSync( bool useHardware )
+{
+ mVSyncMonitor->SetUseHardwareVSync( useHardware );
+}
+
+EglFactory& Adaptor::GetEGLFactory() const
+{
+ DALI_ASSERT_DEBUG( mEglFactory && "EGL Factory not created" );
+ return *mEglFactory;
+}
+
+EglFactoryInterface& Adaptor::GetEGLFactoryInterface() const
+{
+ return *mEglFactory;
+}
+
+Integration::GlAbstraction& Adaptor::GetGlAbstraction() const
+{
+ DALI_ASSERT_DEBUG( mGLES && "GLImplementation not created" );
+ return *mGLES;
+}
+
+Dali::Integration::PlatformAbstraction& Adaptor::GetPlatformAbstractionInterface()
+{
+ return *mPlatformAbstraction;
+}
+
+Dali::Integration::GlAbstraction& Adaptor::GetGlesInterface()
+{
+ return *mGLES;
+}
+
+TriggerEventInterface& Adaptor::GetProcessCoreEventsTrigger()
+{
+ return *mNotificationTrigger;
+}
+
+TriggerEventFactoryInterface& Adaptor::GetTriggerEventFactoryInterface()
+{
+ return mTriggerEventFactory;
+}
+
+SocketFactoryInterface& Adaptor::GetSocketFactoryInterface()
+{
+ return mSocketFactory;
+}
+
+RenderSurface* Adaptor::GetRenderSurfaceInterface()
+{
+ return mSurface;
+}
+
+VSyncMonitorInterface* Adaptor::GetVSyncMonitorInterface()
+{
+ return mVSyncMonitor;
+}
+
+TraceInterface& Adaptor::GetKernelTraceInterface()
+{
+ return mKernelTracer;
+}
+
+TraceInterface& Adaptor::GetSystemTraceInterface()
+{
+ return mSystemTracer;
+}
+
+PerformanceInterface* Adaptor::GetPerformanceInterface()
+{
+ return mPerformanceInterface;
+}
+
+Integration::PlatformAbstraction& Adaptor::GetPlatformAbstraction() const
+{
+ DALI_ASSERT_DEBUG( mPlatformAbstraction && "PlatformAbstraction not created" );
+ return *mPlatformAbstraction;
+}
+
+void Adaptor::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
+{
+ mDragAndDropDetector = detector;
+
+ if ( mEventHandler )
+ {
+ mEventHandler->SetDragAndDropDetector( detector );
+ }
+}
+
+void Adaptor::SetRotationObserver( RotationObserver* observer )
+{
+ if( mEventHandler )
+ {
+ mEventHandler->SetRotationObserver( observer );
+ }
+ else if( mState == READY )
+ {
+ // Set once event handler exists
+ mDeferredRotationObserver = observer;
+ }
+}
+
+void Adaptor::DestroyTtsPlayer(Dali::TtsPlayer::Mode mode)
+{
+ if(mTtsPlayers[mode])
+ {
+ mTtsPlayers[mode].Reset();
+ }
+}
+
+void Adaptor::SetMinimumPinchDistance(float distance)
+{
+ if( mGestureManager )
+ {
+ mGestureManager->SetMinimumPinchDistance(distance);
+ }
+}
+
+Any Adaptor::GetNativeWindowHandle()
+{
+ return mNativeWindow;
+}
+
+void Adaptor::SetUseRemoteSurface(bool useRemoteSurface)
+{
+ mUseRemoteSurface = useRemoteSurface;
+}
+
+void Adaptor::AddObserver( LifeCycleObserver& observer )
+{
+ ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
+
+ if ( match == mObservers.end() )
+ {
+ mObservers.push_back( &observer );
+ }
+}
+
+void Adaptor::RemoveObserver( LifeCycleObserver& observer )
+{
+ ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) );
+
+ if ( match != mObservers.end() )
+ {
+ mObservers.erase( match );
+ }
+}
+
+void Adaptor::QueueCoreEvent(const Dali::Integration::Event& event)
+{
+ if( mCore )
+ {
+ mCore->QueueEvent(event);
+ }
+}
+
+void Adaptor::ProcessCoreEvents()
+{
+ if( mCore )
+ {
+ if( mPerformanceInterface )
+ {
+ mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_START );
+ }
+
+ mCore->ProcessEvents();
+
+ if( mPerformanceInterface )
+ {
+ mPerformanceInterface->AddMarker( PerformanceInterface::PROCESS_EVENTS_END );
+ }
+ }
+}
+
+void Adaptor::RequestUpdate( bool forceUpdate )
+{
+ switch( mState )
+ {
+ case RUNNING:
+ {
+ mThreadController->RequestUpdate();
+ break;
+ }
+ case PAUSED:
+ case PAUSED_WHILE_HIDDEN:
+ {
+ // When Dali applications are partially visible behind the lock-screen,
+ // the indicator must be updated (therefore allow updates in the PAUSED state)
+ if( forceUpdate )
+ {
+ mThreadController->RequestUpdateOnce();
+ }
+ break;
+ }
+ default:
+ {
+ // Do nothing
+ break;
+ }
+ }
+}
+
+void Adaptor::RequestProcessEventsOnIdle( bool forceProcess )
+{
+ // Only request a notification if the Adaptor is actually running
+ // and we haven't installed the idle notification
+ if( ( ! mNotificationOnIdleInstalled ) && ( RUNNING == mState || READY == mState || forceProcess ) )
+ {
+ mNotificationOnIdleInstalled = AddIdle( MakeCallback( this, &Adaptor::ProcessCoreEventsFromIdle ), forceProcess );
+ }
+}
+
+void Adaptor::OnWindowShown()
+{
+ if ( PAUSED_WHILE_HIDDEN == mState )
+ {
+ // Adaptor can now be resumed
+ mState = PAUSED;
+
+ Resume();
+
+ // Force a render task
+ RequestUpdateOnce();
+ }
+}
+
+void Adaptor::OnWindowHidden()
+{
+ if ( RUNNING == mState )
+ {
+ Pause();
+
+ // Adaptor cannot be resumed until the window is shown
+ mState = PAUSED_WHILE_HIDDEN;
+ }
+}
+
+// Dali::Internal::Adaptor::Adaptor::OnDamaged
+void Adaptor::OnDamaged( const DamageArea& area )
+{
+ // This is needed for the case where Dali window is partially obscured
+ RequestUpdate( false );
+}
+
+void Adaptor::SurfaceResizePrepare( SurfaceSize surfaceSize )
+{
+ // let the core know the surface size has changed
+ mCore->SurfaceResized( surfaceSize.GetWidth(), surfaceSize.GetHeight() );
+
+ mResizedSignal.Emit( mAdaptor );
+}
+
+void Adaptor::SurfaceResizeComplete( SurfaceSize surfaceSize )
+{
+ // flush the event queue to give the update-render thread chance
+ // to start processing messages for new camera setup etc as soon as possible
+ ProcessCoreEvents();
+
+ // this method blocks until the render thread has completed the resizing.
+ mThreadController->ResizeSurface();
+}
+
+void Adaptor::NotifySceneCreated()
+{
+ GetCore().SceneCreated();
+
+ // Start thread controller after the scene has been created
+ mThreadController->Start();
+
+ // process after surface is created (registering to remote surface provider if required)
+ SurfaceInitialized();
+
+ mState = RUNNING;
+}
+
+void Adaptor::NotifyLanguageChanged()
+{
+ mLanguageChangedSignal.Emit( mAdaptor );
+}
+
+void Adaptor::RenderOnce()
+{
+ RequestUpdateOnce();
+}
+
+void Adaptor::RequestUpdateOnce()
+{
+ if( mThreadController )
+ {
+ mThreadController->RequestUpdateOnce();
+ }
+}
+
+void Adaptor::IndicatorSizeChanged(int height)
+{
+ // let the core know the indicator height is changed
+ mCore->SetTopMargin(height);
+}
+
+void Adaptor::ProcessCoreEventsFromIdle()
+{
+ ProcessCoreEvents();
+
+ // the idle handle automatically un-installs itself
+ mNotificationOnIdleInstalled = false;
+}
+
+Adaptor::Adaptor(Any nativeWindow, Dali::Adaptor& adaptor, RenderSurface* surface, EnvironmentOptions* environmentOptions)
+: mResizedSignal(),
+ mLanguageChangedSignal(),
+ mAdaptor( adaptor ),
+ mState( READY ),
+ mCore( NULL ),
+ mThreadController( NULL ),
+ mVSyncMonitor( NULL ),
+ mGLES( NULL ),
+ mGlSync( NULL ),
+ mEglFactory( NULL ),
+ mNativeWindow( nativeWindow ),
+ mSurface( surface ),
+ mPlatformAbstraction( NULL ),
+ mEventHandler( NULL ),
+ mCallbackManager( NULL ),
+ mNotificationOnIdleInstalled( false ),
+ mNotificationTrigger( NULL ),
+ mGestureManager( NULL ),
+ mDaliFeedbackPlugin(),
+ mFeedbackController( NULL ),
+ mTtsPlayers(),
+ mObservers(),
+ mDragAndDropDetector(),
+ mDeferredRotationObserver( NULL ),
+ mEnvironmentOptions( environmentOptions ? environmentOptions : new EnvironmentOptions /* Create the options if not provided */),
+ mPerformanceInterface( NULL ),
+ mKernelTracer(),
+ mSystemTracer(),
+ mTriggerEventFactory(),
+ mObjectProfiler( NULL ),
+ mSocketFactory(),
+ mEnvironmentOptionsOwned( environmentOptions ? false : true /* If not provided then we own the object */ ),
+ mUseRemoteSurface( false )
+{
+ DALI_ASSERT_ALWAYS( !IsAvailable() && "Cannot create more than one Adaptor per thread" );
+ gThreadLocalAdaptor = this;
+}
+
+// Stereoscopy
+
+void Adaptor::SetViewMode( ViewMode viewMode )
+{
+ mSurface->SetViewMode( viewMode );
+ mCore->SetViewMode( viewMode );
+}
+
+ViewMode Adaptor::GetViewMode() const
+{
+ return mCore->GetViewMode();
+}
+
+void Adaptor::SetStereoBase( float stereoBase )
+{
+ mCore->SetStereoBase( stereoBase );
+}
+
+float Adaptor::GetStereoBase() const
+{
+ return mCore->GetStereoBase();
+}
+
+void Adaptor::SetRootLayoutDirection( std::string locale )
+{
+ Dali::Stage stage = Dali::Stage::GetCurrent();
+
+ stage.GetRootLayer().SetProperty( Dali::Actor::Property::LAYOUT_DIRECTION,
+ static_cast< LayoutDirection::Type >( Internal::Adaptor::Locale::GetDirection( std::string( locale ) ) ) );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_IMPL_H__
+#define __DALI_INTERNAL_ADAPTOR_IMPL_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/common/view-mode.h>
+#include <dali/public-api/math/rect.h>
+#include <dali/public-api/signals/callback.h>
+#include <dali/public-api/math/uint-16-pair.h>
+#include <dali/integration-api/render-controller.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/adaptor.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/public-api/adaptor-framework/tts-player.h>
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+#include <dali/devel-api/adaptor-framework/clipboard.h>
+
+#include <dali/internal/legacy/common/tizen-platform-abstraction.h>
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+#include <dali/internal/system/common/environment-options.h>
+#include <dali/internal/system/common/core-event-interface.h>
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+#include <dali/internal/window-system/common/damage-observer.h>
+#include <dali/internal/window-system/common/window-visibility-observer.h>
+#include <dali/internal/system/common/kernel-trace.h>
+#include <dali/internal/system/common/system-trace.h>
+#include <dali/integration-api/trigger-event-factory.h>
+#include <dali/internal/network/common/socket-factory.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class Window;
+
+namespace Integration
+{
+class Core;
+class GlAbstraction;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class EventHandler;
+class EglFactory;
+class GestureManager;
+class GlImplementation;
+class GlSyncImplementation;
+class ThreadController;
+class TriggerEvent;
+class CallbackManager;
+class FeedbackPluginProxy;
+class FeedbackController;
+class RotationObserver;
+class VSyncMonitor;
+class PerformanceInterface;
+class LifeCycleObserver;
+class ObjectProfiler;
+
+/**
+ * Implementation of the Adaptor class.
+ */
+class Adaptor : public Integration::RenderController,
+ public AdaptorInternalServices,
+ public CoreEventInterface,
+ public DamageObserver,
+ public WindowVisibilityObserver
+{
+public:
+
+ typedef Dali::Adaptor::AdaptorSignalType AdaptorSignalType;
+
+ typedef Uint16Pair SurfaceSize; ///< Surface size type
+
+ /**
+ * Creates a New Adaptor
+ * @param[in] nativeWindow Native window handle
+ * @param[in] surface A render surface can be one of the following
+ * - Pixmap, adaptor will use existing Pixmap to draw on to
+ * - Window, adaptor will use existing Window to draw on to
+ * @param[in] configuration The context loss configuration ( to choose resource discard policy )
+ * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
+ */
+ static Dali::Adaptor* New( Any nativeWindow,
+ RenderSurface* surface,
+ Dali::Configuration::ContextLoss configuration,
+ EnvironmentOptions* environmentOptions );
+
+ /**
+ * Creates a New Adaptor
+ * @param[in] nativeWindow native window handle
+ * @param[in] configuration The context loss configuration ( to choose resource discard policy )
+ * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
+ */
+ static Dali::Adaptor* New( Dali::Window window, Dali::Configuration::ContextLoss configuration, EnvironmentOptions* environmentOptions );
+
+ /**
+ * 2-step initialisation, this should be called after creating an adaptor instance.
+ */
+ void Initialize(Dali::Configuration::ContextLoss configuration);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~Adaptor();
+
+ /**
+ * @copydoc Dali::Adaptor::Get()
+ */
+ static Dali::Adaptor& Get();
+
+ /**
+ * @copydoc Dali::Adaptor::IsAvailable()
+ */
+ static bool IsAvailable();
+
+ /**
+ * @copydoc Dali::Core::SceneCreated();
+ */
+ void SceneCreated();
+
+public: // AdaptorInternalServices implementation
+ /**
+ * @copydoc Dali::Adaptor::Start()
+ */
+ virtual void Start();
+
+ /**
+ * @copydoc Dali::Adaptor::Pause()
+ */
+ virtual void Pause();
+
+ /**
+ * @copydoc Dali::Adaptor::Resume()
+ */
+ virtual void Resume();
+
+ /**
+ * @copydoc Dali::Adaptor::Stop()
+ */
+ virtual void Stop();
+
+ /**
+ * @copydoc Dali::Adaptor::ContextLost()
+ */
+ virtual void ContextLost();
+
+ /**
+ * @copydoc Dali::Adaptor::ContextRegained()
+ */
+ virtual void ContextRegained();
+
+ /**
+ * @copydoc Dali::EventFeeder::FeedTouchPoint()
+ */
+ virtual void FeedTouchPoint( TouchPoint& point, int timeStamp );
+
+ /**
+ * @copydoc Dali::EventFeeder::FeedWheelEvent()
+ */
+ virtual void FeedWheelEvent( WheelEvent& wheelEvent );
+
+ /**
+ * @copydoc Dali::EventFeeder::FeedKeyEvent()
+ */
+ virtual void FeedKeyEvent( KeyEvent& keyEvent );
+
+ /**
+ * @copydoc AdaptorInterface::ReplaceSurface()
+ */
+ virtual void ReplaceSurface( Any nativeWindow, RenderSurface& surface );
+
+ /**
+ * @copydoc Dali::Adaptor::GetSurface()
+ */
+ virtual RenderSurface& GetSurface() const;
+
+ /**
+ * @copydoc Dali::Adaptor::ReleaseSurfaceLock()
+ */
+ virtual void ReleaseSurfaceLock();
+
+ /**
+ * Retrieve the TtsPlayer.
+ * @param[in] mode The mode of TtsPlayer
+ * @return A handle to the TtsPlayer.
+ */
+ virtual Dali::TtsPlayer GetTtsPlayer(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * @copydoc Dali::Adaptor::AddIdle()
+ */
+ virtual bool AddIdle( CallbackBase* callback, bool forceAdd );
+
+ /**
+ * @copydoc Dali::Adaptor::RemoveIdle()
+ */
+ virtual void RemoveIdle( CallbackBase* callback );
+
+public:
+
+ /**
+ * @return the Core instance
+ */
+ virtual Dali::Integration::Core& GetCore();
+
+ /**
+ * @copydoc Dali::Adaptor::SetRenderRefreshRate()
+ */
+ void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender );
+
+ /**
+ * @copydoc Dali::Adaptor::SetUseHardwareVSync()
+ */
+ void SetUseHardwareVSync(bool useHardware);
+
+ /**
+ * @return reference to EglFactory class
+ */
+ EglFactory& GetEGLFactory() const;
+
+ /**
+ * Return GlAbstraction.
+ * @return the GlAbstraction.
+ */
+ Integration::GlAbstraction& GetGlAbstraction() const;
+
+ /**
+ * Return the PlatformAbstraction.
+ * @return The PlatformAbstraction.
+ */
+ Integration::PlatformAbstraction& GetPlatformAbstraction() const;
+
+ /**
+ * Sets the Drag & Drop Listener.
+ * @param[in] detector The detector to send Drag & Drop events to.
+ */
+ void SetDragAndDropDetector( DragAndDropDetectorPtr detector );
+
+ /**
+ * Sets a rotation observer, or set to NULL to remove.
+ * @pre Adaptor::Start() has been called ( to create EventHandler )
+ * @param[in] observer The observer to listen for window rotation events
+ */
+ void SetRotationObserver( RotationObserver* observer );
+
+ /**
+ * Destroy the TtsPlayer of sepcific mode.
+ * @param[in] mode The mode of TtsPlayer to destroy
+ */
+ void DestroyTtsPlayer(Dali::TtsPlayer::Mode mode);
+
+ /**
+ * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
+ * trigger a pinch gesture
+ *
+ * @param[in] distance The minimum pinch distance in pixels
+ */
+ void SetMinimumPinchDistance(float distance);
+
+ /**
+ * Gets native window handle
+ *
+ * @return native window handle
+ */
+ Any GetNativeWindowHandle();
+
+ /**
+ * Sets use remote surface for eglSurface output
+ * @param[in] useRemoteSurface True if the remote surface is used
+ */
+ void SetUseRemoteSurface(bool useRemoteSurface);
+
+public:
+
+ /**
+ * Adds an adaptor observer so that we can observe the adaptor's lifetime events.
+ * @param[in] observer The observer.
+ * @note Observers should remove themselves when they are destroyed.
+ */
+ void AddObserver( LifeCycleObserver& observer );
+
+ /**
+ * Removes the observer from the adaptor.
+ * @param[in] observer The observer to remove.
+ * @note Observers should remove themselves when they are destroyed.
+ */
+ void RemoveObserver( LifeCycleObserver& observer );
+
+ /**
+ * Emits the Notification event to the Dali core.
+ */
+ void SendNotificationEvent();
+
+ /**
+ * Request adaptor to update once
+ */
+ void RequestUpdateOnce();
+
+ /**
+ * Request adaptor to update indicator's height
+ */
+ void IndicatorSizeChanged(int height);
+
+ /**
+ * @copydoc Dali::Adaptor::NotifySceneCreated()
+ */
+ void NotifySceneCreated();
+
+ /**
+ * @copydoc Dali::Adaptor::NotifyLanguageChanged()
+ */
+ void NotifyLanguageChanged();
+
+ /**
+ * Gets AppId of current application
+ */
+ void GetAppId( std::string& appId );
+
+ /**
+ * Informs core the surface size has changed
+ */
+ void SurfaceResizePrepare( SurfaceSize surfaceSize );
+
+ /**
+ * Informs ThreadController the surface size has changed
+ */
+ void SurfaceResizeComplete( SurfaceSize surfaceSize );
+
+ /**
+ * Sets layout direction of root by system language
+ * @param[in] locale System locale
+ */
+ void SetRootLayoutDirection( std::string locale );
+
+ /**
+ * @copydoc Dali::Adaptor::RenderOnce
+ */
+ void RenderOnce();
+
+public: //AdaptorInternalServices
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetPlatformAbstractionInterface()
+ */
+ virtual Dali::Integration::PlatformAbstraction& GetPlatformAbstractionInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetGlesInterface()
+ */
+ virtual Dali::Integration::GlAbstraction& GetGlesInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetEGLFactoryInterface()
+ */
+ virtual EglFactoryInterface& GetEGLFactoryInterface() const;
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetTriggerEventInterface()
+ */
+ virtual TriggerEventInterface& GetProcessCoreEventsTrigger();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetTriggerEventFactoryInterface()
+ */
+ virtual TriggerEventFactoryInterface& GetTriggerEventFactoryInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetSocketFactoryInterface()
+ */
+ virtual SocketFactoryInterface& GetSocketFactoryInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetRenderSurfaceInterface()
+ */
+ virtual RenderSurface* GetRenderSurfaceInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetVSyncMonitorInterface()
+ */
+ virtual VSyncMonitorInterface* GetVSyncMonitorInterface();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetPerformanceInterface()
+ */
+ virtual PerformanceInterface* GetPerformanceInterface();
+
+ /**
+ * copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetKernelTraceInterface()
+ */
+ virtual TraceInterface& GetKernelTraceInterface();
+
+ /**
+ * copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetSystemTraceInterface()
+ */
+ virtual TraceInterface& GetSystemTraceInterface();
+
+public: // Stereoscopy
+
+ /**
+ * @copydoc Dali::Integration::Core::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::Integration::Core::GetViewMode()
+ */
+ ViewMode GetViewMode() const;
+
+ /**
+ * @copydoc Dali::Integration::Core::SetStereoBase()
+ */
+ void SetStereoBase( float stereoBase );
+
+ /**
+ * @copydoc Dali::Integration::Core::GetStereoBase()
+ */
+ float GetStereoBase() const;
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::Adaptor::SignalResized
+ */
+ AdaptorSignalType& ResizedSignal()
+ {
+ return mResizedSignal;
+ }
+
+ /**
+ * @copydoc Dali::Adaptor::LanguageChangedSignal
+ */
+ AdaptorSignalType& LanguageChangedSignal()
+ {
+ return mLanguageChangedSignal;
+ }
+
+private: // From Dali::Internal::Adaptor::CoreEventInterface
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::CoreEventInterface::QueueCoreEvent()
+ */
+ virtual void QueueCoreEvent(const Dali::Integration::Event& event);
+
+ /**
+ * @copydoc Dali::Internal::Adaptor:CoreEventInterface:::ProcessCoreEvents()
+ */
+ virtual void ProcessCoreEvents();
+
+private: // From Dali::Integration::RenderController
+
+ /**
+ * @copydoc Dali::Integration::RenderController::RequestUpdate()
+ */
+ virtual void RequestUpdate( bool forceUpdate );
+
+ /**
+ * @copydoc Dali::Integration::RenderController::RequestProcessEventsOnIdle()
+ */
+ virtual void RequestProcessEventsOnIdle( bool forceProcess );
+
+private: // From Dali::Internal::Adaptor::WindowVisibilityObserver
+
+ /**
+ * Called when the window becomes fully or partially visible.
+ */
+ virtual void OnWindowShown();
+
+ /**
+ * Called when the window is fully hidden.
+ */
+ virtual void OnWindowHidden();
+
+private: // From Dali::Internal::Adaptor::DamageObserver
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::DamageObserver::OnDamaged()
+ */
+ void OnDamaged( const DamageArea& area );
+
+private:
+
+ // Undefined
+ Adaptor(const Adaptor&);
+ Adaptor& operator=(Adaptor&);
+
+private:
+
+ /**
+ * Assigns the render surface to the adaptor
+ *
+ */
+ void SetSurface(RenderSurface *surface);
+
+ /**
+ * called after surface is created
+ */
+ void SurfaceInitialized();
+
+ /**
+ * Sends an notification message from main loop idle handler
+ */
+ void ProcessCoreEventsFromIdle();
+
+ /**
+ * Gets path for data/resource storage.
+ * @param[out] path Path for data/resource storage
+ */
+ void GetDataStoragePath(std::string& path);
+
+ /**
+ * Sets up system information if needs
+ */
+ void SetupSystemInformation();
+
+private:
+
+ /**
+ * Constructor
+ * @param[in] nativeWindow native window handle
+ * @param[in] adaptor The public adaptor
+ * @param[in] surface A render surface can be one of the following
+ * - Pixmap, adaptor will use existing Pixmap to draw on to
+ * - Window, adaptor will use existing Window to draw on to
+ * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created.
+ */
+ Adaptor( Any nativeWindow, Dali::Adaptor& adaptor, RenderSurface* surface, EnvironmentOptions* environmentOptions );
+
+private: // Types
+
+ enum State
+ {
+ READY, ///< Initial state before Adaptor::Start is called.
+ RUNNING, ///< Adaptor is running.
+ PAUSED, ///< Adaptor has been paused.
+ PAUSED_WHILE_HIDDEN, ///< Adaptor is paused while window is hidden (& cannot be resumed until window is shown).
+ STOPPED, ///< Adaptor has been stopped.
+ };
+
+ typedef std::vector<LifeCycleObserver*> ObserverContainer;
+
+private: // Data
+
+ AdaptorSignalType mResizedSignal; ///< Resized signal.
+ AdaptorSignalType mLanguageChangedSignal; ///< Language changed signal.
+
+ Dali::Adaptor& mAdaptor; ///< Reference to public adaptor instance.
+ State mState; ///< Current state of the adaptor
+ Dali::Integration::Core* mCore; ///< Dali Core
+ ThreadController* mThreadController; ///< Controls the threads
+ VSyncMonitor* mVSyncMonitor; ///< Monitors VSync events
+ GlImplementation* mGLES; ///< GL implementation
+ GlSyncImplementation* mGlSync; ///< GL Sync implementation
+ EglFactory* mEglFactory; ///< EGL Factory
+
+ Any mNativeWindow; ///< window identifier
+ RenderSurface* mSurface; ///< Current surface
+ TizenPlatform::TizenPlatformAbstraction* mPlatformAbstraction; ///< Platform abstraction
+
+ EventHandler* mEventHandler; ///< event handler
+ CallbackManager* mCallbackManager; ///< Used to install callbacks
+ bool mNotificationOnIdleInstalled; ///< whether the idle handler is installed to send an notification event
+ TriggerEventInterface* mNotificationTrigger; ///< Notification event trigger
+ GestureManager* mGestureManager; ///< Gesture manager
+ FeedbackPluginProxy* mDaliFeedbackPlugin; ///< Used to access feedback support
+ FeedbackController* mFeedbackController; ///< Plays feedback effects for Dali-Toolkit UI Controls.
+ Dali::TtsPlayer mTtsPlayers[Dali::TtsPlayer::MODE_NUM]; ///< Provides TTS support
+ ObserverContainer mObservers; ///< A list of adaptor observer pointers
+ DragAndDropDetectorPtr mDragAndDropDetector; ///< The Drag & Drop detector
+ RotationObserver* mDeferredRotationObserver; ///< deferred Rotation observer needs event handler
+ EnvironmentOptions* mEnvironmentOptions; ///< environment options
+ PerformanceInterface* mPerformanceInterface; ///< Performance interface
+ KernelTrace mKernelTracer; ///< Kernel tracer
+ SystemTrace mSystemTracer; ///< System tracer
+ TriggerEventFactory mTriggerEventFactory; ///< Trigger event factory
+ ObjectProfiler* mObjectProfiler; ///< Tracks object lifetime for profiling
+ SocketFactory mSocketFactory; ///< Socket factory
+ const bool mEnvironmentOptionsOwned:1; ///< Whether we own the EnvironmentOptions (and thus, need to delete it)
+ bool mUseRemoteSurface; ///< whether the remoteSurface is used or not
+public:
+ inline static Adaptor& GetImplementation(Dali::Adaptor& adaptor) {return *adaptor.mImpl;}
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_IMPL_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
+#define __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/core.h>
+#include <dali/integration-api/gl-abstraction.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/trigger-event-interface.h>
+#include <dali/integration-api/trigger-event-factory-interface.h>
+#include <dali/internal/graphics/gles20/egl-factory-interface.h>
+#include <dali/internal/network/common/socket-factory-interface.h>
+#include <dali/internal/system/common/performance-interface.h>
+#include <dali/internal/graphics/common/vsync-monitor-interface.h>
+#include <dali/internal/network/common/trace-interface.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * A class to contain various interfaces provided by the adaptor which
+ * can be used by the cross platform parts of adaptor.
+ * E.g. any files held in adaptors/base/ directory
+ *
+ */
+class AdaptorInternalServices
+{
+
+public:
+
+ /**
+ * @return core
+ */
+ virtual Dali::Integration::Core& GetCore() = 0;
+
+ /**
+ * @return platform abstraction
+ */
+ virtual Dali::Integration::PlatformAbstraction& GetPlatformAbstractionInterface() = 0;
+
+ /**
+ * @return gles abstraction
+ */
+ virtual Dali::Integration::GlAbstraction& GetGlesInterface() = 0;
+
+ /**
+ * @return egl factory
+ */
+ virtual EglFactoryInterface& GetEGLFactoryInterface() const = 0;
+
+ /**
+ * Used by update-thread to notify core (main-thread) it has messages to process
+ * @return trigger event ProcessCoreEvents
+ */
+ virtual TriggerEventInterface& GetProcessCoreEventsTrigger() = 0;
+
+ /**
+ * @return trigger event factory interface
+ */
+ virtual TriggerEventFactoryInterface& GetTriggerEventFactoryInterface() = 0;
+
+ /**
+ * @return socket factory interface
+ */
+ virtual SocketFactoryInterface& GetSocketFactoryInterface() = 0;
+
+ /**
+ * @return render surface
+ */
+ virtual RenderSurface* GetRenderSurfaceInterface() = 0;
+
+ /**
+ * @return vsync monitor interface
+ */
+ virtual VSyncMonitorInterface* GetVSyncMonitorInterface() = 0;
+
+ /**
+ * @return performance interface
+ */
+ virtual PerformanceInterface* GetPerformanceInterface() = 0;
+
+ /**
+ * @return interface for logging to the kernel ( e.g. using ftrace )
+ */
+ virtual TraceInterface& GetKernelTraceInterface() = 0;
+
+ /**
+ * @return system trace interface, e.g. for using Tizen Trace (ttrace) or Android Trace (atrace)
+ */
+ virtual TraceInterface& GetSystemTraceInterface() = 0;
+
+
+protected:
+
+ /**
+ * constructor
+ */
+ AdaptorInternalServices()
+ {
+ };
+
+ /**
+ * virtual destructor
+ */
+ virtual ~AdaptorInternalServices()
+ {
+ };
+
+ // Undefined copy constructor.
+ AdaptorInternalServices( const AdaptorInternalServices& );
+
+ // Undefined assignment operator.
+ AdaptorInternalServices& operator=( const AdaptorInternalServices& );
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/adaptor.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/accessibility-adaptor.h>
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+Adaptor& Adaptor::New( Window window )
+{
+ return New( window, Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS );
+}
+
+Adaptor& Adaptor::New( Window window, Configuration::ContextLoss configuration )
+{
+ Adaptor* adaptor = Internal::Adaptor::Adaptor::New( window, configuration, NULL );
+ return *adaptor;
+}
+
+Adaptor& Adaptor::New( Any nativeWindow, const Dali::RenderSurface& surface )
+{
+ return New( nativeWindow, surface, Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS );
+}
+
+Adaptor& Adaptor::New( Any nativeWindow, const Dali::RenderSurface& surface, Configuration::ContextLoss configuration )
+{
+ Dali::RenderSurface* pSurface = const_cast<Dali::RenderSurface *>(&surface);
+ Adaptor* adaptor = Internal::Adaptor::Adaptor::New( nativeWindow, pSurface, configuration, NULL );
+ return *adaptor;
+}
+
+Adaptor::~Adaptor()
+{
+ delete mImpl;
+}
+
+void Adaptor::Start()
+{
+ mImpl->Start();
+}
+
+void Adaptor::Pause()
+{
+ mImpl->Pause();
+}
+
+void Adaptor::Resume()
+{
+ mImpl->Resume();
+}
+
+void Adaptor::Stop()
+{
+ mImpl->Stop();
+}
+
+bool Adaptor::AddIdle( CallbackBase* callback )
+{
+ return mImpl->AddIdle( callback, false );
+}
+
+void Adaptor::RemoveIdle( CallbackBase* callback )
+{
+ mImpl->RemoveIdle( callback );
+}
+
+void Adaptor::ReplaceSurface( Any nativeWindow, Dali::RenderSurface& surface )
+{
+ mImpl->ReplaceSurface(nativeWindow, surface);
+}
+
+Adaptor::AdaptorSignalType& Adaptor::ResizedSignal()
+{
+ return mImpl->ResizedSignal();
+}
+
+Adaptor::AdaptorSignalType& Adaptor::LanguageChangedSignal()
+{
+ return mImpl->LanguageChangedSignal();
+}
+
+RenderSurface& Adaptor::GetSurface()
+{
+ return mImpl->GetSurface();
+}
+
+Any Adaptor::GetNativeWindowHandle()
+{
+ return mImpl->GetNativeWindowHandle();
+}
+
+void Adaptor::ReleaseSurfaceLock()
+{
+ mImpl->ReleaseSurfaceLock();
+}
+
+void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender )
+{
+ mImpl->SetRenderRefreshRate( numberOfVSyncsPerRender );
+}
+
+void Adaptor::SetUseHardwareVSync(bool useHardware)
+{
+ mImpl->SetUseHardwareVSync( useHardware );
+}
+
+Adaptor& Adaptor::Get()
+{
+ return Internal::Adaptor::Adaptor::Get();
+}
+
+bool Adaptor::IsAvailable()
+{
+ return Internal::Adaptor::Adaptor::IsAvailable();
+}
+
+void Adaptor::NotifySceneCreated()
+{
+ mImpl->NotifySceneCreated();
+}
+
+void Adaptor::NotifyLanguageChanged()
+{
+ mImpl->NotifyLanguageChanged();
+}
+
+void Adaptor::SetMinimumPinchDistance(float distance)
+{
+ mImpl->SetMinimumPinchDistance(distance);
+}
+
+void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp )
+{
+ mImpl->FeedTouchPoint(point, timeStamp);
+}
+
+void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent )
+{
+ mImpl->FeedWheelEvent(wheelEvent);
+}
+
+void Adaptor::FeedKeyEvent( KeyEvent& keyEvent )
+{
+ mImpl->FeedKeyEvent(keyEvent);
+}
+
+void Adaptor::SceneCreated()
+{
+ mImpl->SceneCreated();
+}
+
+void Adaptor::SetViewMode( ViewMode mode )
+{
+ mImpl->SetViewMode( mode );
+}
+
+void Adaptor::SetStereoBase( float stereoBase )
+{
+ mImpl->SetStereoBase( stereoBase );
+}
+
+void Adaptor::RenderOnce()
+{
+ mImpl->RenderOnce();
+}
+
+Adaptor::Adaptor()
+: mImpl( NULL )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/application-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
+#include <dali/internal/system/common/command-line-options.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/adaptor/common/framework.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/adaptor/common/lifecycle-controller-impl.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+class TizenPlatformAbstraction;
+}
+
+namespace Integration
+{
+class Core;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+ApplicationPtr Application::gPreInitializedApplication( NULL );
+
+ApplicationPtr Application::New(
+ int* argc,
+ char **argv[],
+ const std::string& stylesheet,
+ Dali::Application::WINDOW_MODE windowMode,
+ const PositionSize& positionSize,
+ Framework::Type applicationType)
+{
+ ApplicationPtr application ( new Application (argc, argv, stylesheet, windowMode, positionSize, applicationType ) );
+ return application;
+}
+
+void Application::PreInitialize( int* argc, char** argv[] )
+{
+ if( !gPreInitializedApplication )
+ {
+ gPreInitializedApplication = new Application ( argc, argv, "", Dali::Application::OPAQUE, PositionSize(), Framework::NORMAL );
+
+ gPreInitializedApplication->CreateWindow(); // Only create window
+
+ gPreInitializedApplication->mLaunchpadState = Launchpad::PRE_INITIALIZED;
+ }
+}
+
+Application::Application( int* argc, char** argv[], const std::string& stylesheet,
+ Dali::Application::WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType )
+: mInitSignal(),
+ mTerminateSignal(),
+ mPauseSignal(),
+ mResumeSignal(),
+ mResetSignal(),
+ mResizeSignal(),
+ mAppControlSignal(),
+ mLanguageChangedSignal(),
+ mRegionChangedSignal(),
+ mBatteryLowSignal(),
+ mMemoryLowSignal(),
+ mEventLoop( NULL ),
+ mFramework( NULL ),
+ mContextLossConfiguration( Configuration::APPLICATION_DOES_NOT_HANDLE_CONTEXT_LOSS ),
+ mCommandLineOptions( NULL ),
+ mSingletonService( SingletonService::New() ),
+ mAdaptor( NULL ),
+ mWindow(),
+ mWindowMode( windowMode ),
+ mName(),
+ mStylesheet( stylesheet ),
+ mEnvironmentOptions(),
+ mWindowPositionSize( positionSize ),
+ mLaunchpadState( Launchpad::NONE ),
+ mSlotDelegate( this )
+{
+ // Get mName from environment options
+ mName = mEnvironmentOptions.GetWindowName();
+ if( mName.empty() && argc && ( *argc > 0 ) )
+ {
+ // Set mName from command-line args if environment option not set
+ mName = (*argv)[0];
+ }
+
+ mCommandLineOptions = new CommandLineOptions(argc, argv);
+ mFramework = new Framework( *this, argc, argv, applicationType );
+ mUseRemoteSurface = (applicationType == Framework::WATCH);
+}
+
+Application::~Application()
+{
+ mSingletonService.UnregisterAll();
+
+ mWindow.Reset();
+ delete mAdaptor;
+ delete mCommandLineOptions;
+ delete mFramework;
+}
+
+void Application::CreateWindow()
+{
+ if( mWindowPositionSize.width == 0 && mWindowPositionSize.height == 0 )
+ {
+ if( mCommandLineOptions->stageWidth > 0 && mCommandLineOptions->stageHeight > 0 )
+ {
+ // Command line options override environment options and full screen
+ mWindowPositionSize.width = mCommandLineOptions->stageWidth;
+ mWindowPositionSize.height = mCommandLineOptions->stageHeight;
+ }
+ else if( mEnvironmentOptions.GetWindowWidth() && mEnvironmentOptions.GetWindowHeight() )
+ {
+ // Environment options override full screen functionality if command line arguments not provided
+ mWindowPositionSize.width = mEnvironmentOptions.GetWindowWidth();
+ mWindowPositionSize.height = mEnvironmentOptions.GetWindowHeight();
+ }
+ }
+
+ const std::string& windowClassName = mEnvironmentOptions.GetWindowClassName();
+ mWindow = Dali::Window::New( mWindowPositionSize, mName, windowClassName, mWindowMode == Dali::Application::TRANSPARENT );
+
+ int indicatorVisibleMode = mEnvironmentOptions.GetIndicatorVisibleMode();
+ if( indicatorVisibleMode >= Dali::Window::INVISIBLE && indicatorVisibleMode <= Dali::Window::AUTO )
+ {
+ GetImplementation( mWindow ).SetIndicatorVisibleMode( static_cast< Dali::Window::IndicatorVisibleMode >( indicatorVisibleMode ) );
+ }
+
+ // Quit the application when the window is closed
+ GetImplementation( mWindow ).DeleteRequestSignal().Connect( mSlotDelegate, &Application::Quit );
+}
+
+void Application::CreateAdaptor()
+{
+ DALI_ASSERT_ALWAYS( mWindow && "Window required to create adaptor" );
+
+ mAdaptor = Dali::Internal::Adaptor::Adaptor::New( mWindow, mContextLossConfiguration, &mEnvironmentOptions );
+
+ mAdaptor->ResizedSignal().Connect( mSlotDelegate, &Application::OnResize );
+
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetUseRemoteSurface( mUseRemoteSurface );
+}
+
+void Application::MainLoop(Dali::Configuration::ContextLoss configuration)
+{
+ mContextLossConfiguration = configuration;
+
+ // Run the application
+ mFramework->Run();
+}
+
+void Application::Lower()
+{
+ // Lower the application without quitting it.
+ mWindow.Lower();
+}
+
+void Application::Quit()
+{
+ // Actually quit the application.
+ // Force a call to Quit even if adaptor is not running.
+ Internal::Adaptor::Adaptor::GetImplementation(*mAdaptor).AddIdle( MakeCallback( this, &Application::QuitFromMainLoop ), true );
+}
+
+void Application::QuitFromMainLoop()
+{
+ mAdaptor->Stop();
+
+ mFramework->Quit();
+ // This will trigger OnTerminate(), below, after the main loop has completed.
+}
+
+void Application::DoInit()
+{
+ // If an application was pre-initialized, a window was made in advance
+ if( mLaunchpadState == Launchpad::NONE )
+ {
+ CreateWindow();
+ }
+
+ CreateAdaptor();
+
+ // Run the adaptor
+ mAdaptor->Start();
+
+ // Check if user requires no vsyncing and set Adaptor
+ if (mCommandLineOptions->noVSyncOnRender)
+ {
+ mAdaptor->SetUseHardwareVSync(false);
+ }
+
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetStereoBase( mCommandLineOptions->stereoBase );
+ if( mCommandLineOptions->viewMode != 0 )
+ {
+ ViewMode viewMode = MONO;
+ if( mCommandLineOptions->viewMode <= STEREO_INTERLACED )
+ {
+ viewMode = static_cast<ViewMode>( mCommandLineOptions->viewMode );
+ }
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetViewMode( viewMode );
+ }
+
+ if( ! mStylesheet.empty() )
+ {
+ Dali::StyleMonitor::Get().SetTheme( mStylesheet );
+ }
+}
+
+void Application::DoStart()
+{
+ mAdaptor->NotifySceneCreated();
+}
+
+void Application::DoTerminate()
+{
+ if( mAdaptor )
+ {
+ // Ensure that the render-thread is not using the surface(window) after we delete it
+ mAdaptor->Stop();
+ }
+
+ mWindow.Reset();
+}
+
+void Application::DoPause()
+{
+ mAdaptor->Pause();
+}
+
+void Application::DoResume()
+{
+ mAdaptor->Resume();
+}
+
+void Application::DoLanguageChange()
+{
+ mAdaptor->NotifyLanguageChanged();
+}
+
+void Application::OnInit()
+{
+ mFramework->AddAbortCallback( MakeCallback( this, &Application::QuitFromMainLoop ) );
+
+ DoInit();
+
+ // Wire up the LifecycleController
+ Dali::LifecycleController lifecycleController = Dali::LifecycleController::Get();
+
+ InitSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnInit );
+ TerminateSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnTerminate );
+ PauseSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnPause );
+ ResumeSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnResume );
+ ResetSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnReset );
+ ResizeSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnResize );
+ LanguageChangedSignal().Connect( &GetImplementation( lifecycleController ), &LifecycleController::OnLanguageChanged );
+
+ Dali::Application application(this);
+ mInitSignal.Emit( application );
+
+ DoStart();
+}
+
+void Application::OnTerminate()
+{
+ // we've been told to quit by AppCore, ecore_x_destroy has been called, need to quit synchronously
+ // delete the window as ecore_x has been destroyed by AppCore
+
+ Dali::Application application(this);
+ mTerminateSignal.Emit( application );
+
+ DoTerminate();
+}
+
+void Application::OnPause()
+{
+ // A DALi app should handle Pause/Resume events.
+ // DALi just delivers the framework Pause event to the application, but not actually pause DALi core.
+ // Pausing DALi core only occurs on the Window Hidden framework event
+ Dali::Application application(this);
+ mPauseSignal.Emit( application );
+}
+
+void Application::OnResume()
+{
+ // Emit the signal first so the application can queue any messages before we do an update/render
+ // This ensures we do not just redraw the last frame before pausing if that's not required
+ Dali::Application application(this);
+ mResumeSignal.Emit( application );
+
+ // DALi just delivers the framework Resume event to the application.
+ // Resuming DALi core only occurs on the Window Show framework event
+}
+
+void Application::OnReset()
+{
+ /*
+ * usually, reset callback was called when a caller request to launch this application via aul.
+ * because Application class already handled initialization in OnInit(), OnReset do nothing.
+ */
+ Dali::Application application(this);
+ mResetSignal.Emit( application );
+}
+
+void Application::OnAppControl(void *data)
+{
+ Dali::Application application(this);
+ mAppControlSignal.Emit( application , data );
+}
+
+void Application::OnLanguageChanged()
+{
+ DoLanguageChange();
+ Dali::Application application(this);
+ mLanguageChangedSignal.Emit( application );
+}
+
+void Application::OnRegionChanged()
+{
+ Dali::Application application(this);
+ mRegionChangedSignal.Emit( application );
+}
+
+void Application::OnBatteryLow( Dali::DeviceStatus::Battery::Status status )
+{
+ Dali::Application application(this);
+ mBatteryLowSignal.Emit( application );
+
+ mLowBatterySignal.Emit( status );
+}
+
+void Application::OnMemoryLow( Dali::DeviceStatus::Memory::Status status )
+{
+ Dali::Application application(this);
+ mMemoryLowSignal.Emit( application );
+
+ mLowMemorySignal.Emit( status );
+}
+void Application::OnResize(Dali::Adaptor& adaptor)
+{
+ Dali::Application application(this);
+ mResizeSignal.Emit( application );
+}
+
+bool Application::AddIdle( CallbackBase* callback )
+{
+ return mAdaptor->AddIdle( callback );
+}
+
+std::string Application::GetRegion() const
+{
+ return mFramework->GetRegion();
+}
+
+std::string Application::GetLanguage() const
+{
+ return mFramework->GetLanguage();
+}
+
+Dali::Adaptor& Application::GetAdaptor()
+{
+ return *mAdaptor;
+}
+
+Dali::Window Application::GetWindow()
+{
+ return mWindow;
+}
+
+// Stereoscopy
+
+void Application::SetViewMode( ViewMode viewMode )
+{
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetViewMode( viewMode );
+}
+
+ViewMode Application::GetViewMode() const
+{
+ return Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).GetViewMode();
+}
+
+void Application::SetStereoBase( float stereoBase )
+{
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).SetStereoBase( stereoBase );
+}
+
+float Application::GetStereoBase() const
+{
+ return Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).GetStereoBase();
+}
+
+
+void Application::ReplaceWindow( const PositionSize& positionSize, const std::string& name )
+{
+ Dali::Window newWindow = Dali::Window::New( positionSize, name, mWindowMode == Dali::Application::TRANSPARENT );
+ Window& windowImpl = GetImplementation(newWindow);
+ windowImpl.SetAdaptor(*mAdaptor);
+
+ int indicatorVisibleMode = mEnvironmentOptions.GetIndicatorVisibleMode();
+ if( indicatorVisibleMode >= Dali::Window::INVISIBLE && indicatorVisibleMode <= Dali::Window::AUTO )
+ {
+ GetImplementation( newWindow ).SetIndicatorVisibleMode( static_cast< Dali::Window::IndicatorVisibleMode >( indicatorVisibleMode ) );
+ }
+
+ Dali::RenderSurface* renderSurface = windowImpl.GetSurface();
+
+ Any nativeWindow = newWindow.GetNativeHandle();
+ Internal::Adaptor::Adaptor::GetImplementation( *mAdaptor ).ReplaceSurface(nativeWindow, *renderSurface);
+ mWindow = newWindow;
+ mWindowPositionSize = positionSize;
+}
+
+std::string Application::GetResourcePath()
+{
+ return Internal::Adaptor::Framework::GetResourcePath();
+}
+
+void Application::SetStyleSheet( const std::string& stylesheet )
+{
+ mStylesheet = stylesheet;
+}
+
+
+ApplicationPtr Application::GetPreInitializedApplication()
+{
+ return gPreInitializedApplication;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_APPLICATION_H__
+#define __DALI_INTERNAL_APPLICATION_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/math/rect.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application.h>
+#include <dali/devel-api/adaptor-framework/singleton-service.h>
+
+#include <dali/internal/adaptor/common/framework.h>
+#include <dali/internal/window-system/common/window-impl.h>
+#include <dali/internal/system/common/environment-options.h>
+
+namespace Dali
+{
+class Adaptor;
+class Window;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace Launchpad
+{
+
+/**
+ * @brief Launchpad is used to improve application launch performance.
+ * When an application is pre-initialized, so files are preloaded, some functions are initialized and a window is made in advance.
+ */
+enum State
+{
+ NONE, ///< The default state
+ PRE_INITIALIZED ///< Application is pre-initialized.
+};
+
+} // namespace Launchpad
+
+class CommandLineOptions;
+class EventLoop;
+
+typedef Dali::Rect<int> PositionSize;
+
+class Application;
+typedef IntrusivePtr<Application> ApplicationPtr;
+
+/**
+ * Implementation of the Application class.
+ */
+class Application : public BaseObject, public Framework::Observer
+{
+public:
+
+ typedef Dali::Application::LowBatterySignalType LowBatterySignalType;
+ typedef Dali::Application::LowMemorySignalType LowMemorySignalType;
+ typedef Dali::Application::AppSignalType AppSignalType;
+ typedef Dali::Application::AppControlSignalType AppControlSignalType;
+ typedef Dali::Application::WINDOW_MODE WINDOW_MODE;
+
+ /**
+ * Create a new application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of Dali::Application::WINDOW_MODE
+ * @param[in] positionSize A position and a size of the window
+ * @param[in] applicationType A member of Dali::Framework::Type
+ */
+ static ApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet,
+ WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType );
+
+ /**
+ * @copydoc Dali::DevelApplication::PreInitialize()
+ */
+ static void PreInitialize( int* argc, char** argv[] );
+
+public:
+
+ /**
+ * @copydoc Dali::Application::MainLoop()
+ */
+ void MainLoop(Dali::Configuration::ContextLoss configuration);
+
+ /**
+ * @copydoc Dali::Application::Lower()
+ */
+ void Lower();
+
+ /**
+ * @copydoc Dali::Application::Quit()
+ */
+ void Quit();
+
+ /**
+ * @copydoc Dali::Application::AddIdle()
+ */
+ bool AddIdle( CallbackBase* callback );
+
+ /**
+ * @copydoc Dali::Application::GetAdaptor();
+ */
+ Dali::Adaptor& GetAdaptor();
+
+ /**
+ * @copydoc Dali::Application::GetWindow();
+ */
+ Dali::Window GetWindow();
+
+ /**
+ * @copydoc Dali::Application::GetRegion();
+ */
+ std::string GetRegion() const;
+
+ /**
+ * @copydoc Dali::Application::GetLanguage();
+ */
+ std::string GetLanguage() const;
+
+ /**
+ * @copydoc Dali::Application::ReplaceWindow();
+ */
+ void ReplaceWindow( const PositionSize& positionSize, const std::string& name);
+
+ /**
+ * @copydoc Dali::Application::GetResourcePath();
+ */
+ static std::string GetResourcePath();
+
+ /**
+ * Retrieves the pre-initialized application.
+ *
+ * @return A pointer to the pre-initialized application
+ */
+ static ApplicationPtr GetPreInitializedApplication();
+
+public: // Stereoscopy
+
+ /**
+ * @copydoc Dali::Application::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::Application::GetViewMode()
+ */
+ ViewMode GetViewMode() const;
+
+ /**
+ * @copydoc Dali::Application::SetStereoBase()
+ */
+ void SetStereoBase( float stereoBase );
+
+ /**
+ * @copydoc Dali::Application::GetStereoBase()
+ */
+ float GetStereoBase() const;
+
+public: // Lifecycle functionality
+
+ /**
+ * Called when OnInit is called or the framework is initialised.
+ */
+ void DoInit();
+
+ /**
+ * Called after OnInit is called or the framework is started.
+ */
+ void DoStart();
+
+ /**
+ * Called when OnTerminate is called or the framework is terminated.
+ */
+ void DoTerminate();
+
+ /**
+ * Called when OnPause is called or the framework is paused.
+ */
+ void DoPause();
+
+ /**
+ * Called when OnResume is called or the framework resumes from a paused state.
+ */
+ void DoResume();
+
+ /**
+ * Called when OnLanguageChanged is called or the framework informs the application that the language of the device has changed.
+ */
+ void DoLanguageChange();
+
+public: // From Framework::Observer
+
+ /**
+ * Called when the framework is initialised.
+ */
+ virtual void OnInit();
+
+ /**
+ * Called when the framework is terminated.
+ */
+ virtual void OnTerminate();
+
+ /**
+ * Called when the framework is paused.
+ */
+ virtual void OnPause();
+
+ /**
+ * Called when the framework resumes from a paused state.
+ */
+ virtual void OnResume();
+
+ /**
+ * Called when the framework received AppControlSignal.
+ * @param[in] The bundle data of AppControl event.
+ */
+ virtual void OnAppControl(void *data);
+
+ /**
+ * Called when the framework informs the application that it should reset itself.
+ */
+ virtual void OnReset();
+
+ /**
+ * Called when the framework informs the application that the language of the device has changed.
+ */
+ virtual void OnLanguageChanged();
+
+ /**
+ * Called when the framework informs the application that the region of the device has changed.
+ */
+ virtual void OnRegionChanged();
+
+ /**
+ * Called when the framework informs the application that the battery level of the device is low.
+ */
+ virtual void OnBatteryLow( Dali::DeviceStatus::Battery::Status status );
+
+ /**
+ * Called when the framework informs the application that the memory level of the device is low.
+ */
+ virtual void OnMemoryLow( Dali::DeviceStatus::Memory::Status status );
+
+public:
+
+ /**
+ * Signal handler when the adaptor's window resizes itself.
+ * @param[in] adaptor The adaptor
+ */
+ void OnResize(Dali::Adaptor& adaptor);
+
+ /**
+ * Sets a user defined theme file.
+ * This should be called before initialization.
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ void SetStyleSheet( const std::string& stylesheet );
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::Application::InitSignal()
+ */
+ Dali::Application::AppSignalType& InitSignal() { return mInitSignal; }
+
+ /**
+ * @copydoc Dali::Application::TerminateSignal()
+ */
+ Dali::Application::AppSignalType& TerminateSignal() { return mTerminateSignal; }
+
+ /**
+ * @copydoc Dali::Application::PauseSignal()
+ */
+ Dali::Application::AppSignalType& PauseSignal() { return mPauseSignal; }
+
+ /**
+ * @copydoc Dali::Application::ResumeSignal()
+ */
+ Dali::Application::AppSignalType& ResumeSignal() { return mResumeSignal; }
+
+ /**
+ * @copydoc Dali::Application::ResetSignal()
+ */
+ Dali::Application::AppSignalType& ResetSignal() { return mResetSignal; }
+
+ /**
+ * @copydoc Dali::Application::AppControlSignal()
+ */
+ Dali::Application::AppControlSignalType& AppControlSignal() { return mAppControlSignal; }
+
+ /**
+ * @copydoc Dali::Application::ResizeSignal()
+ */
+ Dali::Application::AppSignalType& ResizeSignal() { return mResizeSignal; }
+
+ /**
+ * @copydoc Dali::Application::LanguageChangedSignal()
+ */
+ Dali::Application::AppSignalType& LanguageChangedSignal() { return mLanguageChangedSignal; }
+
+ /**
+ * @copydoc Dali::Application::RegionChangedSignal()
+ */
+ Dali::Application::AppSignalType& RegionChangedSignal() { return mRegionChangedSignal; }
+
+ /**
+ * @copydoc Dali::Application::BatteryLowSignal()
+ */
+ Dali::Application::AppSignalType& BatteryLowSignal() { return mBatteryLowSignal; }
+
+ /**
+ * @copydoc Dali::Application::MemoryLowSignal()
+ */
+ Dali::Application::AppSignalType& MemoryLowSignal() { return mMemoryLowSignal; }
+
+ /**
+ * @copydoc Dali::Application::LowBatterySignal()
+ */
+ Dali::Application::LowBatterySignalType& LowBatterySignal() { return mLowBatterySignal; }
+
+ /**
+ * @copydoc Dali::Application:::LowMemorySignal()
+ */
+ Dali::Application::LowMemorySignalType& LowMemorySignal() { return mLowMemorySignal; }
+
+protected:
+
+ /**
+ * Private Constructor
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of Dali::Application::WINDOW_MODE
+ * @param[in] positionSize A position and a size of the window
+ * @param[in] applicationType A member of Dali::Framework::Type
+ */
+ Application( int* argc, char **argv[], const std::string& stylesheet,
+ WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType );
+
+ /**
+ * Destructor
+ */
+ virtual ~Application();
+
+ // Undefined
+ Application(const Application&);
+ Application& operator=(Application&);
+
+ /**
+ * Creates the window
+ */
+ void CreateWindow();
+
+ /**
+ * Creates the adaptor
+ */
+ void CreateAdaptor();
+
+ /**
+ * Quits from the main loop
+ */
+ void QuitFromMainLoop();
+
+private:
+
+ AppSignalType mInitSignal;
+ AppSignalType mTerminateSignal;
+ AppSignalType mPauseSignal;
+ AppSignalType mResumeSignal;
+ AppSignalType mResetSignal;
+ AppSignalType mResizeSignal;
+ AppControlSignalType mAppControlSignal;
+ AppSignalType mLanguageChangedSignal;
+ AppSignalType mRegionChangedSignal;
+ AppSignalType mBatteryLowSignal;
+ AppSignalType mMemoryLowSignal;
+ LowBatterySignalType mLowBatterySignal;
+ LowMemorySignalType mLowMemorySignal;
+
+ EventLoop* mEventLoop;
+ Framework* mFramework;
+
+ Dali::Configuration::ContextLoss mContextLossConfiguration;
+ CommandLineOptions* mCommandLineOptions;
+
+ Dali::SingletonService mSingletonService;
+ Dali::Adaptor* mAdaptor;
+ Dali::Window mWindow;
+ Dali::Application::WINDOW_MODE mWindowMode;
+ std::string mName;
+ std::string mStylesheet;
+ EnvironmentOptions mEnvironmentOptions;
+ PositionSize mWindowPositionSize;
+ Launchpad::State mLaunchpadState;
+ bool mUseRemoteSurface;
+
+ SlotDelegate< Application > mSlotDelegate;
+
+ static ApplicationPtr gPreInitializedApplication;
+};
+
+inline Application& GetImplementation(Dali::Application& application)
+{
+ DALI_ASSERT_ALWAYS(application && "application handle is empty");
+
+ BaseObject& handle = application.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::Application&>(handle);
+}
+
+inline const Application& GetImplementation(const Dali::Application& application)
+{
+ DALI_ASSERT_ALWAYS(application && "Timre handle is empty");
+
+ const BaseObject& handle = application.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::Application&>(handle);
+}
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_APPLICATION_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/combined-update-render-controller.h>
+
+// EXTERNAL INCLUDES
+#include <errno.h>
+#include <dali/integration-api/platform-abstraction.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/trigger-event-factory.h>
+#include <dali/internal/adaptor/common/combined-update-render-controller-debug.h>
+#include <dali/internal/system/common/environment-options.h>
+#include <dali/internal/system/common/time-service.h>
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const unsigned int CREATED_THREAD_COUNT = 1u;
+
+const int CONTINUOUS = -1;
+const int ONCE = 1;
+
+const unsigned int TRUE = 1u;
+const unsigned int FALSE = 0u;
+
+const unsigned int MILLISECONDS_PER_SECOND( 1e+3 );
+const float NANOSECONDS_TO_SECOND( 1e-9f );
+const unsigned int NANOSECONDS_PER_SECOND( 1e+9 );
+const unsigned int NANOSECONDS_PER_MILLISECOND( 1e+6 );
+
+// The following values will get calculated at compile time
+const float DEFAULT_FRAME_DURATION_IN_SECONDS( 1.0f / 60.0f );
+const uint64_t DEFAULT_FRAME_DURATION_IN_MILLISECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * MILLISECONDS_PER_SECOND );
+const uint64_t DEFAULT_FRAME_DURATION_IN_NANOSECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * NANOSECONDS_PER_SECOND );
+
+/**
+ * Handles the use case when an update-request is received JUST before we process a sleep-request. If we did not have an update-request count then
+ * there is a danger that, on the event-thread we could have:
+ * 1) An update-request where we do nothing as Update/Render thread still running.
+ * 2) Quickly followed by a sleep-request being handled where we pause the Update/Render Thread (even though we have an update to process).
+ *
+ * Using a counter means we increment the counter on an update-request, and decrement it on a sleep-request. This handles the above scenario because:
+ * 1) MAIN THREAD: Update Request: COUNTER = 1
+ * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
+ * 3) MAIN THREAD: Update Request: COUNTER = 2
+ * 4) MAIN THREAD: Sleep Request: COUNTER = 1 -> We do not sleep just yet
+ *
+ * Also ensures we preserve battery life by only doing ONE update when the above use case is not triggered.
+ * 1) MAIN THREAD: Update Request: COUNTER = 1
+ * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
+ * 3) MAIN THREAD: Sleep Request: COUNTER = 0 -> Go to sleep
+ */
+const unsigned int MAXIMUM_UPDATE_REQUESTS = 2;
+} // unnamed namespace
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// EVENT THREAD
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+CombinedUpdateRenderController::CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions )
+: mFpsTracker( environmentOptions ),
+ mUpdateStatusLogger( environmentOptions ),
+ mRenderHelper( adaptorInterfaces ),
+ mEventThreadSemaphore(),
+ mUpdateRenderThreadWaitCondition(),
+ mAdaptorInterfaces( adaptorInterfaces ),
+ mPerformanceInterface( adaptorInterfaces.GetPerformanceInterface() ),
+ mCore( adaptorInterfaces.GetCore() ),
+ mEnvironmentOptions( environmentOptions ),
+ mNotificationTrigger( adaptorInterfaces.GetProcessCoreEventsTrigger() ),
+ mSleepTrigger( NULL ),
+ mUpdateRenderThread( NULL ),
+ mDefaultFrameDelta( 0.0f ),
+ mDefaultFrameDurationMilliseconds( 0u ),
+ mDefaultFrameDurationNanoseconds( 0u ),
+ mDefaultHalfFrameNanoseconds( 0u ),
+ mUpdateRequestCount( 0u ),
+ mRunning( FALSE ),
+ mUpdateRenderRunCount( 0 ),
+ mDestroyUpdateRenderThread( FALSE ),
+ mUpdateRenderThreadCanSleep( FALSE ),
+ mPendingRequestUpdate( FALSE ),
+ mUseElapsedTimeAfterWait( FALSE ),
+ mNewSurface( NULL ),
+ mPostRendering( FALSE ),
+ mSurfaceResized( FALSE )
+{
+ LOG_EVENT_TRACE;
+
+ // Initialise frame delta/duration variables first
+ SetRenderRefreshRate( environmentOptions.GetRenderRefreshRate() );
+
+ // Set the thread-synchronization interface on the render-surface
+ RenderSurface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
+ if( currentSurface )
+ {
+ currentSurface->SetThreadSynchronization( *this );
+ }
+
+ TriggerEventFactoryInterface& triggerFactory = mAdaptorInterfaces.GetTriggerEventFactoryInterface();
+ mSleepTrigger = triggerFactory.CreateTriggerEvent( MakeCallback( this, &CombinedUpdateRenderController::ProcessSleepRequest ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
+
+ sem_init( &mEventThreadSemaphore, 0, 0 ); // Initialize to 0 so that it just waits if sem_post has not been called
+}
+
+CombinedUpdateRenderController::~CombinedUpdateRenderController()
+{
+ LOG_EVENT_TRACE;
+
+ Stop();
+
+ delete mSleepTrigger;
+}
+
+void CombinedUpdateRenderController::Initialize()
+{
+ LOG_EVENT_TRACE;
+
+ // Ensure Update/Render Thread not already created
+ DALI_ASSERT_ALWAYS( ! mUpdateRenderThread );
+
+ // Create Update/Render Thread
+ mUpdateRenderThread = new pthread_t();
+ int error = pthread_create( mUpdateRenderThread, NULL, InternalUpdateRenderThreadEntryFunc, this );
+ DALI_ASSERT_ALWAYS( !error && "Return code from pthread_create() when creating UpdateRenderThread" );
+
+ // The Update/Render thread will now run and initialise EGL etc. and will then wait for Start to be called
+ // When this function returns, the application initialisation on the event thread should occur
+}
+
+void CombinedUpdateRenderController::Start()
+{
+ LOG_EVENT_TRACE;
+
+ DALI_ASSERT_ALWAYS( !mRunning && mUpdateRenderThread );
+
+ // Wait until all threads created in Initialise are up and running
+ for( unsigned int i = 0; i < CREATED_THREAD_COUNT; ++i )
+ {
+ sem_wait( &mEventThreadSemaphore );
+ }
+
+ mRenderHelper.Start();
+
+ mRunning = TRUE;
+
+ LOG_EVENT( "Startup Complete, starting Update/Render Thread" );
+
+ RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
+}
+
+void CombinedUpdateRenderController::Pause()
+{
+ LOG_EVENT_TRACE;
+
+ mRunning = FALSE;
+
+ PauseUpdateRenderThread();
+
+ AddPerformanceMarker( PerformanceInterface::PAUSED );
+}
+
+void CombinedUpdateRenderController::Resume()
+{
+ LOG_EVENT_TRACE;
+
+ if( !mRunning && IsUpdateRenderThreadPaused() )
+ {
+ LOG_EVENT( "Resuming" );
+
+ RunUpdateRenderThread( CONTINUOUS, true /* Animation progression required while we were paused */ );
+
+ AddPerformanceMarker( PerformanceInterface::RESUME );
+
+ mRunning = TRUE;
+ }
+}
+
+void CombinedUpdateRenderController::Stop()
+{
+ LOG_EVENT_TRACE;
+
+ // Stop Rendering and the Update/Render Thread
+ mRenderHelper.Stop();
+
+ StopUpdateRenderThread();
+
+ if( mUpdateRenderThread )
+ {
+ LOG_EVENT( "Destroying UpdateRenderThread" );
+
+ // wait for the thread to finish
+ pthread_join( *mUpdateRenderThread, NULL );
+
+ delete mUpdateRenderThread;
+ mUpdateRenderThread = NULL;
+ }
+
+ mRunning = FALSE;
+}
+
+void CombinedUpdateRenderController::RequestUpdate()
+{
+ LOG_EVENT_TRACE;
+
+ // Increment the update-request count to the maximum
+ if( mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS )
+ {
+ ++mUpdateRequestCount;
+ }
+
+ if( mRunning && IsUpdateRenderThreadPaused() )
+ {
+ LOG_EVENT( "Processing" );
+
+ RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
+ }
+
+ ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
+ mPendingRequestUpdate = TRUE;
+}
+
+void CombinedUpdateRenderController::RequestUpdateOnce()
+{
+ // Increment the update-request count to the maximum
+ if( mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS )
+ {
+ ++mUpdateRequestCount;
+ }
+
+ if( IsUpdateRenderThreadPaused() )
+ {
+ LOG_EVENT_TRACE;
+
+ // Run Update/Render once
+ RunUpdateRenderThread( ONCE, false /* No animation progression */ );
+ }
+}
+
+void CombinedUpdateRenderController::ReplaceSurface( RenderSurface* newSurface )
+{
+ LOG_EVENT_TRACE;
+
+ // Set the ThreadSyncronizationInterface on the new surface
+ newSurface->SetThreadSynchronization( *this );
+
+ LOG_EVENT( "Starting to replace the surface, event-thread blocked" );
+
+ // Start replacing the surface.
+ {
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will replace the surface now
+ mNewSurface = newSurface;
+ mUpdateRenderThreadWaitCondition.Notify( lock );
+ }
+
+ // Wait until the surface has been replaced
+ sem_wait( &mEventThreadSemaphore );
+
+ LOG_EVENT( "Surface replaced, event-thread continuing" );
+}
+
+void CombinedUpdateRenderController::ResizeSurface()
+{
+ LOG_EVENT_TRACE;
+
+ LOG_EVENT( "Starting to resize the surface, event-thread blocked" );
+
+ // Start resizing the surface.
+ {
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will resize the surface now
+ mSurfaceResized = TRUE;
+ mUpdateRenderThreadWaitCondition.Notify( lock );
+ }
+
+ // Wait until the surface has been resized
+ sem_wait( &mEventThreadSemaphore );
+
+ LOG_EVENT( "Surface resized, event-thread continuing" );
+}
+
+void CombinedUpdateRenderController::SetRenderRefreshRate( unsigned int numberOfFramesPerRender )
+{
+ // Not protected by lock, but written to rarely so not worth adding a lock when reading
+ mDefaultFrameDelta = numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_SECONDS;
+ mDefaultFrameDurationMilliseconds = uint64_t( numberOfFramesPerRender ) * DEFAULT_FRAME_DURATION_IN_MILLISECONDS;
+ mDefaultFrameDurationNanoseconds = uint64_t( numberOfFramesPerRender ) * DEFAULT_FRAME_DURATION_IN_NANOSECONDS;
+ mDefaultHalfFrameNanoseconds = mDefaultFrameDurationNanoseconds / 2u;
+
+ LOG_EVENT( "mDefaultFrameDelta(%.6f), mDefaultFrameDurationMilliseconds(%lld), mDefaultFrameDurationNanoseconds(%lld)", mDefaultFrameDelta, mDefaultFrameDurationMilliseconds, mDefaultFrameDurationNanoseconds );
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// EVENT THREAD
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void CombinedUpdateRenderController::RunUpdateRenderThread( int numberOfCycles, bool useElapsedTime )
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mUpdateRenderRunCount = numberOfCycles;
+ mUpdateRenderThreadCanSleep = FALSE;
+ mUseElapsedTimeAfterWait = useElapsedTime;
+ LOG_COUNTER_EVENT( "mUpdateRenderRunCount: %d, mUseElapsedTimeAfterWait: %d", mUpdateRenderRunCount, mUseElapsedTimeAfterWait );
+ mUpdateRenderThreadWaitCondition.Notify( lock );
+}
+
+void CombinedUpdateRenderController::PauseUpdateRenderThread()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mUpdateRenderRunCount = 0;
+}
+
+void CombinedUpdateRenderController::StopUpdateRenderThread()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mDestroyUpdateRenderThread = TRUE;
+ mUpdateRenderThreadWaitCondition.Notify( lock );
+}
+
+bool CombinedUpdateRenderController::IsUpdateRenderThreadPaused()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ return ( mUpdateRenderRunCount != CONTINUOUS ) || // Report paused if NOT continuously running
+ mUpdateRenderThreadCanSleep; // Report paused if sleeping
+}
+
+void CombinedUpdateRenderController::ProcessSleepRequest()
+{
+ LOG_EVENT_TRACE;
+
+ // Decrement Update request count
+ if( mUpdateRequestCount > 0 )
+ {
+ --mUpdateRequestCount;
+ }
+
+ // Can sleep if our update-request count is 0
+ // Update/Render thread can choose to carry on updating if it determines more update/renders are required
+ if( mUpdateRequestCount == 0 )
+ {
+ LOG_EVENT( "Going to sleep" );
+
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mUpdateRenderThreadCanSleep = TRUE;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// UPDATE/RENDER THREAD
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void CombinedUpdateRenderController::UpdateRenderThread()
+{
+ // Install a function for logging
+ mEnvironmentOptions.InstallLogFunction();
+
+ LOG_UPDATE_RENDER( "THREAD CREATED" );
+
+ mRenderHelper.InitializeEgl();
+
+ // tell core it has a context
+ mCore.ContextCreated();
+
+ NotifyThreadInitialised();
+
+ // Update time
+ uint64_t lastFrameTime;
+ TimeService::GetNanoseconds( lastFrameTime );
+
+ LOG_UPDATE_RENDER( "THREAD INITIALISED" );
+
+ bool useElapsedTime = true;
+ bool updateRequired = true;
+ uint64_t timeToSleepUntil = 0;
+ int extraFramesDropped = 0;
+
+ const unsigned int renderToFboInterval = mEnvironmentOptions.GetRenderToFboInterval();
+ const bool renderToFboEnabled = 0u != renderToFboInterval;
+ unsigned int frameCount = 0u;
+
+ while( UpdateRenderReady( useElapsedTime, updateRequired, timeToSleepUntil ) )
+ {
+ LOG_UPDATE_RENDER_TRACE;
+
+ // Performance statistics are logged upon a VSYNC tick so use this point for a VSync marker
+ AddPerformanceMarker( PerformanceInterface::VSYNC );
+
+ uint64_t currentFrameStartTime = 0;
+ TimeService::GetNanoseconds( currentFrameStartTime );
+
+ const uint64_t timeSinceLastFrame = currentFrameStartTime - lastFrameTime;
+
+ // Optional FPS Tracking when continuously rendering
+ if( useElapsedTime && mFpsTracker.Enabled() )
+ {
+ float absoluteTimeSinceLastRender = timeSinceLastFrame * NANOSECONDS_TO_SECOND;
+ mFpsTracker.Track( absoluteTimeSinceLastRender );
+ }
+
+ lastFrameTime = currentFrameStartTime; // Store frame start time
+
+ //////////////////////////////
+ // REPLACE SURFACE
+ //////////////////////////////
+
+ RenderSurface* newSurface = ShouldSurfaceBeReplaced();
+ if( DALI_UNLIKELY( newSurface ) )
+ {
+ LOG_UPDATE_RENDER_TRACE_FMT( "Replacing Surface" );
+ mRenderHelper.ReplaceSurface( newSurface );
+ SurfaceReplaced();
+ }
+
+ //////////////////////////////
+ // RESIZE SURFACE
+ //////////////////////////////
+
+ const bool isRenderingToFbo = renderToFboEnabled && ( ( 0u == frameCount ) || ( 0u != frameCount % renderToFboInterval ) );
+ ++frameCount;
+
+ // The resizing will be applied in the next loop
+ bool surfaceResized = ShouldSurfaceBeResized();
+ if( DALI_UNLIKELY( surfaceResized ) )
+ {
+ LOG_UPDATE_RENDER_TRACE_FMT( "Resizing Surface" );
+ mRenderHelper.ResizeSurface();
+ SurfaceResized();
+ }
+
+ //////////////////////////////
+ // UPDATE
+ //////////////////////////////
+
+ const unsigned int currentTime = currentFrameStartTime / NANOSECONDS_PER_MILLISECOND;
+ const unsigned int nextFrameTime = currentTime + mDefaultFrameDurationMilliseconds;
+
+ uint64_t noOfFramesSinceLastUpdate = 1;
+ float frameDelta = 0.0f;
+ if( useElapsedTime )
+ {
+ // If using the elapsed time, then calculate frameDelta as a multiple of mDefaultFrameDelta
+ noOfFramesSinceLastUpdate += extraFramesDropped;
+
+ frameDelta = mDefaultFrameDelta * noOfFramesSinceLastUpdate;
+ }
+ LOG_UPDATE_RENDER( "timeSinceLastFrame(%llu) noOfFramesSinceLastUpdate(%u) frameDelta(%.6f)", timeSinceLastFrame, noOfFramesSinceLastUpdate, frameDelta );
+
+ Integration::UpdateStatus updateStatus;
+
+ AddPerformanceMarker( PerformanceInterface::UPDATE_START );
+ mCore.Update( frameDelta,
+ currentTime,
+ nextFrameTime,
+ updateStatus,
+ renderToFboEnabled,
+ isRenderingToFbo );
+ AddPerformanceMarker( PerformanceInterface::UPDATE_END );
+
+ unsigned int keepUpdatingStatus = updateStatus.KeepUpdating();
+
+ // Tell the event-thread to wake up (if asleep) and send a notification event to Core if required
+ if( updateStatus.NeedsNotification() )
+ {
+ mNotificationTrigger.Trigger();
+ LOG_UPDATE_RENDER( "Notification Triggered" );
+ }
+
+ // Optional logging of update/render status
+ mUpdateStatusLogger.Log( keepUpdatingStatus );
+
+ //////////////////////////////
+ // RENDER
+ //////////////////////////////
+
+ mRenderHelper.ConsumeEvents();
+ mRenderHelper.PreRender();
+
+ Integration::RenderStatus renderStatus;
+
+ AddPerformanceMarker( PerformanceInterface::RENDER_START );
+ mCore.Render( renderStatus );
+ AddPerformanceMarker( PerformanceInterface::RENDER_END );
+
+ if( renderStatus.NeedsPostRender() )
+ {
+ mRenderHelper.PostRender( isRenderingToFbo );
+ }
+
+ // Trigger event thread to request Update/Render thread to sleep if update not required
+ if( ( Integration::KeepUpdating::NOT_REQUESTED == keepUpdatingStatus ) &&
+ ! renderStatus.NeedsUpdate() )
+ {
+ mSleepTrigger->Trigger();
+ updateRequired = false;
+ LOG_UPDATE_RENDER( "Sleep Triggered" );
+ }
+ else
+ {
+ updateRequired = true;
+ }
+
+ //////////////////////////////
+ // FRAME TIME
+ //////////////////////////////
+
+ extraFramesDropped = 0;
+
+ if (timeToSleepUntil == 0)
+ {
+ // If this is the first frame after the thread is initialized or resumed, we
+ // use the actual time the current frame starts from to calculate the time to
+ // sleep until the next frame.
+ timeToSleepUntil = currentFrameStartTime + mDefaultFrameDurationNanoseconds;
+ }
+ else
+ {
+ // Otherwise, always use the sleep-until time calculated in the last frame to
+ // calculate the time to sleep until the next frame. In this way, if there is
+ // any time gap between the current frame and the next frame, or if update or
+ // rendering in the current frame takes too much time so that the specified
+ // sleep-until time has already passed, it will try to keep the frames syncing
+ // by shortening the duration of the next frame.
+ timeToSleepUntil += mDefaultFrameDurationNanoseconds;
+
+ // Check the current time at the end of the frame
+ uint64_t currentFrameEndTime = 0;
+ TimeService::GetNanoseconds( currentFrameEndTime );
+ while ( currentFrameEndTime > timeToSleepUntil + mDefaultFrameDurationNanoseconds )
+ {
+ // We are more than one frame behind already, so just drop the next frames
+ // until the sleep-until time is later than the current time so that we can
+ // catch up.
+ timeToSleepUntil += mDefaultFrameDurationNanoseconds;
+ extraFramesDropped++;
+ }
+ }
+
+ // Render to FBO is intended to measure fps above 60 so sleep is not wanted.
+ if( 0u == renderToFboInterval )
+ {
+ // Sleep until at least the the default frame duration has elapsed. This will return immediately if the specified end-time has already passed.
+ TimeService::SleepUntil( timeToSleepUntil );
+ }
+ }
+
+ // Inform core of context destruction & shutdown EGL
+ mCore.ContextDestroyed();
+ mRenderHelper.ShutdownEgl();
+
+ LOG_UPDATE_RENDER( "THREAD DESTROYED" );
+
+ // Uninstall the logging function
+ mEnvironmentOptions.UnInstallLogFunction();
+}
+
+bool CombinedUpdateRenderController::UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil )
+{
+ useElapsedTime = true;
+
+ ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
+ while( ( ! mUpdateRenderRunCount || // Should try to wait if event-thread has paused the Update/Render thread
+ ( mUpdateRenderThreadCanSleep && ! updateRequired && ! mPendingRequestUpdate ) ) && // Ensure we wait if we're supposed to be sleeping AND do not require another update
+ ! mDestroyUpdateRenderThread && // Ensure we don't wait if the update-render-thread is supposed to be destroyed
+ ! mNewSurface && // Ensure we don't wait if we need to replace the surface
+ ! mSurfaceResized ) // Ensure we don't wait if we need to resize the surface
+ {
+ LOG_UPDATE_RENDER( "WAIT: mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
+ LOG_UPDATE_RENDER( " mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
+ LOG_UPDATE_RENDER( " mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
+ LOG_UPDATE_RENDER( " mNewSurface: %d", mNewSurface );
+ LOG_UPDATE_RENDER( " mSurfaceResized: %d", mSurfaceResized );
+
+ // Reset the time when the thread is waiting, so the sleep-until time for
+ // the first frame after resuming should be based on the actual start time
+ // of the first frame.
+ timeToSleepUntil = 0;
+
+ mUpdateRenderThreadWaitCondition.Wait( updateLock );
+
+ if( ! mUseElapsedTimeAfterWait )
+ {
+ useElapsedTime = false;
+ }
+ }
+
+ LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
+ LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
+ LOG_COUNTER_UPDATE_RENDER( "mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
+ LOG_COUNTER_UPDATE_RENDER( "mNewSurface: %d", mNewSurface );
+ LOG_COUNTER_UPDATE_RENDER( "mSurfaceResized: %d", mSurfaceResized );
+
+ mUseElapsedTimeAfterWait = FALSE;
+ mUpdateRenderThreadCanSleep = FALSE;
+ mPendingRequestUpdate = FALSE;
+
+ // If we've been asked to run Update/Render cycles a finite number of times then decrement so we wait after the
+ // requested number of cycles
+ if( mUpdateRenderRunCount > 0 )
+ {
+ --mUpdateRenderRunCount;
+ }
+
+ // Keep the update-render thread alive if this thread is NOT to be destroyed
+ return ! mDestroyUpdateRenderThread;
+}
+
+RenderSurface* CombinedUpdateRenderController::ShouldSurfaceBeReplaced()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+
+ RenderSurface* newSurface = mNewSurface;
+ mNewSurface = NULL;
+
+ return newSurface;
+}
+
+void CombinedUpdateRenderController::SurfaceReplaced()
+{
+ // Just increment the semaphore
+ sem_post( &mEventThreadSemaphore );
+}
+
+bool CombinedUpdateRenderController::ShouldSurfaceBeResized()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+
+ bool surfaceSized = mSurfaceResized;
+ mSurfaceResized = FALSE;
+
+ return surfaceSized;
+}
+
+void CombinedUpdateRenderController::SurfaceResized()
+{
+ // Just increment the semaphore
+ sem_post( &mEventThreadSemaphore );
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// ALL THREADS
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void CombinedUpdateRenderController::NotifyThreadInitialised()
+{
+ // Just increment the semaphore
+ sem_post( &mEventThreadSemaphore );
+}
+
+void CombinedUpdateRenderController::AddPerformanceMarker( PerformanceInterface::MarkerType type )
+{
+ if( mPerformanceInterface )
+ {
+ mPerformanceInterface->AddMarker( type );
+ }
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////////////
+// POST RENDERING: EVENT THREAD
+/////////////////////////////////////////////////////////////////////////////////////////////////
+
+void CombinedUpdateRenderController::PostRenderComplete()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mPostRendering = FALSE;
+ mUpdateRenderThreadWaitCondition.Notify( lock );
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// POST RENDERING: RENDER THREAD
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+void CombinedUpdateRenderController::PostRenderStarted()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ mPostRendering = TRUE;
+}
+
+void CombinedUpdateRenderController::PostRenderWaitForCompletion()
+{
+ ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
+ while( mPostRendering &&
+ ! mNewSurface && // We should NOT wait if we're replacing the surface
+ ! mSurfaceResized && // We should NOT wait if we're resizing the surface
+ ! mDestroyUpdateRenderThread )
+ {
+ mUpdateRenderThreadWaitCondition.Wait( lock );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
+#define __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <semaphore.h>
+#include <stdint.h>
+#include <dali/integration-api/core.h>
+#include <dali/devel-api/threading/conditional-wait.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/thread-synchronization-interface.h>
+#include <dali/internal/system/common/performance-interface.h>
+#include <dali/internal/system/common/fps-tracker.h>
+#include <dali/internal/graphics/common/render-helper.h>
+#include <dali/internal/adaptor/common/thread-controller-interface.h>
+#include <dali/internal/system/common/update-status-logger.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class TriggerEventInterface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class AdaptorInternalServices;
+class EnvironmentOptions;
+
+/**
+ * @brief Two threads where events/application interaction is handled on the main/event thread and the Update & Render
+ * happen on the other thread.
+ *
+ * Key Points:
+ * 1. Two Threads:
+ * a. Main/Event Thread.
+ * b. Update/Render Thread.
+ * 2. There is NO VSync thread:
+ * a. We retrieve the time before Update.
+ * b. Then retrieve the time after Render.
+ * c. We calculate the difference between these two times and if:
+ * i. The difference is less than the default frame time, we sleep.
+ * ii. If it’s more or the same, we continue.
+ * 3. On the update/render thread, if we discover that we do not need to do any more updates, we use a trigger-event
+ * to inform the main/event thread. This is then processed as soon as the event thread is able to do so where it
+ * is easier to make a decision about whether we should stop the update/render thread or not (depending on any
+ * update requests etc.).
+ * 4. The main thread is blocked while the surface is being replaced.
+ * 5. When we resume from paused, elapsed time is used for the animations, i.e. the could have finished while we were paused.
+ * However, FinishedSignal emission will only happen upon resumption.
+ * 6. Elapsed time is NOT used while if we are waking up from a sleep state or doing an UpdateOnce.
+ */
+class CombinedUpdateRenderController : public ThreadControllerInterface,
+ public ThreadSynchronizationInterface
+{
+public:
+
+ /**
+ * Constructor
+ */
+ CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions );
+
+ /**
+ * Non virtual destructor. Not intended as base class.
+ */
+ ~CombinedUpdateRenderController();
+
+ /**
+ * @copydoc ThreadControllerInterface::Initialize()
+ */
+ virtual void Initialize();
+
+ /**
+ * @copydoc ThreadControllerInterface::Start()
+ */
+ virtual void Start();
+
+ /**
+ * @copydoc ThreadControllerInterface::Pause()
+ */
+ virtual void Pause();
+
+ /**
+ * @copydoc ThreadControllerInterface::Resume()
+ */
+ virtual void Resume();
+
+ /**
+ * @copydoc ThreadControllerInterface::Stop()
+ */
+ virtual void Stop();
+
+ /**
+ * @copydoc ThreadControllerInterface::RequestUpdate()
+ */
+ virtual void RequestUpdate();
+
+ /**
+ * @copydoc ThreadControllerInterface::RequestUpdateOnce()
+ */
+ virtual void RequestUpdateOnce();
+
+ /**
+ * @copydoc ThreadControllerInterface::ReplaceSurface()
+ */
+ virtual void ReplaceSurface( RenderSurface* surface );
+
+ /**
+ * @copydoc ThreadControllerInterface::ResizeSurface()
+ */
+ virtual void ResizeSurface();
+
+ /**
+ * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
+ */
+ virtual void SetRenderRefreshRate( unsigned int numberOfFramesPerRender );
+
+private:
+
+ // Undefined copy constructor.
+ CombinedUpdateRenderController( const CombinedUpdateRenderController& );
+
+ // Undefined assignment operator.
+ CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& );
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // EventThread
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Runs the Update/Render Thread.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ *
+ * @param[in] numberOfCycles The number of times the update/render cycle should run. If -1, then it will run continuously.
+ * @param[in] useElapsedTimeAfterWait If true, then the elapsed time during wait is used for animations, otherwise no animation progression is made.
+ */
+ inline void RunUpdateRenderThread( int numberOfCycles, bool useElapsedTimeAfterWait );
+
+ /**
+ * Pauses the Update/Render Thread.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ */
+ inline void PauseUpdateRenderThread();
+
+ /**
+ * Stops the Update/Render Thread.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ *
+ * @note Should only be called in Stop as calling this will kill the update-thread.
+ */
+ inline void StopUpdateRenderThread();
+
+ /**
+ * Checks if the the Update/Render Thread is paused.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ *
+ * @return true if paused, false otherwise
+ */
+ inline bool IsUpdateRenderThreadPaused();
+
+ /**
+ * Used as the callback for the sleep-trigger.
+ *
+ * Will sleep when enough requests are made without any requests.
+ */
+ void ProcessSleepRequest();
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // UpdateRenderThread
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * The Update/Render thread loop. This thread will be destroyed on exit from this function.
+ */
+ void UpdateRenderThread();
+
+ /**
+ * Called by the Update/Render Thread which ensures a wait if required.
+ *
+ * @param[out] useElapsedTime If true when returned, then the actual elapsed time will be used for animation.
+ * If false when returned, then there should NOT be any animation progression in the next Update.
+ * @param[in] updateRequired Whether another update is required.
+ * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming.
+ * @return false, if the thread should stop.
+ */
+ bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil );
+
+ /**
+ * Checks to see if the surface needs to be replaced.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ *
+ * @return Pointer to the new surface, NULL otherwise
+ */
+ RenderSurface* ShouldSurfaceBeReplaced();
+
+ /**
+ * Called by the Update/Render thread after a surface has been replaced.
+ *
+ * This will lock the mutex in mEventThreadWaitCondition
+ */
+ void SurfaceReplaced();
+
+ /**
+ * Checks to see if the surface needs to be resized.
+ * This will lock the mutex in mUpdateRenderThreadWaitCondition.
+ *
+ * @return true if the surface should be resized, false otherwise
+ */
+ bool ShouldSurfaceBeResized();
+
+ /**
+ * Called by the Update/Render thread after a surface has been resized.
+ *
+ * This will lock the mutex in mEventThreadWaitCondition
+ */
+ void SurfaceResized();
+
+ /**
+ * Helper for the thread calling the entry function
+ * @param[in] This A pointer to the current object
+ */
+ static void* InternalUpdateRenderThreadEntryFunc( void* This )
+ {
+ ( static_cast<CombinedUpdateRenderController*>( This ) )->UpdateRenderThread();
+ return NULL;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // ALL Threads
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called by the update-render & v-sync threads when they up and running.
+ *
+ * This will lock the mutex in mEventThreadWaitCondition.
+ */
+ void NotifyThreadInitialised();
+
+ /**
+ * Helper to add a performance marker to the performance server (if it's active)
+ * @param[in] type performance marker type
+ */
+ void AddPerformanceMarker( PerformanceInterface::MarkerType type );
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // POST RENDERING - ThreadSynchronizationInterface overrides
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ //// Called by the Event Thread if post-rendering is required
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
+ */
+ virtual void PostRenderComplete();
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ //// Called by the Render Thread if post-rendering is required
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
+ */
+ virtual void PostRenderStarted();
+
+ /**
+ * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
+ */
+ virtual void PostRenderWaitForCompletion();
+
+private:
+
+ FpsTracker mFpsTracker; ///< Object that tracks the FPS
+ UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required.
+
+ RenderHelper mRenderHelper; ///< Helper class for EGL, pre & post rendering
+
+ sem_t mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
+
+ ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread.
+
+ AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface
+ PerformanceInterface* mPerformanceInterface; ///< The performance logging interface
+ Integration::Core& mCore; ///< Dali core reference
+ const EnvironmentOptions& mEnvironmentOptions; ///< Environment options
+ TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger
+ TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
+
+ pthread_t* mUpdateRenderThread; ///< The Update/Render thread.
+
+ float mDefaultFrameDelta; ///< Default time delta between each frame (used for animations). Not protected by lock, but written to rarely so not worth adding a lock when reading.
+ uint64_t mDefaultFrameDurationMilliseconds; ///< Default duration of a frame (used for predicting the time of the next frame). Not protected by lock, but written to rarely so not worth adding a lock when reading.
+ uint64_t mDefaultFrameDurationNanoseconds; ///< Default duration of a frame (used for sleeping if not enough time elapsed). Not protected by lock, but written to rarely so not worth adding a lock when reading.
+ uint64_t mDefaultHalfFrameNanoseconds; ///< Is half of mDefaultFrameDurationNanoseconds. Using a member variable avoids having to do the calculation every frame. Not protected by lock, but written to rarely so not worth adding a lock when reading.
+
+ unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early.
+ unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running.
+
+ //
+ // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
+ //
+
+ volatile int mUpdateRenderRunCount; ///< The number of times Update/Render cycle should run. If -1, then will run continuously (set by the event-thread, read by v-sync-thread).
+ volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
+ volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
+ volatile unsigned int mPendingRequestUpdate; ///< Is set as soon as an RequestUpdate is made and unset when the next update happens (set by the event-thread and update-render thread, read by the update-render-thread).
+ ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
+
+ volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
+
+ RenderSurface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread).
+
+ volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
+ volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_FRAMEWORK_H__
+#define __DALI_INTERNAL_FRAMEWORK_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/signals/callback.h>
+#ifdef APPCORE_WATCH_AVAILABLE
+#include <dali/public-api/watch/watch-application.h>
+#endif
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/abort-handler.h>
+#include <dali/public-api/adaptor-framework/device-status.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * The Framework class is ideally placed to provide key API required by Applications.
+ *
+ * The class is also used to register callbacks with the TIZEN platform so that
+ * we know when any of the application lifecycle events occur. This includes events
+ * like when our application is to be initialised, terminated, paused, resumed etc.
+ *
+ */
+class Framework
+{
+public:
+
+ enum Type
+ {
+ NORMAL, ///< normal appFramework
+ WATCH, ///< watch appFramework
+ WIDGET ///< widget appFramework
+ };
+
+ /**
+ * Observer class for the framework.
+ */
+ class Observer
+ {
+ public:
+
+ /**
+ * Invoked when the application is to be initialised.
+ */
+ virtual void OnInit() {}
+
+ /**
+ * Invoked when the application is to be terminated.
+ */
+ virtual void OnTerminate() {}
+
+ /**
+ * Invoked when the application is to be paused.
+ */
+ virtual void OnPause() {}
+
+ /**
+ * Invoked when the application is to be resumed.
+ */
+ virtual void OnResume() {}
+
+ /**
+ * Invoked when the application is to be reset.
+ */
+ virtual void OnReset() {}
+
+ /**
+ * Invoked when the AppControl message is received.
+ * @param[in] The bundle data of AppControl message.
+ */
+ virtual void OnAppControl(void *) {}
+
+#ifdef APPCORE_WATCH_AVAILABLE
+ /**
+ * Invoked at every second
+ */
+ virtual void OnTimeTick(WatchTime&) {}
+
+ /**
+ * Invoked at every second in ambient mode
+ */
+ virtual void OnAmbientTick(WatchTime&) {}
+
+ /**
+ * Invoked when the device enters or exits ambient mode
+ */
+ virtual void OnAmbientChanged(bool ambient) {}
+#endif
+
+ /**
+ * Invoked when the language of the device is changed.
+ */
+ virtual void OnLanguageChanged() {}
+
+ /**
+ * Invoked when the region is changed.
+ */
+ virtual void OnRegionChanged() {}
+
+ /**
+ * Invoked when the battery level of the device is low.
+ */
+ virtual void OnBatteryLow( Dali::DeviceStatus::Battery::Status status ) {}
+
+ /**
+ * Invoked when the memory level of the device is low.
+ */
+ virtual void OnMemoryLow( Dali::DeviceStatus::Memory::Status status ) {}
+ };
+
+public:
+
+ /**
+ * Constructor
+ * @param[in] observer The observer of the Framework.
+ * @param[in] argc A pointer to the number of arguments.
+ * @param[in] argv A pointer the the argument list.
+ * @param[in] type The type of application
+ */
+ Framework( Observer& observer, int* argc, char ***argv, Type type = NORMAL );
+
+ /**
+ * Destructor
+ */
+ ~Framework();
+
+public:
+
+ /**
+ * Runs the main loop of framework
+ */
+ void Run();
+
+ /**
+ * Quits the main loop
+ */
+ void Quit();
+
+ /**
+ * Checks whether the main loop of the framework is running.
+ * @return true, if the main loop is running, false otherwise.
+ */
+ bool IsMainLoopRunning();
+
+ /**
+ * If the main loop aborts unexpectedly, then the connected callback function is called.
+ * @param[in] callBack The function to call.
+ * @note Only one callback can be registered. The last callback to be set will be called on abort.
+ * @note The ownership of callback is passed onto this class.
+ */
+ void AddAbortCallback( CallbackBase* callback );
+
+ /**
+ * Gets bundle name which was passed in app_reset callback.
+ */
+ std::string GetBundleName() const;
+
+ /**
+ * Gets bundle id which was passed in app_reset callback.
+ */
+ std::string GetBundleId() const;
+
+ /**
+ * Gets the path at which application resources are stored.
+ */
+ static std::string GetResourcePath();
+
+ /**
+ * Sets system language.
+ */
+ void SetLanguage( const std::string& language );
+
+ /**
+ * Sets system region.
+ */
+ void SetRegion( const std::string& region );
+
+ /**
+ * Gets system language.
+ */
+ std::string GetLanguage() const;
+
+ /**
+ * Gets system region.
+ */
+ std::string GetRegion() const;
+
+private:
+
+ // Undefined
+ Framework(const Framework&);
+ Framework& operator=(Framework&);
+
+private:
+
+ /**
+ * Called when the application is created.
+ */
+ bool Create();
+
+ /**
+ * Called by the App framework when an application lifecycle event occurs.
+ * @param[in] type The type of event occurred.
+ * @param[in] bundleData The bundle data of event occurred.
+ */
+ bool AppStatusHandler(int type, void *bundleData);
+
+ /**
+ * Called app_reset callback was called with bundle.
+ */
+ void SetBundleName(const std::string& name);
+
+ /**
+ * Called app_reset callback was called with bundle.
+ */
+ void SetBundleId(const std::string& id);
+
+ /**
+ * Called if the application is aborted.
+ */
+ void AbortCallback();
+
+ /**
+ * Called for initializing on specified backend. (X11 or Wayland)
+ */
+ void InitThreads();
+
+private:
+ Observer& mObserver;
+ bool mInitialised;
+ bool mRunning;
+ int* mArgc;
+ char*** mArgv;
+ std::string mBundleName;
+ std::string mBundleId;
+ AbortHandler mAbortHandler;
+
+private: // impl members
+
+ struct Impl;
+ Impl* mImpl;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_FRAMEWORK_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/lifecycle-controller-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::LifecycleController LifecycleController::Get()
+{
+ Dali::LifecycleController lifecycleController;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::LifecycleController ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ lifecycleController = Dali::LifecycleController( dynamic_cast< LifecycleController* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ lifecycleController = Dali::LifecycleController( new LifecycleController() );
+ service.Register( typeid( lifecycleController ), lifecycleController );
+ }
+ }
+
+ return lifecycleController;
+}
+
+LifecycleController::LifecycleController()
+{
+}
+
+LifecycleController::~LifecycleController()
+{
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::InitSignal()
+{
+ return mInitSignal;
+}
+
+void LifecycleController::EmitInitSignal()
+{
+ if( !mInitSignal.Empty() )
+ {
+ mInitSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::TerminateSignal()
+{
+ return mTerminateSignal;
+}
+
+void LifecycleController::EmitTerminateSignal()
+{
+ if( !mTerminateSignal.Empty() )
+ {
+ mTerminateSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::PauseSignal()
+{
+ return mPauseSignal;
+}
+
+void LifecycleController::EmitPauseSignal()
+{
+ if( !mPauseSignal.Empty() )
+ {
+ mPauseSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResumeSignal()
+{
+ return mResumeSignal;
+}
+
+void LifecycleController::EmitResumeSignal()
+{
+ if( !mResumeSignal.Empty() )
+ {
+ mResumeSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResetSignal()
+{
+ return mResetSignal;
+}
+
+void LifecycleController::EmitResetSignal()
+{
+ if( !mResetSignal.Empty() )
+ {
+ mResetSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResizeSignal()
+{
+ return mResizeSignal;
+}
+
+void LifecycleController::EmitResizeSignal()
+{
+ if( !mResizeSignal.Empty() )
+ {
+ mResizeSignal.Emit();
+ }
+}
+
+Dali::LifecycleController::LifecycleSignalType& LifecycleController::LanguageChangedSignal()
+{
+ return mLanguageChangedSignal;
+}
+
+void LifecycleController::EmitLanguageChangedSignal()
+{
+ if( !mLanguageChangedSignal.Empty() )
+ {
+ mLanguageChangedSignal.Emit();
+ }
+}
+
+void LifecycleController::OnInit( Dali::Application& app )
+{
+ EmitInitSignal();
+}
+
+void LifecycleController::OnTerminate( Dali::Application& app )
+{
+ EmitTerminateSignal();
+}
+
+void LifecycleController::OnPause( Dali::Application& app )
+{
+ EmitPauseSignal();
+}
+
+void LifecycleController::OnResume( Dali::Application& app )
+{
+ EmitResumeSignal();
+}
+
+void LifecycleController::OnReset( Dali::Application& app )
+{
+ EmitResetSignal();
+}
+
+void LifecycleController::OnLanguageChanged( Dali::Application& app )
+{
+ EmitLanguageChangedSignal();
+}
+
+void LifecycleController::OnResize( Dali::Application& app )
+{
+ EmitResizeSignal();
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
+#define __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/lifecycle-controller.h>
+#include <dali/public-api/adaptor-framework/application.h>
+
+namespace Dali
+{
+
+class Adaptor;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * This provides signals that are emitted according the lifecylce of the program.
+ */
+class LifecycleController : public BaseObject, public ConnectionTracker
+{
+public:
+
+ // Creation & Destruction
+
+ /**
+ * Constructor.
+ */
+ LifecycleController();
+
+ /**
+ * Retrieve the initialized instance of the LifecycleController.
+ * @return Handle to LifecycleController.
+ */
+ static Dali::LifecycleController Get();
+
+ // Signals
+
+ /**
+ * @copydoc Dali::StyleMonitor::InitSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& InitSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::TerminateSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& TerminateSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::PauseSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& PauseSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::ResumeSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& ResumeSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::ResetSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& ResetSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::ResizeSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& ResizeSignal();
+
+ /**
+ * @copydoc Dali::StyleMonitor::LanguageChangedSignal()
+ */
+ Dali::LifecycleController::LifecycleSignalType& LanguageChangedSignal();
+
+public:
+
+ /**
+ * Called when the framework is initialised.
+ *
+ * @param[in] app The application instance
+ */
+ void OnInit( Dali::Application& app );
+
+ /**
+ * Called when the framework is terminated.
+ *
+ * @param[in] app The application instance
+ */
+ void OnTerminate( Dali::Application& app );
+
+ /**
+ * Called when the framework is paused.
+ *
+ * @param[in] app The application instance
+ */
+ void OnPause( Dali::Application& app );
+
+ /**
+ * Called when the framework resumes from a paused state.
+ *
+ * @param[in] app The application instance
+ */
+ void OnResume( Dali::Application& app );
+
+ /**
+ * Called when the framework informs the application that it should reset itself.
+ *
+ * @param[in] app The application instance
+ */
+ void OnReset( Dali::Application& app );
+
+ /**
+ * Called when the framework informs the application that the language of the device has changed.
+ *
+ * @param[in] app The application instance
+ */
+ void OnLanguageChanged( Dali::Application& app );
+
+ /**
+ * Signal handler when the adaptor's window resizes itself.
+ *
+ * @param[in] app The application instance
+ */
+ void OnResize( Dali::Application& app );
+
+protected:
+
+ /**
+ * Virtual Destructor.
+ */
+ virtual ~LifecycleController();
+
+private:
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitInitSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitTerminateSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitPauseSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitResumeSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitResetSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitResizeSignal();
+
+ /**
+ * Emit the init signal.
+ */
+ void EmitLanguageChangedSignal();
+
+private:
+
+ // Signals
+ Dali::LifecycleController::LifecycleSignalType mInitSignal;
+ Dali::LifecycleController::LifecycleSignalType mTerminateSignal;
+ Dali::LifecycleController::LifecycleSignalType mPauseSignal;
+ Dali::LifecycleController::LifecycleSignalType mResumeSignal;
+ Dali::LifecycleController::LifecycleSignalType mResetSignal;
+ Dali::LifecycleController::LifecycleSignalType mResizeSignal;
+ Dali::LifecycleController::LifecycleSignalType mLanguageChangedSignal;
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Additional Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::LifecycleController& GetImplementation(Dali::LifecycleController& controller)
+{
+ DALI_ASSERT_ALWAYS(controller && "Controller handle is empty");
+ BaseObject& handle = controller.GetBaseObject();
+ return static_cast<Internal::Adaptor::LifecycleController&>(handle);
+}
+
+inline const Internal::Adaptor::LifecycleController& GetImplementation(const Dali::LifecycleController& controller)
+{
+ DALI_ASSERT_ALWAYS(controller && "Controller handle is empty");
+ const BaseObject& handle = controller.GetBaseObject();
+ return static_cast<const Internal::Adaptor::LifecycleController&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_LIFECYCLE_CONTROLLER_H__
--- /dev/null
+
+
+# module: adaptor, backend: common
+adaptor_adaptor_common_src_files=\
+ ${adaptor_adaptor_dir}/common/lifecycle-controller-impl.cpp \
+ ${adaptor_adaptor_dir}/common/adaptor-impl.cpp \
+ ${adaptor_adaptor_dir}/common/adaptor.cpp \
+ ${adaptor_adaptor_dir}/common/application-impl.cpp \
+ ${adaptor_adaptor_dir}/common/combined-update-render-controller.cpp
+
+# module: adaptor, backend: tizen
+adaptor_adaptor_tizen_src_files=\
+ ${adaptor_adaptor_dir}/tizen/adaptor-impl-tizen.cpp \
+ ${adaptor_adaptor_dir}/tizen/framework-tizen.cpp
+
+# module: adaptor, backend: tizen-wearable
+adaptor_adaptor_tizen_wearable_src_files=\
+ ${adaptor_adaptor_dir}/tizen-wearable/watch-application.cpp \
+ ${adaptor_adaptor_dir}/tizen-wearable/watch-application-impl.cpp
+
+# module: adaptor, backend: ubuntu
+adaptor_adaptor_ubuntu_src_files=\
+ ${adaptor_adaptor_dir}/ubuntu/adaptor-impl-ubuntu.cpp \
+ ${adaptor_adaptor_dir}/ubuntu/framework-ubuntu.cpp
+
+# module: adaptor, backend: tizen-wayland
+adaptor_adaptor_tizen_wayland_src_files=\
+ ${adaptor_adaptor_dir}/tizen-wayland/framework-ecore-wl.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/framework.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+void Framework::InitThreads()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/tizen-wearable/watch-application-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+WatchApplicationPtr WatchApplication::New(
+ int* argc,
+ char **argv[],
+ const std::string& stylesheet,
+ Dali::WatchApplication::WINDOW_MODE windowMode)
+{
+ WatchApplicationPtr watch ( new WatchApplication (argc, argv, stylesheet, windowMode ) );
+ return watch;
+}
+
+WatchApplication::WatchApplication( int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode )
+: Application(argc, argv, stylesheet, windowMode, PositionSize(), Framework::WATCH)
+{
+}
+
+WatchApplication::~WatchApplication()
+{
+}
+
+void WatchApplication::OnInit()
+{
+ Application::OnInit();
+
+ Dali::Adaptor::Get().SetRenderRefreshRate( 2 ); // make 30 fps for watch applications
+
+ mState = INITIALIZED;
+}
+
+void WatchApplication::OnTerminate()
+{
+ Application::OnTerminate();
+
+ mState = TERMINATED;
+}
+
+void WatchApplication::OnResume()
+{
+ Application::OnResume();
+
+ mState = RESUMED;
+}
+
+void WatchApplication::OnPause()
+{
+ Application::OnPause();
+
+ mState = PAUSED;
+}
+
+void WatchApplication::OnTimeTick(WatchTime& time)
+{
+ Dali::WatchApplication watch(this);
+ mTickSignal.Emit( watch, time );
+
+ if(mState == PAUSED)
+ {
+ // This is a pre-resume scenario. All rendering engine of tizen SHOULD forcely update once at this time.
+ Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() ).RequestUpdateOnce();
+ }
+
+ // A watch application will queue messages to update the UI in the signal emitted above
+ // Process these immediately to avoid a blinking issue where the old time is briefly visible
+ CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() );
+ eventInterface.ProcessCoreEvents();
+}
+
+void WatchApplication::OnAmbientTick(WatchTime& time)
+{
+ Dali::WatchApplication watch(this);
+ mAmbientTickSignal.Emit( watch, time );
+
+ // A watch application will queue messages to update the UI in the signal emitted above
+ // Process these immediately to avoid a blinking issue where the old time is briefly visible
+ CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() );
+ eventInterface.ProcessCoreEvents();
+}
+
+void WatchApplication::OnAmbientChanged(bool ambient)
+{
+ Dali::WatchApplication watch(this);
+ mAmbientChangeSignal.Emit( watch, ambient );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_WATCH_APPLICATION_H__
+#define __DALI_INTERNAL_WATCH_APPLICATION_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/watch/watch-application.h>
+#include <dali/internal/adaptor/common/application-impl.h>
+
+namespace Dali
+{
+class Adaptor;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class WatchApplication;
+typedef IntrusivePtr<WatchApplication> WatchApplicationPtr;
+
+enum WatchApplicationState
+{
+ INITIALIZED,
+ PAUSED,
+ RESUMED = INITIALIZED,
+ TERMINATED
+};
+
+/**
+ * Implementation of the WatchApplication class.
+ */
+class WatchApplication : public Application
+{
+public:
+ typedef Dali::WatchApplication::WatchTimeSignal WatchTimeSignal;
+ typedef Dali::WatchApplication::WatchBoolSignal WatchBoolSignal;
+
+ /**
+ * Create a new watch
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE
+ */
+ static WatchApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
+
+ /**
+ * Private Constructor
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE
+ */
+ WatchApplication( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
+
+ /**
+ * Destructor
+ */
+ virtual ~WatchApplication();
+
+ /**
+ * Called when the framework is initialised.
+ */
+ virtual void OnInit();
+
+ /**
+ * Called when the framework is terminated.
+ */
+ virtual void OnTerminate();
+
+ /**
+ * Called when the framework is paused.
+ */
+ virtual void OnPause();
+
+ /**
+ * Called when the framework resumes from a paused state.
+ */
+ virtual void OnResume();
+
+ /**
+ * Called every second
+ */
+ void OnTimeTick(WatchTime& time);
+
+ /**
+ * Called every second in ambient mode
+ */
+ void OnAmbientTick(WatchTime& time);
+
+ /**
+ * Called when the device enters or exits ambient mode
+ */
+ void OnAmbientChanged(bool ambient);
+
+private:
+
+ // @brief Undefined copy constructor.
+ WatchApplication( const WatchApplication& );
+
+ // @brief Undefined assignment operator.
+ WatchApplication& operator=( const WatchApplication& );
+
+public:
+
+ // Signals
+ WatchTimeSignal mTickSignal;
+ WatchTimeSignal mAmbientTickSignal;
+ WatchBoolSignal mAmbientChangeSignal;
+
+private:
+ WatchApplicationState mState;
+};
+
+inline WatchApplication& GetImplementation(Dali::WatchApplication& watch)
+{
+ DALI_ASSERT_ALWAYS(watch && "watch handle is empty");
+
+ BaseObject& handle = watch.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::WatchApplication&>(handle);
+}
+
+inline const WatchApplication& GetImplementation(const Dali::WatchApplication& watch)
+{
+ DALI_ASSERT_ALWAYS(watch && "Time handle is empty");
+
+ const BaseObject& handle = watch.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::WatchApplication&>(handle);
+}
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_WATCH_APPLICATION_H__
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/watch/watch-application.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/tizen-wearable/watch-application-impl.h>
+
+namespace Dali
+{
+
+WatchApplication WatchApplication::New()
+{
+ return New( NULL, NULL );
+}
+
+WatchApplication WatchApplication::New( int* argc, char **argv[] )
+{
+ Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, "", OPAQUE );
+ return WatchApplication(internal.Get());
+}
+
+WatchApplication WatchApplication::New( int* argc, char **argv[], const std::string& stylesheet )
+{
+ Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, stylesheet, OPAQUE );
+ return WatchApplication(internal.Get());
+}
+
+WatchApplication::~WatchApplication()
+{
+}
+
+WatchApplication::WatchApplication()
+{
+}
+
+WatchApplication::WatchApplication(const WatchApplication& implementation)
+: Application(implementation)
+{
+}
+
+WatchApplication& WatchApplication::operator=(const WatchApplication& application)
+{
+ if( *this != application )
+ {
+ BaseHandle::operator=( application );
+ }
+ return *this;
+}
+
+WatchApplication::WatchTimeSignal& WatchApplication::TimeTickSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).mTickSignal;
+}
+
+WatchApplication::WatchTimeSignal& WatchApplication::AmbientTickSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).mAmbientTickSignal;
+}
+
+WatchApplication::WatchBoolSignal& WatchApplication::AmbientChangedSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).mAmbientChangeSignal;
+}
+
+WatchApplication::WatchApplication(Internal::Adaptor::WatchApplication* implementation)
+: Application(implementation)
+{
+}
+
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <app_common.h>
+#ifdef APPCORE_WATCH_AVAILABLE
+#include <screen_connector_provider.h>
+#include <dali/integration-api/wayland/ecore-wl-render-surface.h>
+#endif
+
+#include <system_settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+static void OnSystemLanguageChanged( system_settings_key_e key, void* data )
+{
+ char* locale = NULL;
+ if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE ||
+ locale == NULL )
+ {
+ DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " );
+ return;
+ }
+
+ Adaptor* adaptor = static_cast< Adaptor* >( data );
+ if( adaptor != NULL )
+ {
+ adaptor->SetRootLayoutDirection( locale );
+ }
+
+ free( locale );
+}
+
+} // namesapce
+
+void Adaptor::GetDataStoragePath( std::string& path)
+{
+#ifdef USE_APPFW
+ char *pathInt = app_get_data_path();
+ if ( pathInt )
+ {
+ path = pathInt;
+ free( pathInt );
+ }
+ else
+ {
+ path = "";
+ }
+#endif
+
+}
+
+void Adaptor::GetAppId( std::string& appId )
+{
+#ifdef USE_APPFW
+ char *id;
+ app_get_id(&id);
+ if ( id )
+ {
+ appId = id;
+ }
+ else
+ {
+ appId = "";
+ }
+#endif
+}
+
+void Adaptor::SurfaceInitialized()
+{
+#ifdef APPCORE_WATCH_AVAILABLE
+ if ( !mUseRemoteSurface )
+ {
+ return;
+ }
+ char *appId;
+ app_get_id(&appId);
+
+ Ecore_Wl_Window* ecoreWlWindow = AnyCast<Ecore_Wl_Window*>( mNativeWindow );
+ screen_connector_provider_remote_enable(appId, ecore_wl_window_surface_get(ecoreWlWindow));
+#endif
+}
+
+void Adaptor::SetupSystemInformation()
+{
+ if( system_settings_set_changed_cb( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, OnSystemLanguageChanged, this ) != SYSTEM_SETTINGS_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "DALI system_settings_set_changed_cb failed.\n" );
+ return;
+ }
+
+ char* locale = NULL;
+ if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE ||
+ locale == NULL )
+ {
+ DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " );
+ return;
+ }
+
+ SetRootLayoutDirection( locale );
+
+ free( locale );
+
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/framework.h>
+
+// EXTERNAL INCLUDES
+#include <appcore_ui_base.h>
+#include <app_control_internal.h>
+#include <app_common.h>
+#include <bundle.h>
+#include <Ecore.h>
+
+#include <system_info.h>
+#include <system_settings.h>
+#include <bundle_internal.h>
+#include <widget_base.h>
+// CONDITIONAL INCLUDES
+#ifdef APPCORE_WATCH_AVAILABLE
+#include <appcore-watch/watch_app.h>
+#endif
+#ifdef DALI_ELDBUS_AVAILABLE
+#include <Eldbus.h>
+#endif // DALI_ELDBUS_AVAILABLE
+
+#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
+#include <tzplatform_config.h>
+#endif // TIZEN_PLATFORM_CONFIG_SUPPORTED
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/callback-manager.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Integration::Log::Filter* gDBusLogging = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DBUS" );
+#endif
+
+bool IsWidgetFeatureEnabled()
+{
+ static bool feature = false;
+ static bool retrieved = false;
+ int ret;
+
+ if(retrieved == true)
+ {
+ return feature;
+ }
+
+ ret = system_info_get_platform_bool("http://tizen.org/feature/shell.appwidget", &feature);
+ if(ret != SYSTEM_INFO_ERROR_NONE)
+ {
+ DALI_LOG_ERROR("failed to get system info");
+ return false;
+ }
+
+ retrieved = true;
+ return feature;
+}
+
+} // anonymous namespace
+
+namespace AppCore
+{
+
+typedef enum
+{
+ LOW_MEMORY, //< The low memory event
+ LOW_BATTERY, //< The low battery event
+ LANGUAGE_CHANGED, //< The system language changed event
+ DEVICE_ORIENTATION_CHANGED, //< The device orientation changed event
+ REGION_FORMAT_CHANGED, //< The region format changed event
+ SUSPENDED_STATE_CHANGED, //< The suspended state changed event of the application
+ UPDATE_REQUESTED, //< The update requested event. This event can occur when an app needs to be updated. It is dependent on target devices.
+} AppEventType;
+
+static int AppEventConverter[APPCORE_BASE_EVENT_MAX] =
+{
+ [LOW_MEMORY] = APPCORE_BASE_EVENT_LOW_MEMORY,
+ [LOW_BATTERY] = APPCORE_BASE_EVENT_LOW_BATTERY,
+ [LANGUAGE_CHANGED] = APPCORE_BASE_EVENT_LANG_CHANGE,
+ [DEVICE_ORIENTATION_CHANGED] = APPCORE_BASE_EVENT_DEVICE_ORIENTATION_CHANGED,
+ [REGION_FORMAT_CHANGED] = APPCORE_BASE_EVENT_REGION_CHANGE,
+ [SUSPENDED_STATE_CHANGED] = APPCORE_BASE_EVENT_SUSPENDED_STATE_CHANGE,
+};
+
+struct AppEventInfo
+{
+ AppEventType type;
+ void *value;
+};
+
+typedef struct AppEventInfo *AppEventInfoPtr;
+
+typedef void (*AppEventCallback)(AppEventInfoPtr eventInfo, void *userData);
+
+struct AppEventHandler
+{
+ AppEventType type;
+ AppEventCallback cb;
+ void *data;
+ void *raw;
+};
+
+typedef struct AppEventHandler *AppEventHandlerPtr;
+
+int EventCallback(void *event, void *data)
+{
+ AppEventHandlerPtr handler = static_cast<AppEventHandlerPtr>(data);
+
+ struct AppEventInfo appEvent;
+
+ appEvent.type = handler->type;
+ appEvent.value = event;
+
+ if (handler->cb)
+ handler->cb(&appEvent, handler->data);
+
+ return 0;
+}
+
+int AppAddEventHandler(AppEventHandlerPtr *eventHandler, AppEventType eventType, AppEventCallback callback, void *userData)
+{
+ AppEventHandlerPtr handler;
+
+ handler = static_cast<AppEventHandlerPtr>( calloc(1, sizeof(struct AppEventHandler)) );
+ if (!handler)
+ {
+ DALI_LOG_ERROR( "failed to create handler" );
+ return TIZEN_ERROR_UNKNOWN;
+ }
+ else
+ {
+ handler->type = eventType;
+ handler->cb = callback;
+ handler->data = userData;
+ handler->raw = appcore_base_add_event( static_cast<appcore_base_event>(AppEventConverter[static_cast<int>(eventType)]), EventCallback, handler);
+
+ *eventHandler = handler;
+
+ return TIZEN_ERROR_NONE;
+ }
+}
+
+} // namespace Appcore
+
+/**
+ * Impl to hide EFL data members
+ */
+struct Framework::Impl
+{
+// Constructor
+ Impl(void* data, Type type )
+ : mAbortCallBack( NULL ),
+ mCallbackManager( NULL )
+#ifdef APPCORE_WATCH_AVAILABLE
+ , mWatchCallback()
+#endif
+ {
+ mFramework = static_cast<Framework*>(data);
+
+#ifndef APPCORE_WATCH_AVAILABLE
+ if ( type == WATCH )
+ {
+ throw Dali::DaliException( "", "Watch Application is not supported." );
+ }
+#endif
+ mApplicationType = type;
+ mCallbackManager = CallbackManager::New();
+
+ char* region;
+ char* language;
+ system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_COUNTRY, ®ion );
+ system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &language );
+ mRegion = std::string( region );
+ mLanguage = std::string( language );
+ }
+
+ ~Impl()
+ {
+ delete mAbortCallBack;
+
+ // we're quiting the main loop so
+ // mCallbackManager->RemoveAllCallBacks() does not need to be called
+ // to delete our abort handler
+ delete mCallbackManager;
+ }
+
+ int AppMain()
+ {
+ int ret;
+
+ if (mApplicationType == NORMAL)
+ {
+ ret = AppNormalMain();
+ }
+ else if(mApplicationType == WIDGET)
+ {
+ ret = AppWidgetMain();
+ }
+ else
+ {
+ ret = AppWatchMain();
+ }
+ return ret;
+ }
+
+ void AppExit()
+ {
+ if (mApplicationType == NORMAL)
+ {
+ AppNormalExit();
+ }
+ else if(mApplicationType == WIDGET)
+ {
+ AppWidgetExit();
+ }
+ else
+ {
+ AppWatchExit();
+ }
+ }
+
+ void SetLanguage( const std::string& language )
+ {
+ mLanguage = language;
+ }
+
+ void SetRegion( const std::string& region )
+ {
+ mRegion = region;
+ }
+
+ std::string GetLanguage() const
+ {
+ return mLanguage;
+ }
+
+ std::string GetRegion() const
+ {
+ return mRegion;
+ }
+
+ // Data
+ Type mApplicationType;
+ CallbackBase* mAbortCallBack;
+ CallbackManager *mCallbackManager;
+ std::string mLanguage;
+ std::string mRegion;
+
+ Framework* mFramework;
+ AppCore::AppEventHandlerPtr handlers[5];
+#ifdef APPCORE_WATCH_AVAILABLE
+ watch_app_lifecycle_callback_s mWatchCallback;
+ app_event_handler_h watchHandlers[5];
+#endif
+
+ static int AppCreate(void *data)
+ {
+ appcore_ui_base_on_create();
+ return static_cast<int>( static_cast<Framework*>(data)->Create() );
+ }
+
+ static int AppTerminate(void *data)
+ {
+ appcore_ui_base_on_terminate();
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnTerminate();
+
+ return 0;
+ }
+
+ static int AppPause(void *data)
+ {
+ appcore_ui_base_on_pause();
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnPause();
+
+ return 0;
+ }
+
+ static int AppResume(void *data)
+ {
+ appcore_ui_base_on_resume();
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnResume();
+
+ return 0;
+ }
+
+ static void ProcessBundle(Framework* framework, bundle *bundleData)
+ {
+ if(bundleData == NULL)
+ {
+ return;
+ }
+
+ // get bundle name
+ char* bundleName = const_cast<char*>(bundle_get_val(bundleData, "name"));
+ if(bundleName != NULL)
+ {
+ framework->SetBundleName(bundleName);
+ }
+
+ // get bundle? id
+ char* bundleId = const_cast<char*>(bundle_get_val(bundleData, "id"));
+ if(bundleId != NULL)
+ {
+ framework->SetBundleId(bundleId);
+ }
+ }
+
+ /**
+ * Called by AppCore when the application is launched from another module (e.g. homescreen).
+ * @param[in] b the bundle data which the launcher module sent
+ */
+ static int AppControl(bundle* bundleData, void *data)
+ {
+ app_control_h appControl = NULL;
+
+ appcore_ui_base_on_control(bundleData);
+
+ if (bundleData)
+ {
+ if (app_control_create_event(bundleData, &appControl) != TIZEN_ERROR_NONE)
+ {
+ DALI_LOG_ERROR("Failed to create an app_control handle");
+ }
+ }
+ else
+ {
+ if (app_control_create(&appControl) != TIZEN_ERROR_NONE)
+ {
+ DALI_LOG_ERROR("Failed to create an app_control handle");
+ }
+ }
+
+ Framework* framework = static_cast<Framework*>(data);
+ Observer *observer = &framework->mObserver;
+
+ ProcessBundle(framework, bundleData);
+
+ observer->OnReset();
+ observer->OnAppControl(appControl);
+
+ app_control_destroy(appControl);
+
+ return 0;
+ }
+
+ static void AppInit(int argc, char **argv, void *data)
+ {
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+
+ ecore_init();
+ ecore_app_args_set( argc, (const char **)argv );
+
+#pragma GCC diagnostic pop
+ }
+
+ static void AppFinish(void)
+ {
+ ecore_shutdown();
+
+ if(getenv("AUL_LOADER_INIT"))
+ {
+ unsetenv("AUL_LOADER_INIT");
+ ecore_shutdown();
+ }
+ }
+
+ static void AppRun(void *data)
+ {
+ ecore_main_loop_begin();
+ }
+
+ static void AppExit(void *data)
+ {
+ ecore_main_loop_quit();
+ }
+
+ static void AppLanguageChanged(AppCore::AppEventInfoPtr event, void *data)
+ {
+ Framework* framework = static_cast<Framework*>(data);
+ Observer *observer = &framework->mObserver;
+
+ if( event && event->value )
+ {
+ framework->SetLanguage( std::string( static_cast<const char *>(event->value) ) );
+ observer->OnLanguageChanged();
+ }
+ else
+ {
+ DALI_LOG_ERROR( "NULL pointer in Language changed event\n" );
+ }
+ }
+
+ static void AppDeviceRotated(AppCore::AppEventInfoPtr event_info, void *data)
+ {
+ }
+
+ static void AppRegionChanged(AppCore::AppEventInfoPtr event, void *data)
+ {
+ Framework* framework = static_cast<Framework*>(data);
+ Observer *observer = &framework->mObserver;
+
+ if( event && event->value )
+ {
+ framework->SetRegion( std::string( static_cast<const char *>(event->value) ) );
+ observer->OnRegionChanged();
+ }
+ else
+ {
+ DALI_LOG_ERROR( "NULL pointer in Region changed event\n" );
+ }
+ }
+
+ static void AppBatteryLow(AppCore::AppEventInfoPtr event, void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+ int status = *static_cast<int *>(event->value);
+ Dali::DeviceStatus::Battery::Status result = Dali::DeviceStatus::Battery::NORMAL;
+
+ // convert to dali battery status
+ switch( status )
+ {
+ case 1:
+ {
+ result = Dali::DeviceStatus::Battery::POWER_OFF;
+ break;
+ }
+ case 2:
+ {
+ result = Dali::DeviceStatus::Battery::CRITICALLY_LOW;
+ break;
+ }
+ default :
+ break;
+ }
+ observer->OnBatteryLow(result);
+ }
+
+ static void AppMemoryLow(AppCore::AppEventInfoPtr event, void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+ int status = *static_cast<int *>(event->value);
+ Dali::DeviceStatus::Memory::Status result = Dali::DeviceStatus::Memory::NORMAL;
+
+ // convert to dali memmory status
+ switch( status )
+ {
+ case 1:
+ {
+ result = Dali::DeviceStatus::Memory::NORMAL;
+ break;
+ }
+ case 2:
+ {
+ result = Dali::DeviceStatus::Memory::LOW;
+ break;
+ }
+ case 4:
+ {
+ result = Dali::DeviceStatus::Memory::CRITICALLY_LOW;
+ break;
+ }
+ default :
+ break;
+ }
+ observer->OnMemoryLow(result);
+ }
+
+
+ int AppNormalMain()
+ {
+ int ret;
+
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::DEVICE_ORIENTATION_CHANGED], AppCore::DEVICE_ORIENTATION_CHANGED, AppDeviceRotated, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
+
+ appcore_ui_base_ops ops = appcore_ui_base_get_default_ops();
+
+ /* override methods */
+ ops.base.create = AppCreate;
+ ops.base.control = AppControl;
+ ops.base.terminate = AppTerminate;
+ ops.pause = AppPause;
+ ops.resume = AppResume;
+ ops.base.init = AppInit;
+ ops.base.finish = AppFinish;
+ ops.base.run = AppRun;
+ ops.base.exit = AppExit;
+
+ ret = appcore_ui_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework, APPCORE_UI_BASE_HINT_WINDOW_GROUP_CONTROL |
+ APPCORE_UI_BASE_HINT_WINDOW_STACK_CONTROL |
+ APPCORE_UI_BASE_HINT_BG_LAUNCH_CONTROL |
+ APPCORE_UI_BASE_HINT_HW_ACC_CONTROL |
+ APPCORE_UI_BASE_HINT_WINDOW_AUTO_CONTROL );
+
+ if (ret != TIZEN_ERROR_NONE)
+ return ret;
+
+ appcore_ui_base_fini();
+
+ return TIZEN_ERROR_NONE;
+ }
+
+ void AppNormalExit()
+ {
+ appcore_ui_base_exit();
+ }
+
+ void AppWidgetExit()
+ {
+ widget_base_exit();
+ }
+
+ static int WidgetAppCreate( void *data )
+ {
+ widget_base_on_create();
+ return static_cast<int>( static_cast<Framework*>(data)->Create() );
+ }
+
+ static int WidgetAppTerminate( void *data )
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+ observer->OnTerminate();
+
+ widget_base_on_terminate();
+ return 0;
+ }
+
+ int AppWidgetMain()
+ {
+ if( !IsWidgetFeatureEnabled() )
+ {
+ DALI_LOG_ERROR("widget feature is not supported");
+ return 0;
+ }
+
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::DEVICE_ORIENTATION_CHANGED], AppCore::DEVICE_ORIENTATION_CHANGED, AppDeviceRotated, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
+
+ widget_base_ops ops = widget_base_get_default_ops();
+
+ /* override methods */
+ ops.create = WidgetAppCreate;
+ ops.terminate = WidgetAppTerminate;
+ ops.init = AppInit;
+ ops.finish = AppFinish;
+ ops.run = AppRun;
+ ops.exit = AppExit;
+
+ int result = widget_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework);
+
+ widget_base_fini();
+
+ return result;
+ }
+
+#ifdef APPCORE_WATCH_AVAILABLE
+ static bool WatchAppCreate(int width, int height, void *data)
+ {
+ return static_cast<Framework*>(data)->Create();
+ }
+
+ static void WatchAppTimeTick(watch_time_h time, void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+ WatchTime curTime(time);
+
+ observer->OnTimeTick(curTime);
+ }
+
+ static void WatchAppAmbientTick(watch_time_h time, void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+ WatchTime curTime(time);
+
+ observer->OnAmbientTick(curTime);
+ }
+
+ static void WatchAppAmbientChanged(bool ambient, void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnAmbientChanged(ambient);
+ }
+
+ static void WatchAppControl(app_control_h app_control, void *data)
+ {
+ Framework* framework = static_cast<Framework*>(data);
+ Observer *observer = &framework->mObserver;
+ bundle *bundleData = NULL;
+
+ app_control_to_bundle(app_control, &bundleData);
+ ProcessBundle(framework, bundleData);
+
+ observer->OnReset();
+ observer->OnAppControl(app_control);
+ }
+
+ static void WatchAppTerminate(void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnTerminate();
+ }
+
+ static void WatchAppPause(void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnPause();
+ }
+
+ static void WatchAppResume(void *data)
+ {
+ Observer *observer = &static_cast<Framework*>(data)->mObserver;
+
+ observer->OnResume();
+ }
+
+#endif
+
+ int AppWatchMain()
+ {
+ int ret = true;
+
+#ifdef APPCORE_WATCH_AVAILABLE
+ mWatchCallback.create = WatchAppCreate;
+ mWatchCallback.app_control = WatchAppControl;
+ mWatchCallback.terminate = WatchAppTerminate;
+ mWatchCallback.pause = WatchAppPause;
+ mWatchCallback.resume = WatchAppResume;
+ mWatchCallback.time_tick = WatchAppTimeTick;
+ mWatchCallback.ambient_tick = WatchAppAmbientTick;
+ mWatchCallback.ambient_changed = WatchAppAmbientChanged;
+
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LOW_MEMORY], AppCore::LOW_MEMORY, AppMemoryLow, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::LANGUAGE_CHANGED], AppCore::LANGUAGE_CHANGED, AppLanguageChanged, mFramework);
+ AppCore::AppAddEventHandler(&handlers[AppCore::REGION_FORMAT_CHANGED], AppCore::REGION_FORMAT_CHANGED, AppRegionChanged, mFramework);
+
+ ret = watch_app_main(*mFramework->mArgc, *mFramework->mArgv, &mWatchCallback, mFramework);
+#endif
+ return ret;
+ }
+
+ void AppWatchExit()
+ {
+#ifdef APPCORE_WATCH_AVAILABLE
+ watch_app_exit();
+#endif
+ }
+
+private:
+ // Undefined
+ Impl( const Impl& impl );
+
+ // Undefined
+ Impl& operator=( const Impl& impl );
+};
+
+Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
+: mObserver(observer),
+ mInitialised(false),
+ mRunning(false),
+ mArgc(argc),
+ mArgv(argv),
+ mBundleName(""),
+ mBundleId(""),
+ mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
+ mImpl(NULL)
+{
+ bool featureFlag = true;
+ system_info_get_platform_bool( "tizen.org/feature/opengles.version.2_0", &featureFlag );
+
+ if( featureFlag == false )
+ {
+ set_last_result( TIZEN_ERROR_NOT_SUPPORTED );
+ }
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Initialize ElDBus.
+ DALI_LOG_INFO( gDBusLogging, Debug::General, "Starting DBus Initialization\n" );
+ eldbus_init();
+#endif
+ InitThreads();
+
+ mImpl = new Impl(this, type);
+}
+
+Framework::~Framework()
+{
+ if (mRunning)
+ {
+ Quit();
+ }
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Shutdown ELDBus.
+ DALI_LOG_INFO( gDBusLogging, Debug::General, "Shutting down DBus\n" );
+ eldbus_shutdown();
+#endif
+
+ delete mImpl;
+}
+
+bool Framework::Create()
+{
+ mInitialised = true;
+ mObserver.OnInit();
+ return true;
+}
+
+void Framework::Run()
+{
+ mRunning = true;
+ int ret;
+
+ ret = mImpl->AppMain();
+ if (ret != APP_ERROR_NONE)
+ {
+ DALI_LOG_ERROR("Framework::Run(), ui_app_main() is failed. err = %d\n", ret);
+ }
+ mRunning = false;
+}
+
+void Framework::Quit()
+{
+ mImpl->AppExit();
+}
+
+bool Framework::IsMainLoopRunning()
+{
+ return mRunning;
+}
+
+void Framework::AddAbortCallback( CallbackBase* callback )
+{
+ mImpl->mAbortCallBack = callback;
+}
+
+std::string Framework::GetBundleName() const
+{
+ return mBundleName;
+}
+
+void Framework::SetBundleName(const std::string& name)
+{
+ mBundleName = name;
+}
+
+std::string Framework::GetBundleId() const
+{
+ return mBundleId;
+}
+
+std::string Framework::GetResourcePath()
+{
+ std::string resourcePath = "";
+#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED
+ resourcePath = app_get_resource_path();
+#else // For backwards compatibility with older Tizen versions
+
+ // "DALI_APPLICATION_PACKAGE" is used to get the already configured Application package path.
+ const char* environmentVariable = "DALI_APPLICATION_PACKAGE";
+ char* value = getenv( environmentVariable );
+ if ( value != NULL )
+ {
+ resourcePath = value;
+ }
+#endif //TIZEN_PLATFORM_CONFIG_SUPPORTED
+
+ return resourcePath;
+}
+
+void Framework::SetBundleId(const std::string& id)
+{
+ mBundleId = id;
+}
+
+void Framework::AbortCallback( )
+{
+ // if an abort call back has been installed run it.
+ if (mImpl->mAbortCallBack)
+ {
+ CallbackBase::Execute( *mImpl->mAbortCallBack );
+ }
+ else
+ {
+ Quit();
+ }
+}
+
+void Framework::SetLanguage( const std::string& language )
+{
+ mImpl->SetLanguage( language );
+}
+
+void Framework::SetRegion( const std::string& region )
+{
+ mImpl->SetRegion( region );
+}
+
+std::string Framework::GetLanguage() const
+{
+ return mImpl->GetLanguage();
+}
+
+std::string Framework::GetRegion() const
+{
+ return mImpl->GetRegion();
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+void Adaptor::GetDataStoragePath( std::string& path)
+{
+ path = DALI_SHADERBIN_DIR;
+}
+
+void Adaptor::GetAppId( std::string& appId )
+{
+ appId = "";
+}
+
+void Adaptor::SurfaceInitialized()
+{
+}
+
+void Adaptor::SetupSystemInformation()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/adaptor/common/framework.h>
+
+// EXTERNAL INCLUDES
+#include <Ecore.h>
+#include <Elementary.h>
+#include <X11/Xlib.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/callback-manager.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+/// Application Status Enum
+enum
+{
+ APP_CREATE,
+ APP_TERMINATE,
+ APP_PAUSE,
+ APP_RESUME,
+ APP_RESET,
+ APP_LANGUAGE_CHANGE,
+};
+
+} // Unnamed namespace
+
+/**
+ * Impl to hide EFL data members
+ */
+struct Framework::Impl
+{
+ // Constructor
+
+ Impl(void* data)
+ : mAbortCallBack( NULL ),
+ mCallbackManager( CallbackManager::New() ),
+ mLanguage( "NOT_SUPPORTED" ),
+ mRegion( "NOT_SUPPORTED" )
+ {
+ }
+
+ ~Impl()
+ {
+ delete mAbortCallBack;
+
+ // we're quiting the main loop so
+ // mCallbackManager->RemoveAllCallBacks() does not need to be called
+ // to delete our abort handler
+ delete mCallbackManager;
+ }
+
+ std::string GetLanguage() const
+ {
+ return mLanguage;
+ }
+
+ std::string GetRegion() const
+ {
+ return mRegion;
+ }
+
+ // Data
+ CallbackBase* mAbortCallBack;
+ CallbackManager *mCallbackManager;
+ std::string mLanguage;
+ std::string mRegion;
+
+ // Static methods
+
+ /**
+ * Called by AppCore on application creation.
+ */
+ static bool AppCreate(void *data)
+ {
+ return static_cast<Framework*>(data)->AppStatusHandler(APP_CREATE, NULL);
+ }
+
+ /**
+ * Called by AppCore when the application should terminate.
+ */
+ static void AppTerminate(void *data)
+ {
+ static_cast<Framework*>(data)->AppStatusHandler(APP_TERMINATE, NULL);
+ }
+
+ /**
+ * Called by AppCore when the application is paused.
+ */
+ static void AppPause(void *data)
+ {
+ static_cast<Framework*>(data)->AppStatusHandler(APP_PAUSE, NULL);
+ }
+
+ /**
+ * Called by AppCore when the application is resumed.
+ */
+ static void AppResume(void *data)
+ {
+ static_cast<Framework*>(data)->AppStatusHandler(APP_RESUME, NULL);
+ }
+
+ /**
+ * Called by AppCore when the language changes on the device.
+ */
+ static void AppLanguageChange(void* data)
+ {
+ static_cast<Framework*>(data)->AppStatusHandler(APP_LANGUAGE_CHANGE, NULL);
+ }
+
+};
+
+Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
+: mObserver(observer),
+ mInitialised(false),
+ mRunning(false),
+ mArgc(argc),
+ mArgv(argv),
+ mBundleName(""),
+ mBundleId(""),
+ mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
+ mImpl(NULL)
+{
+ InitThreads();
+ mImpl = new Impl(this);
+}
+
+Framework::~Framework()
+{
+ if (mRunning)
+ {
+ Quit();
+ }
+
+ delete mImpl;
+}
+
+void Framework::Run()
+{
+ mRunning = true;
+
+ elm_init(*mArgc, *mArgv);
+
+ Impl::AppCreate(this);
+
+ elm_run();
+
+ mRunning = false;
+}
+
+void Framework::Quit()
+{
+ Impl::AppTerminate(this);
+
+ elm_exit();
+}
+
+bool Framework::IsMainLoopRunning()
+{
+ return mRunning;
+}
+
+void Framework::AddAbortCallback( CallbackBase* callback )
+{
+ mImpl->mAbortCallBack = callback;
+}
+
+std::string Framework::GetBundleName() const
+{
+ return mBundleName;
+}
+
+void Framework::SetBundleName(const std::string& name)
+{
+ mBundleName = name;
+}
+
+std::string Framework::GetBundleId() const
+{
+ return mBundleId;
+}
+
+std::string Framework::GetResourcePath()
+{
+ // "DALI_APPLICATION_PACKAGE" is used by Ubuntu specifically to get the already configured Application package path.
+ const char* ubuntuEnvironmentVariable = "DALI_APPLICATION_PACKAGE";
+ char* value = getenv( ubuntuEnvironmentVariable );
+ std::string resourcePath;
+ if ( value != NULL )
+ {
+ resourcePath = value;
+ }
+
+ return resourcePath;
+}
+
+void Framework::SetBundleId(const std::string& id)
+{
+ mBundleId = id;
+}
+
+void Framework::AbortCallback( )
+{
+ // if an abort call back has been installed run it.
+ if (mImpl->mAbortCallBack)
+ {
+ CallbackBase::Execute( *mImpl->mAbortCallBack );
+ }
+ else
+ {
+ Quit();
+ }
+}
+
+bool Framework::AppStatusHandler(int type, void *bundleData)
+{
+ switch (type)
+ {
+ case APP_CREATE:
+ {
+ mInitialised = true;
+
+ mObserver.OnInit();
+ break;
+ }
+
+ case APP_RESET:
+ mObserver.OnReset();
+ break;
+
+ case APP_RESUME:
+ mObserver.OnResume();
+ break;
+
+ case APP_TERMINATE:
+ mObserver.OnTerminate();
+ break;
+
+ case APP_PAUSE:
+ mObserver.OnPause();
+ break;
+
+ case APP_LANGUAGE_CHANGE:
+ mObserver.OnLanguageChanged();
+ break;
+
+ default:
+ break;
+ }
+
+ return true;
+}
+
+void Framework::InitThreads()
+{
+ XInitThreads();
+}
+
+std::string Framework::GetLanguage() const
+{
+ return mImpl->GetLanguage();
+}
+
+std::string Framework::GetRegion() const
+{
+ return mImpl->GetRegion();
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/clipboard/common/clipboard-event-notifier-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ClipboardEventNotifier ClipboardEventNotifier::New()
+{
+ Dali::ClipboardEventNotifier notifier = Dali::ClipboardEventNotifier(new ClipboardEventNotifier());
+
+ return notifier;
+}
+
+Dali::ClipboardEventNotifier ClipboardEventNotifier::Get()
+{
+ Dali::ClipboardEventNotifier notifier;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ClipboardEventNotifier ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ notifier = Dali::ClipboardEventNotifier( dynamic_cast< ClipboardEventNotifier* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ notifier = Dali::ClipboardEventNotifier( ClipboardEventNotifier::New() );
+ service.Register( typeid( notifier ), notifier );
+ }
+ }
+
+ return notifier;
+}
+
+const std::string& ClipboardEventNotifier::GetContent() const
+{
+ return mContent;
+}
+
+void ClipboardEventNotifier::SetContent( const std::string& content )
+{
+ mContent = content;
+}
+
+void ClipboardEventNotifier::ClearContent()
+{
+ mContent.clear();
+}
+
+void ClipboardEventNotifier::EmitContentSelectedSignal()
+{
+ if ( !mContentSelectedSignal.Empty() )
+ {
+ Dali::ClipboardEventNotifier handle( this );
+ mContentSelectedSignal.Emit( handle );
+ }
+}
+
+ClipboardEventNotifier::ClipboardEventNotifier()
+: mContent()
+{
+}
+
+ClipboardEventNotifier::~ClipboardEventNotifier()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
+#define __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/math/vector2.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * This class listens to Clipboard events.
+ */
+class ClipboardEventNotifier : public Dali::BaseObject
+{
+public:
+
+ typedef Dali::ClipboardEventNotifier::ClipboardEventSignalType ClipboardEventSignalType;
+
+ // Creation
+
+ /**
+ * Create a ClipboardEventNotifier.
+ * @return A newly allocated clipboard-event-notifier.
+ */
+ static Dali::ClipboardEventNotifier New();
+
+ /**
+ * @copydoc Dali::ClipboardEventNotifier::Get()
+ */
+ static Dali::ClipboardEventNotifier Get();
+
+ // Public API
+
+ /**
+ * @copydoc Dali::ClipboardEventNotifier::GetContent() const
+ */
+ const std::string& GetContent() const;
+
+ /**
+ * Sets the selected content.
+ * @param[in] content A string that represents the content that has been selected.
+ */
+ void SetContent( const std::string& content );
+
+ /**
+ * Clears the stored content.
+ */
+ void ClearContent();
+
+ /**
+ * Called when content is selected in the clipboard.
+ */
+ void EmitContentSelectedSignal();
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::ClipboardEventNotifier::ContentSelectedSignal
+ */
+ ClipboardEventSignalType& ContentSelectedSignal()
+ {
+ return mContentSelectedSignal;
+ }
+
+private:
+
+ // Construction & Destruction
+
+ /**
+ * Constructor.
+ */
+ ClipboardEventNotifier();
+
+ /**
+ * Destructor.
+ */
+ virtual ~ClipboardEventNotifier();
+
+ // Undefined
+ ClipboardEventNotifier( const ClipboardEventNotifier& );
+ ClipboardEventNotifier& operator=( ClipboardEventNotifier& );
+
+private:
+
+ std::string mContent; ///< The current selected content.
+
+ ClipboardEventSignalType mContentSelectedSignal;
+
+public:
+
+ // Helpers for public-api forwarding methods
+
+ inline static Internal::Adaptor::ClipboardEventNotifier& GetImplementation(Dali::ClipboardEventNotifier& detector)
+ {
+ DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" );
+
+ BaseObject& handle = detector.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::ClipboardEventNotifier&>(handle);
+ }
+
+ inline static const Internal::Adaptor::ClipboardEventNotifier& GetImplementation(const Dali::ClipboardEventNotifier& detector)
+ {
+ DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" );
+
+ const BaseObject& handle = detector.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::ClipboardEventNotifier&>(handle);
+ }
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_CLIPBOARD_H__
+#define __DALI_INTERNAL_CLIPBOARD_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/clipboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of the Clip Board
+ */
+
+class Clipboard : public Dali::BaseObject
+{
+public:
+
+ // Hide the specific windowing system
+ struct Impl;
+
+ /**
+ * @copydoc Dali::ClipboardEventNotifier::Get()
+ */
+ static Dali::Clipboard Get();
+
+ /**
+ * Constructor
+ * @param[in] impl Some data from a specific windowing system.
+ */
+ Clipboard(Impl* impl);
+
+ /**
+ * Destructor
+ */
+ virtual ~Clipboard();
+
+ /**
+ * @copydoc Dali::Clipboard::SetItem()
+ */
+ bool SetItem(const std::string &itemData);
+
+ /**
+ * @copydoc Dali::Clipboard::RequestItem()
+ */
+ void RequestItem();
+
+ /**
+ * @copydoc Dali::Clipboard::NumberOfClipboardItems()
+ */
+ unsigned int NumberOfItems();
+
+ /**
+ * @copydoc Dali::Clipboard::ShowClipboard()
+ */
+ void ShowClipboard();
+
+ /**
+ * @copydoc Dali::Clipboard::HideClipboard()
+ */
+ void HideClipboard(bool skipFirstHide);
+
+ /**
+ * @copydoc Dali::Clipboard::IsVisible()
+ */
+ bool IsVisible() const;
+
+ /**
+ * @brief exchange either sending or receiving buffered data
+ *
+ * @param[in] type true for send buffered data, false for receive data to buffer
+ * @param[in] event information pointer
+ * @return The buffer pointer for send or receive data
+ */
+ char* ExcuteBuffered( bool type, void *event );
+
+private:
+
+ // Undefined
+ Clipboard( const Clipboard& );
+ Clipboard& operator=( Clipboard& );
+
+private:
+
+ Impl* mImpl;
+
+public:
+
+}; // class clipboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+inline static Internal::Adaptor::Clipboard& GetImplementation(Dali::Clipboard& clipboard)
+{
+ DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" );
+ BaseObject& handle = clipboard.GetBaseObject();
+ return static_cast<Internal::Adaptor::Clipboard&>(handle);
+}
+
+inline static const Internal::Adaptor::Clipboard& GetImplementation(const Dali::Clipboard& clipboard)
+{
+ DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" );
+ const BaseObject& handle = clipboard.GetBaseObject();
+ return static_cast<const Internal::Adaptor::Clipboard&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_CLIPBOARD_H__
--- /dev/null
+
+
+# module: clipboard, backend: common
+adaptor_clipboard_common_src_files=\
+ ${adaptor_clipboard_dir}/common/clipboard-event-notifier-impl.cpp
+
+# module: clipboard, backend: tizen-wayland
+adaptor_clipboard_tizen_wayland_src_files=\
+ ${adaptor_clipboard_dir}/tizen-wayland/clipboard-impl-ecore-wl.cpp
+
+# module: clipboard, backend: ubuntu-x11
+adaptor_clipboard_ubuntu_x11_src_files=\
+ ${adaptor_clipboard_dir}/ubuntu-x11/clipboard-impl-x.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Ecore_Wayland.h>
+#include <dali/public-api/object/any.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <unistd.h>
+
+#ifdef DALI_ELDBUS_AVAILABLE
+#include <Eldbus.h>
+#endif // DALI_ELDBUS_AVAILABLE
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+#define CBHM_DBUS_OBJPATH "/org/tizen/cbhm/dbus"
+#ifndef CBHM_DBUS_INTERFACE
+#define CBHM_DBUS_INTERFACE "org.tizen.cbhm.dbus"
+#endif /* CBHM_DBUS_INTERFACE */
+#define CBHM_COUNT_ALL 0 // ATOM_INDEX_CBHM_COUNT_ALL
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Clipboard
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+struct Clipboard::Impl
+{
+ Impl()
+ {
+ Eldbus_Object *eldbus_obj;
+ cbhm_conn = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SESSION);
+ eldbus_obj = eldbus_object_get(cbhm_conn, CBHM_DBUS_INTERFACE, CBHM_DBUS_OBJPATH);
+ eldbus_proxy = eldbus_proxy_get(eldbus_obj, CBHM_DBUS_INTERFACE);
+ eldbus_name_owner_changed_callback_add(cbhm_conn, CBHM_DBUS_INTERFACE, NULL, cbhm_conn, EINA_TRUE);
+ eldbus_proxy_signal_handler_add(eldbus_proxy, "ItemClicked", _on_item_clicked, this);
+ mVisible = false;
+ mIsFirstTimeHidden = true;
+ }
+
+ ~Impl()
+ {
+ if (cbhm_conn)
+ eldbus_connection_unref(cbhm_conn);
+ }
+
+ Eldbus_Proxy* cbhm_proxy_get()
+ {
+ return eldbus_proxy;
+ }
+
+ Eldbus_Connection* cbhm_connection_get()
+ {
+ return cbhm_conn;
+ }
+
+ void SetItem( const std::string &itemData )
+ {
+ const char *types[10] = {0, };
+ int i = -1;
+
+ if (itemData.length() == 0)
+ {
+ return;
+ }
+ mSendBuffer = itemData;
+
+ // ELM_SEL_TYPE_CLIPBOARD - To distinguish clipboard selection in cbhm
+ types[++i] = "CLIPBOARD_BEGIN";
+
+ types[++i] = "text/plain;charset=utf-8";
+
+ // ELM_SEL_TYPE_CLIPBOARD - To distinguish clipboard selection in cbhm
+ types[++i] = "CLIPBOARD_END";
+ ecore_wl_dnd_selection_set(ecore_wl_input_get(), types);
+ }
+
+ void RequestItem()
+ {
+ const char *types[10] = {0, };
+ int i = -1;
+
+ types[++i] = "text/plain;charset=utf-8";
+ ecore_wl_dnd_selection_get(ecore_wl_input_get(), *types);
+ }
+
+ char *ExcuteSend( void *event )
+ {
+ Ecore_Wl_Event_Data_Source_Send *ev = (Ecore_Wl_Event_Data_Source_Send *)event;
+ int len_buf = mSendBuffer.length();
+ int len_remained = len_buf;
+ int len_written = 0, ret;
+ const char *buf = mSendBuffer.c_str();
+
+ while (len_written < len_buf)
+ {
+ ret = write(ev->fd, buf, len_remained);
+ if (ret == -1) break;
+ buf += ret;
+ len_written += ret;
+ len_remained -= ret;
+ }
+ close(ev->fd);
+ return NULL;
+ }
+
+ char *ExcuteReceive( void *event )
+ {
+ Ecore_Wl_Event_Selection_Data_Ready *ev = (Ecore_Wl_Event_Selection_Data_Ready *)event;
+
+ return (char *)ev->data;
+ }
+
+ int GetCount()
+ {
+ Eldbus_Message *reply, *req;
+ const char *errname = NULL, *errmsg = NULL;
+ int count = -1;
+
+ if (!(req = eldbus_proxy_method_call_new(eldbus_proxy, "CbhmGetCount")))
+ {
+ DALI_LOG_ERROR("Failed to create method call on org.freedesktop.DBus.Properties.Get");
+ return -1;
+ }
+
+ eldbus_message_ref(req);
+ eldbus_message_arguments_append(req, "i", CBHM_COUNT_ALL) ;
+ reply = eldbus_proxy_send_and_block(eldbus_proxy, req, 100);
+ if (!reply || eldbus_message_error_get(reply, &errname, &errmsg))
+ {
+ DALI_LOG_ERROR("Unable to call method org.freedesktop.DBus.Properties.Get: %s %s",
+ errname, errmsg);
+ eldbus_message_unref(req);
+ return -1;
+ }
+
+ if (!eldbus_message_arguments_get(reply, "i", &count))
+ {
+ DALI_LOG_ERROR("Cannot get arguments from eldbus");
+ eldbus_message_unref(req);
+ return -1;
+ }
+
+ eldbus_message_unref(req);
+ DALI_LOG_ERROR("cbhm item count(%d)", count);
+ return count;
+ }
+
+ void ShowClipboard()
+ {
+ eldbus_proxy_call(cbhm_proxy_get(), "CbhmShow", NULL, NULL, -1, "s", "0");
+ mIsFirstTimeHidden = true;
+ mVisible = true;
+ }
+
+ void HideClipboard( bool skipFirstHide )
+ {
+ if ( skipFirstHide && mIsFirstTimeHidden )
+ {
+ mIsFirstTimeHidden = false;
+ return;
+ }
+ eldbus_proxy_call(cbhm_proxy_get(), "CbhmHide", NULL, NULL, -1, "");
+ mIsFirstTimeHidden = false;
+ mVisible = false;
+ }
+
+ bool IsVisible() const
+ {
+ return mVisible;
+ }
+
+ static void _on_item_clicked(void *data, const Eldbus_Message *msg EINA_UNUSED)
+ {
+ static_cast<Clipboard::Impl*>(data)->RequestItem();
+ }
+
+ Eldbus_Proxy *eldbus_proxy;
+ Eldbus_Connection *cbhm_conn;
+
+ std::string mSendBuffer;
+ bool mVisible;
+ bool mIsFirstTimeHidden;
+};
+
+Clipboard::Clipboard(Impl* impl)
+: mImpl(impl)
+{
+}
+
+Clipboard::~Clipboard()
+{
+ delete mImpl;
+}
+
+Dali::Clipboard Clipboard::Get()
+{
+ Dali::Clipboard clipboard;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ Clipboard::Impl* impl( new Clipboard::Impl() );
+ clipboard = Dali::Clipboard( new Clipboard(impl) );
+ service.Register( typeid(Dali::Clipboard), clipboard );
+ }
+ }
+
+ return clipboard;
+}
+
+bool Clipboard::SetItem(const std::string &itemData )
+{
+ mImpl->SetItem( itemData );
+ return true;
+}
+
+/*
+ * Request clipboard service to give an item
+ */
+void Clipboard::RequestItem()
+{
+ mImpl->RequestItem();
+}
+
+/*
+ * Get number of items in clipboard
+ */
+unsigned int Clipboard::NumberOfItems()
+{
+ return mImpl->GetCount();
+}
+
+void Clipboard::ShowClipboard()
+{
+ mImpl->ShowClipboard();
+}
+
+void Clipboard::HideClipboard(bool skipFirstHide)
+{
+ mImpl->HideClipboard(skipFirstHide);
+}
+
+bool Clipboard::IsVisible() const
+{
+ return mImpl->IsVisible();
+}
+
+char* Clipboard::ExcuteBuffered( bool type, void *event )
+{
+ return (type ? mImpl->ExcuteSend( event ) : mImpl->ExcuteReceive( event ));
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+
+// EXTERNAL INCLUDES
+#include <Ecore_X.h>
+#include <dali/public-api/object/any.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/clipboard/common/clipboard-event-notifier-impl.h>
+
+namespace //unnamed namespace
+{
+const char* const CBHM_WINDOW = "CBHM_XWIN";
+const char* const CBHM_MSG = "CBHM_MSG";
+const char* const CBHM_ITEM = "CBHM_ITEM";
+const char* const CBHM_cCOUNT = "CBHM_cCOUNT";
+const char* const CBHM_ERROR = "CBHM_ERROR";
+const char* const SET_ITEM = "SET_ITEM";
+const char* const SHOW = "show0";
+const char* const HIDE = "cbhm_hide";
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Clipboard
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+struct Clipboard::Impl
+{
+ Impl( Ecore_X_Window ecoreXwin )
+ {
+ mApplicationWindow = ecoreXwin;
+ }
+
+ Ecore_X_Window mApplicationWindow;
+};
+
+Clipboard::Clipboard(Impl* impl)
+: mImpl( impl )
+{
+}
+
+Clipboard::~Clipboard()
+{
+ delete mImpl;
+}
+
+Dali::Clipboard Clipboard::Get()
+{
+ Dali::Clipboard clipboard;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
+ Any nativewindow = adaptorImpl.GetNativeWindowHandle();
+
+ // The Ecore_X_Window needs to use the Clipboard.
+ // Only when the render surface is window, we can get the Ecore_X_Window.
+ Ecore_X_Window ecoreXwin( AnyCast<Ecore_X_Window>(nativewindow) );
+ if (ecoreXwin)
+ {
+ // If we fail to get Ecore_X_Window, we can't use the Clipboard correctly.
+ // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
+ // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
+ Clipboard::Impl* impl( new Clipboard::Impl( ecoreXwin ) );
+ clipboard = Dali::Clipboard( new Clipboard( impl ) );
+ service.Register( typeid( clipboard ), clipboard );
+ }
+ }
+ }
+
+ return clipboard;
+}
+bool Clipboard::SetItem(const std::string &itemData )
+{
+ Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
+ Ecore_X_Atom atomCbhmItem = ecore_x_atom_get( CBHM_ITEM );
+ Ecore_X_Atom dataType = ECORE_X_ATOM_STRING;
+
+ // Set item (property) to send
+ ecore_x_window_prop_property_set( cbhmWin, atomCbhmItem, dataType, 8, const_cast<char*>( itemData.c_str() ), itemData.length() + 1 );
+ ecore_x_sync();
+
+ // Trigger sending of item (property)
+ Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
+ ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SET_ITEM );
+ return true;
+}
+
+/*
+ * Request clipboard service to retrieve an item
+ */
+void Clipboard::RequestItem()
+{
+ int index = 0;
+ char sendBuf[20];
+ snprintf( sendBuf, 20, "%s%d", CBHM_ITEM, index );
+ Ecore_X_Atom xAtomCbhmItem = ecore_x_atom_get( sendBuf );
+ Ecore_X_Atom xAtomItemType = 0;
+
+ std::string clipboardString( ECore::WindowInterface::GetWindowProperty(xAtomCbhmItem, &xAtomItemType, index ) );
+
+ // Only return the text string if the Atom type is text (Do not return a text string/URL for images).
+ if( !clipboardString.empty() &&
+ ( xAtomItemType == ECORE_X_ATOM_TEXT || xAtomItemType == ECORE_X_ATOM_COMPOUND_TEXT || xAtomItemType == ECORE_X_ATOM_STRING || xAtomItemType == ECORE_X_ATOM_UTF8_STRING ) )
+ {
+ Ecore_X_Atom xAtomCbhmError = ecore_x_atom_get( CBHM_ERROR );
+ if ( xAtomItemType != xAtomCbhmError )
+ {
+ // Call ClipboardEventNotifier to notify event observe of retrieved string
+ Dali::ClipboardEventNotifier clipboardEventNotifier(ClipboardEventNotifier::Get());
+ if ( clipboardEventNotifier )
+ {
+ ClipboardEventNotifier& notifierImpl( ClipboardEventNotifier::GetImplementation( clipboardEventNotifier ) );
+
+ notifierImpl.SetContent( clipboardString );
+ notifierImpl.EmitContentSelectedSignal();
+ }
+ }
+ }
+}
+
+/*
+ * Get number of items in clipboard
+ */
+unsigned int Clipboard::NumberOfItems()
+{
+ Ecore_X_Atom xAtomCbhmCountGet = ecore_x_atom_get( CBHM_cCOUNT );
+
+ std::string ret( ECore::WindowInterface::GetWindowProperty( xAtomCbhmCountGet, NULL, 0 ) );
+ int count = 0;
+
+ if ( !ret.empty() )
+ {
+ count = atoi( ret.c_str() );
+ }
+
+ return count;
+}
+
+/**
+ * Show clipboard window
+ * Function to send message to show the Clipboard (cbhm) as no direct API available
+ * Reference elementary/src/modules/ctxpopup_copypasteUI/cbhm_helper.c
+ */
+void Clipboard::ShowClipboard()
+{
+ // Claim the ownership of the SECONDARY selection.
+ ecore_x_selection_secondary_set(mImpl->mApplicationWindow, "", 1);
+ Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
+
+ // Launch the clipboard window
+ Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
+ ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SHOW );
+}
+
+void Clipboard::HideClipboard(bool skipFirstHide)
+{
+ Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow();
+ // Launch the clipboard window
+ Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG );
+ ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, HIDE );
+
+ // release the ownership of SECONDARY selection
+ ecore_x_selection_secondary_clear();
+}
+
+bool Clipboard::IsVisible() const
+{
+ return false;
+}
+
+char* Clipboard::ExcuteBuffered( bool type, void *event )
+{
+ return NULL;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/common/render-helper.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+#include <dali/internal/window-system/common/display-connection.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+RenderHelper::RenderHelper( AdaptorInternalServices& adaptorInterfaces )
+: mGLES( adaptorInterfaces.GetGlesInterface() ),
+ mEglFactory( &adaptorInterfaces.GetEGLFactoryInterface()),
+ mEGL( NULL ),
+ mSurfaceReplaced( false ),
+ mSurfaceResized( false )
+{
+ // set the initial values before render thread starts
+ mSurface = adaptorInterfaces.GetRenderSurfaceInterface();
+
+ if( mSurface )
+ {
+ mDisplayConnection = Dali::DisplayConnection::New( mSurface->GetSurfaceType() );
+ }
+ else
+ {
+ mDisplayConnection = Dali::DisplayConnection::New();
+ }
+}
+
+RenderHelper::~RenderHelper()
+{
+ if (mDisplayConnection)
+ {
+ delete mDisplayConnection;
+ mDisplayConnection = NULL;
+ }
+
+ mEglFactory->Destroy();
+}
+
+void RenderHelper::Start()
+{
+ if( mSurface )
+ {
+ mSurface->StartRender();
+ }
+}
+
+void RenderHelper::Stop()
+{
+ if( mSurface )
+ {
+ // Tell surface we have stopped rendering
+ mSurface->StopRender();
+ }
+}
+
+void RenderHelper::ConsumeEvents()
+{
+ mDisplayConnection->ConsumeEvents();
+}
+
+void RenderHelper::InitializeEgl()
+{
+ mEGL = mEglFactory->Create();
+
+ DALI_ASSERT_ALWAYS( mSurface && "NULL surface" );
+
+ // Initialize EGL & OpenGL
+ mDisplayConnection->InitializeEgl( *mEGL );
+ mSurface->InitializeEgl( *mEGL );
+
+ // create the OpenGL context
+ mEGL->CreateContext();
+
+ // create the OpenGL surface
+ mSurface->CreateEglSurface(*mEGL);
+
+ // Make it current
+ mEGL->MakeContextCurrent();
+}
+
+void RenderHelper::ReplaceSurface( RenderSurface* newSurface )
+{
+ mSurface->DestroyEglSurface(*mEGL);
+
+ // This is designed for replacing pixmap surfaces, but should work for window as well
+ // we need to delete the egl surface and renderable (pixmap / window)
+ // Then create a new pixmap/window and new egl surface
+ // If the new surface has a different display connection, then the context will be lost
+ DALI_ASSERT_ALWAYS(newSurface && "NULL surface");
+
+ mDisplayConnection->InitializeEgl(*mEGL);
+
+ newSurface->ReplaceEGLSurface(*mEGL);
+
+ // use the new surface from now on
+ mSurface = newSurface;
+ mSurfaceReplaced = true;
+}
+
+void RenderHelper::ResizeSurface()
+{
+ mSurfaceResized = true;
+}
+
+void RenderHelper::ShutdownEgl()
+{
+ if( mSurface )
+ {
+ // give a chance to destroy the OpenGL surface that created externally
+ mSurface->DestroyEglSurface( *mEGL );
+
+ mSurface = NULL;
+ }
+
+ // delete the GL context / egl surface
+ mEGL->TerminateGles();
+}
+
+bool RenderHelper::PreRender()
+{
+ if( mSurface )
+ {
+ mSurface->PreRender( *mEGL, mGLES, mSurfaceResized );
+ }
+ mGLES.PreRender();
+ return true;
+}
+
+void RenderHelper::PostRender( bool renderToFbo )
+{
+ // Inform the gl implementation that rendering has finished before informing the surface
+ mGLES.PostRender();
+
+ if( renderToFbo )
+ {
+ mGLES.Flush();
+ mGLES.Finish();
+ }
+ else
+ {
+ if( mSurface )
+ {
+ // Inform the surface that rendering this frame has finished.
+ mSurface->PostRender( *mEGL, mGLES, mDisplayConnection, mSurfaceReplaced, mSurfaceResized );
+ }
+ }
+ mSurfaceReplaced = false;
+ mSurfaceResized = false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_RENDER_HELPER_H
+#define DALI_INTERNAL_RENDER_HELPER_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/egl-interface.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class DisplayConnection;
+
+namespace Integration
+{
+class GlAbstraction;
+}
+
+namespace Internal
+{
+namespace Adaptor
+{
+
+class AdaptorInternalServices;
+class EglFactoryInterface;
+
+/**
+ * Helper class for EGL, surface, pre & post rendering
+ */
+class RenderHelper
+{
+public:
+
+ /**
+ * Create a RenderHelper.
+ * @param[in] adaptorInterfaces base adaptor interface
+ */
+ RenderHelper( AdaptorInternalServices& adaptorInterfaces );
+
+ /**
+ * Non-virtual Destructor
+ */
+ ~RenderHelper();
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Called on the Event Thread
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Sets up all render related objects to start rendering.
+ */
+ void Start();
+
+ /**
+ * Sets up all render related objects to stop rendering.
+ */
+ void Stop();
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Called on the Rendering Thread
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Consumes any pending events to avoid memory leaks
+ *
+ * @note Called from rendering thread
+ */
+ void ConsumeEvents();
+
+ /**
+ * Initializes EGL.
+ *
+ * @note Called from rendering thread
+ */
+ void InitializeEgl();
+
+ /**
+ * Replaces the rendering surface
+ *
+ * Used for replacing pixmaps due to resizing
+ * @param newSurface to use
+ *
+ * @note Called from render thread
+ */
+ void ReplaceSurface( RenderSurface* newSurface );
+
+ /**
+ * Resize the rendering surface.
+ *
+ * @note Called from render thread
+ */
+ void ResizeSurface();
+
+ /**
+ * Shuts down EGL.
+ *
+ * @note Called from render thread
+ */
+ void ShutdownEgl();
+
+ /**
+ * Called before core renders the scene
+ *
+ * @return true if successful and Core::Render should be called.
+ *
+ * @note Called from render thread
+ */
+ bool PreRender();
+
+ /**
+ * Called after core has rendered the scene
+ *
+ * @note Called from render thread
+ *
+ * @param[in] renderToFbo Whether to render to a Frame Buffer Object.
+ */
+ void PostRender( bool renderToFbo );
+
+private:
+
+ // Undefined
+ RenderHelper( const RenderHelper& RenderHelper );
+
+ // Undefined
+ RenderHelper& operator=( const RenderHelper& RenderHelper );
+
+private: // Data
+
+ Integration::GlAbstraction& mGLES; ///< GL abstraction reference
+ EglFactoryInterface* mEglFactory; ///< Factory class to create EGL implementation
+ EglInterface* mEGL; ///< Interface to EGL implementation
+ RenderSurface* mSurface; ///< Current surface
+ Dali::DisplayConnection* mDisplayConnection; ///< Display connection
+ bool mSurfaceReplaced; ///< True when new surface has been initialized.
+ bool mSurfaceResized; ///< True when the surface is resized.
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_RENDER_HELPER_H
--- /dev/null
+#ifndef __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
+#define __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <xf86drm.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/common/vsync-monitor-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Tizen interface for monitoring VSync
+ */
+class VSyncMonitor : public VSyncMonitorInterface
+{
+public:
+ /**
+ * Default constructor
+ */
+ VSyncMonitor();
+
+ /**
+ * Destructor
+ */
+ virtual ~VSyncMonitor();
+
+public:
+
+ /**
+ * Set the use hardware flag
+ * @param[in] useHardware The new state for the use hardware flag.
+ */
+ void SetUseHardwareVSync( bool useHardware );
+
+ /**
+ * Set whether the vsync hardware is available.
+ * (This is public to allow callback method to work...)
+ */
+ void SetHardwareVSyncAvailable(bool available);
+
+private: // From Dali::Internal::Adaptor::VSyncMonitorInterface
+
+ /**
+ * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::Initialize
+ */
+ virtual void Initialize();
+
+ /**
+ * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::Terminate
+ */
+ virtual void Terminate();
+
+ /**
+ * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::UseHardware
+ */
+ virtual bool UseHardware();
+
+ /**
+ * copydoc Dali::Internal::Adaptor::VSyncMonitorInterface::DoSync
+ */
+ virtual bool DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds );
+
+private:
+
+ int mFileDescriptor; ///< DRM dev node file descriptor
+ drmVBlank mVBlankInfo;
+ // NOTE cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
+ unsigned int mUseHardwareVSync; ///< Whether to use hardware vsync
+ unsigned int mHardwareVSyncAvailable; ///< Whether hardware vsync is available
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_VSYNC_MONITOR_IMPL_H__
--- /dev/null
+
+
+# module: graphics, backend: common
+adaptor_graphics_common_src_files=\
+ ${adaptor_graphics_dir}/common/render-helper.cpp
+
+# module: graphics, backend: gles20
+adaptor_graphics_gles20_src_files=\
+ ${adaptor_graphics_dir}/gles20/egl-debug.cpp \
+ ${adaptor_graphics_dir}/gles20/egl-factory.cpp \
+ ${adaptor_graphics_dir}/gles20/egl-implementation.cpp \
+ ${adaptor_graphics_dir}/gles20/egl-sync-implementation.cpp \
+ ${adaptor_graphics_dir}/gles20/gl-extensions.cpp \
+ ${adaptor_graphics_dir}/gles20/gl-proxy-implementation.cpp
+
+# module: graphics, backend: tizen
+adaptor_graphics_tizen_src_files=\
+ ${adaptor_graphics_dir}/tizen/egl-image-extensions-tizen.cpp \
+ ${adaptor_graphics_dir}/tizen/vsync-monitor-tizen.cpp
+
+# module: graphics, backend: ubuntu-gl
+adaptor_graphics_ubuntu_gl_src_files=\
+ ${adaptor_graphics_dir}/ubuntu-gl/egl-image-extensions.cpp
+
+# module: graphics, backend: ubuntu
+adaptor_graphics_ubuntu_src_files=\
+ ${adaptor_graphics_dir}/ubuntu/vsync-monitor-ubuntu.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/egl-debug.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace Egl
+{
+
+void PrintError( EGLint error)
+{
+ switch (error)
+ {
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR("EGL_BAD_DISPLAY : Display is not an EGL display connection\n");
+ break;
+ }
+ case EGL_NOT_INITIALIZED:
+ {
+ DALI_LOG_ERROR("EGL_NOT_INITIALIZED : Display has not been initialized\n");
+ break;
+ }
+ case EGL_BAD_SURFACE:
+ {
+ DALI_LOG_ERROR("EGL_BAD_SURFACE : Draw or read is not an EGL surface\n");
+ break;
+ }
+ case EGL_BAD_CONTEXT:
+ {
+ DALI_LOG_ERROR("EGL_BAD_CONTEXT : Context is not an EGL rendering context\n");
+ break;
+ }
+ case EGL_BAD_MATCH:
+ {
+ DALI_LOG_ERROR("EGL_BAD_MATCH : Draw or read are not compatible with context, or if context is set to EGL_NO_CONTEXT and draw or read are not set to EGL_NO_SURFACE, or if draw or read are set to EGL_NO_SURFACE and context is not set to EGL_NO_CONTEXT\n");
+ break;
+ }
+ case EGL_BAD_ACCESS:
+ {
+ DALI_LOG_ERROR("EGL_BAD_ACCESS : Context is current to some other thread\n");
+ break;
+ }
+ case EGL_BAD_NATIVE_PIXMAP:
+ {
+ DALI_LOG_ERROR("EGL_BAD_NATIVE_PIXMAP : A native pixmap underlying either draw or read is no longer valid\n");
+ break;
+ }
+ case EGL_BAD_NATIVE_WINDOW:
+ {
+ DALI_LOG_ERROR("EGL_BAD_NATIVE_WINDOW : A native window underlying either draw or read is no longer valid\n");
+ break;
+ }
+ case EGL_BAD_CURRENT_SURFACE:
+ {
+ DALI_LOG_ERROR("EGL_BAD_CURRENT_SURFACE : The previous context has unflushed commands and the previous surface is no longer valid\n");
+ break;
+ }
+ case EGL_BAD_ALLOC:
+ {
+ DALI_LOG_ERROR("EGL_BAD_ALLOC : Allocation of ancillary buffers for draw or read were delayed until eglMakeCurrent is called, and there are not enough resources to allocate them\n");
+ break;
+ }
+ case EGL_CONTEXT_LOST:
+ {
+ DALI_LOG_ERROR("EGL_CONTEXT_LOST : If a power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering\n");
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR("Unknown error with code: %d\n", error);
+ break;
+ }
+ }
+}
+
+} // namespace Egl
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/egl-factory.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+#include <dali/internal/graphics/gles20/egl-sync-implementation.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+EglFactory::EglFactory( int multiSamplingLevel,
+ Integration::DepthBufferAvailable depthBufferRequired,
+ Integration::StencilBufferAvailable stencilBufferRequired )
+: mEglImplementation(NULL),
+ mEglImageExtensions(NULL),
+ mEglSync(new EglSyncImplementation), // Created early, as needed by Core constructor
+ mMultiSamplingLevel( multiSamplingLevel ),
+ mDepthBufferRequired( depthBufferRequired ),
+ mStencilBufferRequired( stencilBufferRequired )
+{
+}
+
+EglFactory::~EglFactory()
+{
+ // Ensure the EGL implementation is destroyed
+ delete mEglImageExtensions;
+ delete mEglImplementation;
+ delete mEglSync;
+}
+
+EglInterface* EglFactory::Create()
+{
+ // Created by RenderThread (After Core construction)
+ mEglImplementation = new EglImplementation( mMultiSamplingLevel, mDepthBufferRequired, mStencilBufferRequired );
+ mEglImageExtensions = new EglImageExtensions( mEglImplementation );
+
+ mEglSync->Initialize(mEglImplementation); // The sync impl needs the EglDisplay
+ return mEglImplementation;
+}
+
+void EglFactory::Destroy()
+{
+ delete mEglImageExtensions;
+ mEglImageExtensions = NULL;
+ delete mEglImplementation;
+ mEglImplementation = NULL;
+}
+
+EglInterface* EglFactory::GetImplementation()
+{
+ return mEglImplementation;
+}
+
+EglImageExtensions* EglFactory::GetImageExtensions()
+{
+ return mEglImageExtensions;
+}
+
+EglSyncImplementation* EglFactory::GetSyncImplementation()
+{
+ return mEglSync;
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
+#define DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/core-enumerations.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/egl-factory-interface.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class EglImplementation;
+class EglImageExtensions;
+class EglSyncImplementation;
+
+class EglFactory : public EglFactoryInterface
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] multiSamplingLevel The Multi-sampling level required
+ * @param[in] depthBufferRequired Whether the depth buffer is required
+ * @param[in] stencilBufferRequired Whether the stencil buffer is required
+ */
+ EglFactory( int multiSamplingLevel,
+ Integration::DepthBufferAvailable depthBufferRequired,
+ Integration::StencilBufferAvailable stencilBufferRequired );
+
+ /**
+ * Destructor
+ */
+ virtual ~EglFactory();
+
+ /**
+ * Create an EGL Implementation
+ * @return[in] An implementation
+ */
+ EglInterface* Create();
+
+ /**
+ * Destroy the EGL Implementation
+ */
+ void Destroy();
+
+ /**
+ * Get an implementation if one has been created.
+ * @return An implementation, or NULL if one has not yet been created.
+ */
+ EglInterface* GetImplementation();
+
+ /**
+ * Get the image extension
+ */
+ EglImageExtensions* GetImageExtensions();
+
+ /**
+ * Get the fence sync implementation
+ * @return An implementation of fence sync
+ */
+ EglSyncImplementation* GetSyncImplementation();
+
+private:
+ /** Undefined */
+ EglFactory(const EglFactory& rhs);
+ EglFactory& operator=(const EglFactory& rhs);
+
+private:
+ EglImplementation* mEglImplementation;
+ EglImageExtensions* mEglImageExtensions;
+ EglSyncImplementation* mEglSync;
+
+ int mMultiSamplingLevel;
+ Integration::DepthBufferAvailable mDepthBufferRequired;
+ Integration::StencilBufferAvailable mStencilBufferRequired;
+};
+
+} // namespace Adaptor
+} // namespace Internal
+} // namespace Dali
+
+#endif // DALI_INTERNAL_ADAPTOR_EGL_FACTORY_IMPL_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/gl-implementation.h>
+#include <dali/internal/graphics/gles20/egl-debug.h>
+
+// EGL constants use C style casts
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#define TEST_EGL_ERROR(lastCommand) \
+{ \
+ EGLint err = eglGetError(); \
+ if (err != EGL_SUCCESS) \
+ { \
+ DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \
+ Egl::PrintError(err); \
+ DALI_ASSERT_ALWAYS(0 && "EGL error"); \
+ } \
+}
+
+EglImplementation::EglImplementation( int multiSamplingLevel,
+ Integration::DepthBufferAvailable depthBufferRequired,
+ Integration::StencilBufferAvailable stencilBufferRequired )
+: mContextAttribs(),
+ mEglNativeDisplay( 0 ),
+ mEglNativeWindow( 0 ),
+ mCurrentEglNativePixmap( 0 ),
+ mEglDisplay( 0 ),
+ mEglConfig( 0 ),
+ mEglContext( 0 ),
+ mCurrentEglSurface( 0 ),
+ mMultiSamplingLevel( multiSamplingLevel ),
+ mColorDepth( COLOR_DEPTH_24 ),
+ mGlesInitialized( false ),
+ mIsOwnSurface( true ),
+ mContextCurrent( false ),
+ mIsWindow( true ),
+ mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ),
+ mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE )
+{
+}
+
+EglImplementation::~EglImplementation()
+{
+ TerminateGles();
+}
+
+bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface )
+{
+ if ( !mGlesInitialized )
+ {
+ mEglNativeDisplay = display;
+
+ //@todo see if we can just EGL_DEFAULT_DISPLAY instead
+ mEglDisplay = eglGetDisplay(mEglNativeDisplay);
+ EGLint error = eglGetError();
+
+ if( mEglDisplay == NULL && error != EGL_SUCCESS )
+ {
+ throw Dali::DaliException( "", "OpenGL ES is not supported");
+ }
+
+ EGLint majorVersion = 0;
+ EGLint minorVersion = 0;
+ if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) )
+ {
+ return false;
+ }
+ eglBindAPI(EGL_OPENGL_ES_API);
+
+ mContextAttribs.Clear();
+
+#if DALI_GLES_VERSION >= 30
+
+ mContextAttribs.Reserve(5);
+ mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR );
+ mContextAttribs.PushBack( DALI_GLES_VERSION / 10 );
+ mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR );
+ mContextAttribs.PushBack( DALI_GLES_VERSION % 10 );
+
+#else // DALI_GLES_VERSION >= 30
+
+ mContextAttribs.Reserve(3);
+ mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION );
+ mContextAttribs.PushBack( 2 );
+
+#endif // DALI_GLES_VERSION >= 30
+
+ mContextAttribs.PushBack( EGL_NONE );
+
+ mGlesInitialized = true;
+ mIsOwnSurface = isOwnSurface;
+ }
+
+ return mGlesInitialized;
+}
+
+bool EglImplementation::CreateContext()
+{
+ // make sure a context isn't created twice
+ DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" );
+
+ mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0]));
+ TEST_EGL_ERROR("eglCreateContext render thread");
+
+ DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" );
+
+ DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
+ DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
+ DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
+ DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
+ DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
+
+ return true;
+}
+
+void EglImplementation::DestroyContext()
+{
+ DALI_ASSERT_ALWAYS( mEglContext && "no EGL context" );
+
+ eglDestroyContext( mEglDisplay, mEglContext );
+ mEglContext = 0;
+}
+
+void EglImplementation::DestroySurface()
+{
+ if(mIsOwnSurface && mCurrentEglSurface)
+ {
+ // Make context null to prevent crash in driver side
+ MakeContextNull();
+ eglDestroySurface( mEglDisplay, mCurrentEglSurface );
+ mCurrentEglSurface = 0;
+ }
+}
+
+void EglImplementation::MakeContextCurrent()
+{
+ mContextCurrent = true;
+
+ if(mIsOwnSurface)
+ {
+ eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
+ }
+
+ EGLint error = eglGetError();
+
+ if ( error != EGL_SUCCESS )
+ {
+ Egl::PrintError(error);
+
+ DALI_ASSERT_ALWAYS(false && "MakeContextCurrent failed!");
+ }
+
+ // We want to display this information all the time, so use the LogMessage directly
+ Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n"
+ " Vendor: %s\n"
+ " Version: %s\n"
+ " Client APIs: %s\n"
+ " Extensions: %s\n",
+ eglQueryString(mEglDisplay, EGL_VENDOR),
+ eglQueryString(mEglDisplay, EGL_VERSION),
+ eglQueryString(mEglDisplay, EGL_CLIENT_APIS),
+ eglQueryString(mEglDisplay, EGL_EXTENSIONS));
+}
+
+void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface )
+{
+ mCurrentEglNativePixmap = pixmap;
+ mCurrentEglSurface = eglSurface;
+
+ if(mIsOwnSurface)
+ {
+ eglMakeCurrent( mEglDisplay, mCurrentEglSurface, mCurrentEglSurface, mEglContext );
+ }
+
+ EGLint error = eglGetError();
+
+ if ( error != EGL_SUCCESS )
+ {
+ Egl::PrintError(error);
+
+ DALI_ASSERT_ALWAYS(false && "MakeCurrent failed!");
+ }
+}
+
+void EglImplementation::MakeContextNull()
+{
+ mContextCurrent = false;
+ // clear the current context
+ eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
+}
+
+void EglImplementation::TerminateGles()
+{
+ if ( mGlesInitialized )
+ {
+ // Make context null to prevent crash in driver side
+ MakeContextNull();
+
+ if(mIsOwnSurface && mCurrentEglSurface)
+ {
+ eglDestroySurface(mEglDisplay, mCurrentEglSurface);
+ }
+ eglDestroyContext(mEglDisplay, mEglContext);
+
+ eglTerminate(mEglDisplay);
+
+ mEglDisplay = NULL;
+ mEglConfig = NULL;
+ mEglContext = NULL;
+ mCurrentEglSurface = NULL;
+
+ mGlesInitialized = false;
+ }
+}
+
+bool EglImplementation::IsGlesInitialized() const
+{
+ return mGlesInitialized;
+}
+
+void EglImplementation::SwapBuffers()
+{
+ eglSwapBuffers( mEglDisplay, mCurrentEglSurface );
+}
+
+void EglImplementation::CopyBuffers()
+{
+ eglCopyBuffers( mEglDisplay, mCurrentEglSurface, mCurrentEglNativePixmap );
+}
+
+void EglImplementation::WaitGL()
+{
+ eglWaitGL();
+}
+
+void EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth )
+{
+ if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth)
+ {
+ return;
+ }
+
+ mIsWindow = isWindowType;
+
+ EGLint numConfigs;
+ Vector<EGLint> configAttribs;
+ configAttribs.Reserve(31);
+
+ if(isWindowType)
+ {
+ configAttribs.PushBack( EGL_SURFACE_TYPE );
+ configAttribs.PushBack( EGL_WINDOW_BIT );
+ }
+ else
+ {
+ configAttribs.PushBack( EGL_SURFACE_TYPE );
+ configAttribs.PushBack( EGL_PIXMAP_BIT );
+ }
+
+ configAttribs.PushBack( EGL_RENDERABLE_TYPE );
+
+#if DALI_GLES_VERSION >= 30
+
+#ifdef _ARCH_ARM_
+ configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR );
+#else
+ // There is a bug in the desktop emulator
+ // Requesting for ES3 causes eglCreateContext even though it allows to ask
+ // for a configuration that supports GLES 3.0
+ configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
+#endif // _ARCH_ARM_
+
+#else // DALI_GLES_VERSION >= 30
+
+ Integration::Log::LogMessage( Integration::Log::DebugInfo, "Using OpenGL ES 2 \n" );
+ configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
+
+#endif //DALI_GLES_VERSION >= 30
+
+#if DALI_GLES_VERSION >= 30
+// TODO: enable this flag when it becomes supported
+// configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR );
+// configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR );
+#endif //DALI_GLES_VERSION >= 30
+
+ configAttribs.PushBack( EGL_RED_SIZE );
+ configAttribs.PushBack( 8 );
+ configAttribs.PushBack( EGL_GREEN_SIZE );
+ configAttribs.PushBack( 8 );
+ configAttribs.PushBack( EGL_BLUE_SIZE );
+ configAttribs.PushBack( 8 );
+
+ configAttribs.PushBack( EGL_ALPHA_SIZE );
+#ifdef _ARCH_ARM_
+ configAttribs.PushBack( (depth == COLOR_DEPTH_32) ? 8 : 0 );
+#else
+ // There is a bug in the desktop emulator
+ // setting EGL_ALPHA_SIZE to 8 results in eglChooseConfig failing
+ configAttribs.PushBack( 0 );
+#endif // _ARCH_ARM_
+
+ configAttribs.PushBack( EGL_DEPTH_SIZE );
+ configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 );
+ configAttribs.PushBack( EGL_STENCIL_SIZE );
+ configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 );
+
+#ifndef DALI_PROFILE_UBUNTU
+ if( mMultiSamplingLevel != EGL_DONT_CARE )
+ {
+ configAttribs.PushBack( EGL_SAMPLES );
+ configAttribs.PushBack( mMultiSamplingLevel );
+ configAttribs.PushBack( EGL_SAMPLE_BUFFERS );
+ configAttribs.PushBack( 1 );
+ }
+#endif // DALI_PROFILE_UBUNTU
+ configAttribs.PushBack( EGL_NONE );
+
+ if ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE )
+ {
+ EGLint error = eglGetError();
+ switch (error)
+ {
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR("Display is not an EGL display connection\n");
+ break;
+ }
+ case EGL_BAD_ATTRIBUTE:
+ {
+ DALI_LOG_ERROR("The parameter configAttribs contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range\n");
+ break;
+ }
+ case EGL_NOT_INITIALIZED:
+ {
+ DALI_LOG_ERROR("Display has not been initialized\n");
+ break;
+ }
+ case EGL_BAD_PARAMETER:
+ {
+ DALI_LOG_ERROR("The parameter numConfig is NULL\n");
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR("Unknown error.\n");
+ }
+ }
+ DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!");
+ }
+
+ if ( numConfigs != 1 )
+ {
+ DALI_LOG_ERROR("No configurations found.\n");
+
+ TEST_EGL_ERROR("eglChooseConfig");
+ }
+}
+
+void EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth )
+{
+ DALI_ASSERT_ALWAYS( ( mCurrentEglSurface == 0 ) && "EGL surface already exists" );
+
+ mEglNativeWindow = window;
+ mColorDepth = depth;
+ mIsWindow = true;
+
+ // egl choose config
+ ChooseConfig(mIsWindow, mColorDepth);
+
+ mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL );
+ TEST_EGL_ERROR("eglCreateWindowSurface");
+
+ DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" );
+}
+
+EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth )
+{
+ mCurrentEglNativePixmap = pixmap;
+ mColorDepth = depth;
+ mIsWindow = false;
+
+ // egl choose config
+ ChooseConfig(mIsWindow, mColorDepth);
+
+ mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL );
+ TEST_EGL_ERROR("eglCreatePixmapSurface");
+
+ DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" );
+
+ return mCurrentEglSurface;
+}
+
+bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window )
+{
+ bool contextLost = false;
+
+ // display connection has not changed, then we can just create a new surface
+ // the surface is bound to the context, so set the context to null
+ MakeContextNull();
+
+ // destroy the surface
+ DestroySurface();
+
+ // create the EGL surface
+ CreateSurfaceWindow( window, mColorDepth );
+
+ // set the context to be current with the new surface
+ MakeContextCurrent();
+
+ return contextLost;
+}
+
+bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface )
+{
+ bool contextLost = false;
+
+ // display connection has not changed, then we can just create a new surface
+ // create the EGL surface
+ eglSurface = CreateSurfacePixmap( pixmap, mColorDepth );
+
+ // set the eglSurface to be current
+ MakeCurrent( pixmap, eglSurface );
+
+ return contextLost;
+}
+
+EGLDisplay EglImplementation::GetDisplay() const
+{
+ return mEglDisplay;
+}
+
+EGLDisplay EglImplementation::GetContext() const
+{
+ return mEglContext;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef DALI_INTERNAL_EGL_IMPLEMENTATION_H
+#define DALI_INTERNAL_EGL_IMPLEMENTATION_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/integration-api/core-enumerations.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/egl-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * EglImplementation class provides an EGL implementation.
+ */
+class EglImplementation : public EglInterface
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] multiSamplingLevel The Multi-sampling level required
+ * @param[in] depthBufferRequired Whether the depth buffer is required
+ * @param[in] stencilBufferRequired Whether the stencil buffer is required
+ */
+ EglImplementation( int multiSamplingLevel,
+ Integration::DepthBufferAvailable depthBufferRequired,
+ Integration::StencilBufferAvailable stencilBufferRequired );
+
+ /**
+ * Destructor
+ */
+ virtual ~EglImplementation();
+
+public:
+
+ /**
+ * (Called from ECoreX::RenderSurface, not RenderThread, so not in i/f, hence, not virtual)
+ * Initialize GL
+ * @param display The display
+ * @param isOwnSurface whether the surface is own or not
+ * @return true on success, false on failure
+ */
+ bool InitializeGles( EGLNativeDisplayType display, bool isOwnSurface = true );
+
+ /**
+ * Create the OpenGL context.
+ * @return true if successful
+ */
+ virtual bool CreateContext();
+
+ /**
+ * Destroy the OpenGL context.
+ */
+ void DestroyContext();
+
+ /**
+ * Destroy the OpenGL surface.
+ */
+ void DestroySurface();
+
+ /**
+ * Make the OpenGL context current
+ */
+ virtual void MakeContextCurrent();
+
+ /**
+ * clear the OpenGL context
+ */
+ void MakeContextNull();
+
+ /**
+ * @brief Make the OpenGL surface current
+ *
+ * @param pixmap The pixmap to replace the current surface
+ * @param eglSurface The eglSurface to replace the current OpenGL surface.
+ */
+ void MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface );
+
+ /**
+ * Terminate GL
+ */
+ virtual void TerminateGles();
+
+ /**
+ * Checks if GL is initialised
+ * @return true if it is
+ */
+ bool IsGlesInitialized() const;
+
+ /**
+ * Performs an OpenGL swap buffers command
+ */
+ virtual void SwapBuffers();
+
+ /**
+ * Performs an OpenGL copy buffers command
+ */
+ virtual void CopyBuffers();
+
+ /**
+ * Performs an EGL wait GL command
+ */
+ virtual void WaitGL();
+
+ /**
+ * Choose config of egl
+ * @param isWindowType whether the config for window or pixmap
+ * @param colorDepth Bit per pixel value (ex. 32 or 24)
+ */
+ void ChooseConfig( bool isWindowType, ColorDepth depth );
+
+ /**
+ * Create an OpenGL surface using a window
+ * @param window The window to create the surface on
+ * @param colorDepth Bit per pixel value (ex. 32 or 24)
+ * @return true on success, false on failure
+ */
+ void CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth );
+
+ /**
+ * Create the OpenGL surface using a pixmap
+ * @param pixmap The pixmap to create the surface on
+ * @param colorDepth Bit per pixel value (ex. 32 or 24)
+ * @return Handle to an off-screen EGL pixmap surface (the requester has an ownership of this egl surface)
+ */
+ EGLSurface CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth );
+
+ /**
+ * Replaces the render surface
+ * @param[in] window, the window to create the new surface on
+ * @return true if the context was lost due to a change in display
+ * between old surface and new surface
+ */
+ bool ReplaceSurfaceWindow( EGLNativeWindowType window );
+
+ /**
+ * Replaces the render surface
+ * @param[in] pixmap, the pixmap to replace the new surface on
+ * @param[out] eglSurface, the eglSurface is created using a pixmap.
+ * @return true if the context was lost due to a change in x-display
+ * between old surface and new surface
+ */
+ bool ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface );
+
+ /**
+ * returns the display with which this object was initialized
+ * @return the EGL Display.
+ */
+ EGLDisplay GetDisplay() const;
+
+ /**
+ * Returns the EGL context
+ * @return the EGL context.
+ */
+ EGLContext GetContext() const;
+
+private:
+
+ Vector<EGLint> mContextAttribs;
+
+ EGLNativeDisplayType mEglNativeDisplay;
+
+ EGLNativeWindowType mEglNativeWindow;
+
+ EGLNativePixmapType mCurrentEglNativePixmap;
+
+ EGLDisplay mEglDisplay;
+ EGLConfig mEglConfig;
+ EGLContext mEglContext;
+ EGLSurface mCurrentEglSurface;
+
+ int mMultiSamplingLevel;
+
+ ColorDepth mColorDepth;
+
+ bool mGlesInitialized;
+ bool mIsOwnSurface;
+ bool mContextCurrent;
+ bool mIsWindow;
+ bool mDepthBufferRequired;
+ bool mStencilBufferRequired;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_EGL_IMPLEMENTATION_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/egl-sync-implementation.h>
+
+// EXTERNAL INCLUDES
+
+#ifdef _ARCH_ARM_
+
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+#include <EGL/eglext.h>
+
+#endif
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+#ifdef _ARCH_ARM_
+
+// function pointers
+static PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR = NULL;
+static PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR = NULL;
+static PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR = NULL;
+
+#endif
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+#ifdef _ARCH_ARM_
+
+EglSyncObject::EglSyncObject( EglImplementation& eglSyncImpl )
+: mEglSync(NULL),
+ mEglImplementation(eglSyncImpl)
+{
+ EGLDisplay display = mEglImplementation.GetDisplay();
+ mEglSync = eglCreateSyncKHR( display, EGL_SYNC_FENCE_KHR, NULL );
+ if (mEglSync == EGL_NO_SYNC_KHR)
+ {
+ DALI_LOG_ERROR("eglCreateSyncKHR failed %#0.4x\n", eglGetError());
+ mEglSync = NULL;
+ }
+}
+
+EglSyncObject::~EglSyncObject()
+{
+ if( mEglSync != NULL )
+ {
+ eglDestroySyncKHR( mEglImplementation.GetDisplay(), mEglSync );
+ EGLint error = eglGetError();
+ if( EGL_SUCCESS != error )
+ {
+ DALI_LOG_ERROR("eglDestroySyncKHR failed %#0.4x\n", error);
+ }
+ }
+}
+
+bool EglSyncObject::IsSynced()
+{
+ bool synced = false;
+
+ if( mEglSync != NULL )
+ {
+ EGLint result = eglClientWaitSyncKHR( mEglImplementation.GetDisplay(), mEglSync, 0, 0ull );
+ EGLint error = eglGetError();
+ if( EGL_SUCCESS != error )
+ {
+ DALI_LOG_ERROR("eglClientWaitSyncKHR failed %#0.4x\n", error);
+ }
+ else if( result == EGL_CONDITION_SATISFIED_KHR )
+ {
+ synced = true;
+ }
+ }
+
+ return synced;
+}
+
+EglSyncImplementation::EglSyncImplementation()
+: mEglImplementation( NULL ),
+ mSyncInitialized( false ),
+ mSyncInitializeFailed( false )
+{
+}
+
+EglSyncImplementation::~EglSyncImplementation()
+{
+}
+
+void EglSyncImplementation::Initialize( EglImplementation* eglImpl )
+{
+ mEglImplementation = eglImpl;
+}
+
+Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject()
+{
+ DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
+ if( mSyncInitialized == false )
+ {
+ InitializeEglSync();
+ }
+
+ EglSyncObject* syncObject = new EglSyncObject(*mEglImplementation);
+ mSyncObjects.PushBack( syncObject );
+ return syncObject;
+}
+
+void EglSyncImplementation::DestroySyncObject( Integration::GlSyncAbstraction::SyncObject* syncObject )
+{
+ DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
+
+ if( mSyncInitialized == false )
+ {
+ InitializeEglSync();
+ }
+
+ for( SyncIter iter=mSyncObjects.Begin(), end=mSyncObjects.End(); iter != end; ++iter )
+ {
+ if( *iter == syncObject )
+ {
+ mSyncObjects.Erase(iter);
+ break;
+ }
+ }
+ EglSyncObject* eglSyncObject = static_cast<EglSyncObject*>(syncObject);
+ delete eglSyncObject;
+}
+
+void EglSyncImplementation::InitializeEglSync()
+{
+ if( ! mSyncInitializeFailed )
+ {
+ eglCreateSyncKHR = reinterpret_cast< PFNEGLCREATESYNCKHRPROC >( eglGetProcAddress("eglCreateSyncKHR") );
+ eglClientWaitSyncKHR = reinterpret_cast< PFNEGLCLIENTWAITSYNCKHRPROC >( eglGetProcAddress("eglClientWaitSyncKHR") );
+ eglDestroySyncKHR = reinterpret_cast< PFNEGLDESTROYSYNCKHRPROC >( eglGetProcAddress("eglDestroySyncKHR") );
+ }
+
+ if( eglCreateSyncKHR && eglClientWaitSyncKHR && eglDestroySyncKHR )
+ {
+ mSyncInitialized = true;
+ }
+ else
+ {
+ mSyncInitializeFailed = true;
+ }
+}
+
+#else
+
+EglSyncObject::EglSyncObject( EglImplementation& eglImpl )
+: mPollCounter(3),
+ mEglImplementation(eglImpl)
+{
+}
+
+EglSyncObject::~EglSyncObject()
+{
+}
+
+bool EglSyncObject::IsSynced()
+{
+ if(mPollCounter <= 0)
+ {
+ return true;
+ }
+ --mPollCounter;
+ return false;
+}
+
+EglSyncImplementation::EglSyncImplementation()
+: mEglImplementation( NULL ),
+ mSyncInitialized( false ),
+ mSyncInitializeFailed( false )
+{
+}
+
+EglSyncImplementation::~EglSyncImplementation()
+{
+}
+
+void EglSyncImplementation::Initialize( EglImplementation* eglImpl )
+{
+ mEglImplementation = eglImpl;
+}
+
+Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject()
+{
+ DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
+ return new EglSyncObject(*mEglImplementation);
+}
+
+void EglSyncImplementation::DestroySyncObject(Integration::GlSyncAbstraction::SyncObject* syncObject)
+{
+ DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" );
+
+ // The abstraction's virtual destructor is protected, so that Core can't delete the sync objects
+ // directly (This object also needs removing from the mSyncObject container in the ARM
+ // implementation above). We therefore need to cast to the actual implementation object first.
+ EglSyncObject* eglSyncObject = static_cast<EglSyncObject*>(syncObject);
+ delete eglSyncObject;
+}
+
+void EglSyncImplementation::InitializeEglSync()
+{
+}
+
+#endif
+
+} // namespace Dali
+} // namespace Internal
+} // namespace Adaptor
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/gl-extensions.h>
+
+// EXTERNAL INCLUDES
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace ECoreX
+{
+
+GlExtensions::GlExtensions()
+:
+#if DALI_GLES_VERSION < 30
+#ifdef GL_EXT_discard_framebuffer
+ mGlDiscardFramebuffer( NULL ),
+#endif
+#ifdef GL_OES_get_program_binary
+ mGlGetProgramBinaryOES( NULL ),
+ mGlProgramBinaryOES( NULL ),
+#endif
+#endif // DALI_GLES_VERSION < 30
+ mInitialized( false )
+{
+}
+
+GlExtensions::~GlExtensions()
+{
+}
+
+#if DALI_GLES_VERSION < 30
+
+void GlExtensions::DiscardFrameBuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments)
+{
+ // initialize extension on first use as on some hw platforms a context
+ // has to be bound for the extensions to return correct pointer
+ if( !mInitialized )
+ {
+ Initialize();
+ }
+
+#ifdef GL_EXT_discard_framebuffer
+ if( mGlDiscardFramebuffer )
+ {
+ mGlDiscardFramebuffer(target, numAttachments, attachments);
+ }
+ else
+ {
+ DALI_LOG_ERROR("Error: glDiscardFramebufferEXT extension is not available\n");
+ }
+#endif
+}
+
+void GlExtensions::GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary)
+{
+ // initialize extension on first use as on some hw platforms a context
+ // has to be bound for the extensions to return correct pointer
+ if( !mInitialized )
+ {
+ Initialize();
+ }
+
+#ifdef GL_OES_get_program_binary
+ if (mGlGetProgramBinaryOES)
+ {
+ mGlGetProgramBinaryOES(program, bufSize, length, binaryFormat, binary);
+ }
+ else
+ {
+ DALI_LOG_ERROR("Error: glGetProgramBinaryOES extension is not available\n");
+ DALI_ASSERT_DEBUG(0);
+ }
+#endif
+}
+
+void GlExtensions::ProgramBinaryOES(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length)
+{
+ // initialize extension on first use as on some hw platforms a context
+ // has to be bound for the extensions to return correct pointer
+ if( !mInitialized )
+ {
+ Initialize();
+ }
+
+#ifdef GL_OES_get_program_binary
+ if (mGlProgramBinaryOES)
+ {
+ mGlProgramBinaryOES(program, binaryFormat, binary, length);
+ }
+ else
+ {
+ DALI_LOG_ERROR("Error: glProgramBinaryOES extension is not available\n");
+ DALI_ASSERT_DEBUG(0);
+ }
+#endif
+}
+
+void GlExtensions::Initialize()
+{
+ mInitialized = true;
+
+#ifdef GL_EXT_discard_framebuffer
+ mGlDiscardFramebuffer = reinterpret_cast< PFNGLDISCARDFRAMEBUFFEREXTPROC >( eglGetProcAddress("glDiscardFramebufferEXT") );
+#endif
+
+#ifdef GL_OES_get_program_binary
+ mGlGetProgramBinaryOES = reinterpret_cast< PFNGLGETPROGRAMBINARYOESPROC >( eglGetProcAddress("glGetProgramBinaryOES") );
+ mGlProgramBinaryOES = reinterpret_cast< PFNGLPROGRAMBINARYOESPROC >( eglGetProcAddress("glProgramBinaryOES") );
+#endif
+}
+
+#endif // DALI_GLES_VERSION < 30
+
+} // namespace ECoreX
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_GL_IMPLEMENTATION_H__
+#define __DALI_INTERNAL_GL_IMPLEMENTATION_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#ifndef DALI_GLES_VERSION
+#error "OpenGL ES version not specified"
+#endif
+
+#if DALI_GLES_VERSION >= 31
+#include <GLES3/gl31.h>
+#elif DALI_GLES_VERSION >= 30
+#include <GLES3/gl3.h>
+#else
+#include <cstdlib>
+#include <GLES2/gl2.h>
+#endif
+
+#include <dali/integration-api/gl-abstraction.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/gl-extensions.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * GlImplementation is a concrete implementation for GlAbstraction.
+ * The class provides an OpenGL-ES 2.0 implementation.
+ * The class is provided when creating the Integration::Core object.
+ */
+class GlImplementation: public Dali::Integration::GlAbstraction
+{
+
+public:
+ virtual ~GlImplementation() {}
+
+ void PreRender()
+ {
+ /* Do nothing in main implementation */
+ }
+
+ void PostRender()
+ {
+ /* Do nothing in main implementation */
+ }
+
+ /* OpenGL ES 2.0 */
+
+ void ActiveTexture (GLenum texture)
+ {
+ glActiveTexture(texture);
+ }
+
+ void AttachShader (GLuint program, GLuint shader)
+ {
+ glAttachShader(program,shader);
+ }
+
+ void BindAttribLocation (GLuint program, GLuint index, const char* name)
+ {
+ glBindAttribLocation(program,index,name);
+ }
+
+ void BindBuffer (GLenum target, GLuint buffer)
+ {
+ glBindBuffer(target,buffer);
+ }
+
+ void BindFramebuffer (GLenum target, GLuint framebuffer)
+ {
+ glBindFramebuffer(target,framebuffer);
+ }
+
+ void BindRenderbuffer (GLenum target, GLuint renderbuffer)
+ {
+ glBindRenderbuffer(target,renderbuffer);
+ }
+
+ void BindTexture (GLenum target, GLuint texture)
+ {
+ glBindTexture(target,texture);
+ }
+
+ void BlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+ {
+ glBlendColor(red,green,blue,alpha);
+ }
+
+ void BlendEquation ( GLenum mode )
+ {
+ glBlendEquation(mode);
+ }
+
+ void BlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha)
+ {
+ glBlendEquationSeparate(modeRGB,modeAlpha);
+ }
+
+ void BlendFunc (GLenum sfactor, GLenum dfactor)
+ {
+ glBlendFunc(sfactor,dfactor);
+ }
+
+ void BlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
+ {
+ glBlendFuncSeparate(srcRGB,dstRGB,srcAlpha,dstAlpha);
+ }
+
+ void BufferData (GLenum target, GLsizeiptr size, const void* data, GLenum usage)
+ {
+ glBufferData(target,size,data,usage);
+ }
+
+ void BufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void* data)
+ {
+ glBufferSubData(target,offset,size,data);
+ }
+
+ GLenum CheckFramebufferStatus (GLenum target)
+ {
+ return glCheckFramebufferStatus(target);
+ }
+
+ void Clear (GLbitfield mask)
+ {
+ glClear(mask);
+ }
+
+ void ClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+ {
+ glClearColor(red,green,blue,alpha);
+ }
+
+ void ClearDepthf (GLclampf depth)
+ {
+ glClearDepthf(depth);
+ }
+
+ void ClearStencil (GLint s)
+ {
+ glClearStencil(s);
+ }
+
+ void ColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+ {
+ glColorMask(red,green,blue,alpha);
+ }
+
+ void CompileShader (GLuint shader)
+ {
+ glCompileShader(shader);
+ }
+
+ void CompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
+ {
+ glCompressedTexImage2D(target,level,internalformat,width,height,border,imageSize,data);
+ }
+
+ void CompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
+ {
+ glCompressedTexSubImage2D(target,level,xoffset,yoffset,width,height,format,imageSize,data);
+ }
+
+ void CopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+ {
+ glCopyTexImage2D(target,level,internalformat,x,y,width,height,border);
+ }
+
+ void CopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+ {
+ glCopyTexSubImage2D(target,level,xoffset,yoffset,x,y,width,height);
+ }
+
+ GLuint CreateProgram (void)
+ {
+ return glCreateProgram();
+ }
+
+ GLuint CreateShader (GLenum type)
+ {
+ return glCreateShader(type);
+ }
+
+ void CullFace (GLenum mode)
+ {
+ glCullFace(mode);
+ }
+
+ void DeleteBuffers (GLsizei n, const GLuint* buffers)
+ {
+ glDeleteBuffers(n,buffers);
+ }
+
+ void DeleteFramebuffers (GLsizei n, const GLuint* framebuffers)
+ {
+ glDeleteFramebuffers(n,framebuffers);
+ }
+
+ void DeleteProgram (GLuint program)
+ {
+ glDeleteProgram(program);
+ }
+
+ void DeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers)
+ {
+ glDeleteRenderbuffers(n,renderbuffers);
+ }
+
+ void DeleteShader (GLuint shader)
+ {
+ glDeleteShader(shader);
+ }
+
+ void DeleteTextures (GLsizei n, const GLuint* textures)
+ {
+ glDeleteTextures(n,textures);
+ }
+
+ void DepthFunc (GLenum func)
+ {
+ glDepthFunc(func);
+ }
+
+ void DepthMask (GLboolean flag)
+ {
+ glDepthMask(flag);
+ }
+
+ void DepthRangef (GLclampf zNear, GLclampf zFar)
+ {
+ glDepthRangef(zNear,zFar);
+ }
+
+ void DetachShader (GLuint program, GLuint shader)
+ {
+ glDetachShader(program,shader);
+ }
+
+ void Disable (GLenum cap)
+ {
+ glDisable(cap);
+ }
+
+ void DisableVertexAttribArray (GLuint index)
+ {
+ glDisableVertexAttribArray(index);
+ }
+
+ void DrawArrays (GLenum mode, GLint first, GLsizei count)
+ {
+ glDrawArrays(mode,first,count);
+ }
+
+ void DrawElements (GLenum mode, GLsizei count, GLenum type, const void* indices)
+ {
+ glDrawElements(mode,count,type,indices);
+ }
+
+ void Enable (GLenum cap)
+ {
+ glEnable(cap);
+ }
+
+ void EnableVertexAttribArray (GLuint index)
+ {
+ glEnableVertexAttribArray(index);
+ }
+
+ void Finish (void)
+ {
+ glFinish();
+ }
+
+ void Flush (void)
+ {
+ glFlush();
+ }
+
+ void FramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
+ {
+ glFramebufferRenderbuffer(target,attachment,renderbuffertarget,renderbuffer);
+ }
+
+ void FramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
+ {
+ glFramebufferTexture2D(target,attachment,textarget,texture,level);
+ }
+
+ void FrontFace (GLenum mode)
+ {
+ glFrontFace(mode);
+ }
+
+ void GenBuffers (GLsizei n, GLuint* buffers)
+ {
+ glGenBuffers(n,buffers);
+ }
+
+ void GenerateMipmap (GLenum target)
+ {
+ glGenerateMipmap(target);
+ }
+
+ void GenFramebuffers (GLsizei n, GLuint* framebuffers)
+ {
+ glGenFramebuffers(n,framebuffers);
+ }
+
+ void GenRenderbuffers (GLsizei n, GLuint* renderbuffers)
+ {
+ glGenRenderbuffers(n,renderbuffers);
+ }
+
+ void GenTextures (GLsizei n, GLuint* textures)
+ {
+ glGenTextures(n,textures);
+ }
+
+ void GetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+ {
+ glGetActiveAttrib(program,index,bufsize,length,size,type,name);
+ }
+
+ void GetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+ {
+ glGetActiveUniform(program,index,bufsize,length,size,type,name);
+ }
+
+ void GetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
+ {
+ glGetAttachedShaders(program,maxcount,count,shaders);
+ }
+
+ int GetAttribLocation (GLuint program, const char* name)
+ {
+ return glGetAttribLocation(program,name);
+ }
+
+ void GetBooleanv (GLenum pname, GLboolean* params)
+ {
+ glGetBooleanv(pname,params);
+ }
+
+ void GetBufferParameteriv (GLenum target, GLenum pname, GLint* params)
+ {
+ glGetBufferParameteriv(target,pname,params);
+ }
+
+ GLenum GetError (void)
+ {
+ return glGetError();
+ }
+
+ void GetFloatv (GLenum pname, GLfloat* params)
+ {
+ glGetFloatv(pname,params);
+ }
+
+ void GetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params)
+ {
+ glGetFramebufferAttachmentParameteriv(target,attachment,pname,params);
+ }
+
+ void GetIntegerv (GLenum pname, GLint* params)
+ {
+ glGetIntegerv(pname,params);
+ }
+
+ void GetProgramiv (GLuint program, GLenum pname, GLint* params)
+ {
+ glGetProgramiv(program,pname,params);
+ }
+
+ void GetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
+ {
+ glGetProgramInfoLog(program,bufsize,length,infolog);
+ }
+
+ void GetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params)
+ {
+ glGetRenderbufferParameteriv(target,pname,params);
+ }
+
+ void GetShaderiv (GLuint shader, GLenum pname, GLint* params)
+ {
+ glGetShaderiv(shader,pname,params);
+ }
+
+ void GetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
+ {
+ glGetShaderInfoLog(shader,bufsize,length,infolog);
+ }
+
+ void GetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
+ {
+ glGetShaderPrecisionFormat(shadertype,precisiontype,range,precision);
+ }
+
+ void GetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
+ {
+ glGetShaderSource(shader,bufsize,length,source);
+ }
+
+ const GLubyte* GetString (GLenum name)
+ {
+ return glGetString(name);
+ }
+
+ void GetTexParameterfv (GLenum target, GLenum pname, GLfloat* params)
+ {
+ glGetTexParameterfv(target,pname,params);
+ }
+
+ void GetTexParameteriv (GLenum target, GLenum pname, GLint* params)
+ {
+ glGetTexParameteriv(target,pname,params);
+ }
+
+ void GetUniformfv (GLuint program, GLint location, GLfloat* params)
+ {
+ glGetUniformfv(program,location,params);
+ }
+
+ void GetUniformiv (GLuint program, GLint location, GLint* params)
+ {
+ glGetUniformiv(program,location,params);
+ }
+
+ int GetUniformLocation (GLuint program, const char* name)
+ {
+ return glGetUniformLocation(program,name);
+ }
+
+ void GetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params)
+ {
+ glGetVertexAttribfv(index,pname,params);
+ }
+
+ void GetVertexAttribiv (GLuint index, GLenum pname, GLint* params)
+ {
+ glGetVertexAttribiv(index,pname,params);
+ }
+
+ void GetVertexAttribPointerv (GLuint index, GLenum pname, void** pointer)
+ {
+ glGetVertexAttribPointerv(index,pname,pointer);
+ }
+
+ void Hint (GLenum target, GLenum mode)
+ {
+ glHint(target,mode);
+ }
+
+ GLboolean IsBuffer (GLuint buffer)
+ {
+ return glIsBuffer(buffer);
+ }
+
+ GLboolean IsEnabled (GLenum cap)
+ {
+ return glIsEnabled(cap);
+ }
+
+ GLboolean IsFramebuffer (GLuint framebuffer)
+ {
+ return glIsFramebuffer(framebuffer);
+ }
+
+ GLboolean IsProgram (GLuint program)
+ {
+ return glIsProgram(program);
+ }
+
+ GLboolean IsRenderbuffer (GLuint renderbuffer)
+ {
+ return glIsRenderbuffer(renderbuffer);
+ }
+
+ GLboolean IsShader (GLuint shader)
+ {
+ return glIsShader(shader);
+ }
+
+ GLboolean IsTexture (GLuint texture)
+ {
+ return glIsTexture(texture);
+ }
+
+ void LineWidth (GLfloat width)
+ {
+ glLineWidth(width);
+ }
+
+ void LinkProgram (GLuint program)
+ {
+ glLinkProgram(program);
+ }
+
+ void PixelStorei (GLenum pname, GLint param)
+ {
+ glPixelStorei(pname,param);
+ }
+
+ void PolygonOffset (GLfloat factor, GLfloat units)
+ {
+ glPolygonOffset(factor,units);
+ }
+
+ void ReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels)
+ {
+ glReadPixels(x,y,width,height,format,type,pixels);
+ }
+
+ void ReleaseShaderCompiler (void)
+ {
+ glReleaseShaderCompiler();
+ }
+
+ void RenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
+ {
+ glRenderbufferStorage(target,internalformat,width,height);
+ }
+
+ void SampleCoverage (GLclampf value, GLboolean invert)
+ {
+ glSampleCoverage(value,invert);
+ }
+
+ void Scissor (GLint x, GLint y, GLsizei width, GLsizei height)
+ {
+ glScissor(x,y,width,height);
+ }
+
+ void ShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length)
+ {
+ glShaderBinary(n,shaders,binaryformat,binary,length);
+ }
+
+ void ShaderSource (GLuint shader, GLsizei count, const char** string, const GLint* length)
+ {
+ glShaderSource(shader,count,string,length);
+ }
+
+ void StencilFunc (GLenum func, GLint ref, GLuint mask)
+ {
+ glStencilFunc(func,ref,mask);
+ }
+
+ void StencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask)
+ {
+ glStencilFuncSeparate(face,func,ref,mask);
+ }
+
+ void StencilMask (GLuint mask)
+ {
+ glStencilMask(mask);
+ }
+
+ void StencilMaskSeparate (GLenum face, GLuint mask)
+ {
+ glStencilMaskSeparate(face,mask);
+ }
+
+ void StencilOp (GLenum fail, GLenum zfail, GLenum zpass)
+ {
+ glStencilOp(fail,zfail,zpass);
+ }
+
+ void StencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
+ {
+ glStencilOpSeparate(face,fail,zfail,zpass);
+ }
+
+ void TexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels)
+ {
+ glTexImage2D(target,level,internalformat,width,height,border,format,type,pixels);
+ }
+
+ void TexParameterf (GLenum target, GLenum pname, GLfloat param)
+ {
+ glTexParameterf(target,pname,param);
+ }
+
+ void TexParameterfv (GLenum target, GLenum pname, const GLfloat* params)
+ {
+ glTexParameterfv(target,pname,params);
+ }
+
+ void TexParameteri (GLenum target, GLenum pname, GLint param)
+ {
+ glTexParameteri(target,pname,param);
+ }
+
+ void TexParameteriv (GLenum target, GLenum pname, const GLint* params)
+ {
+ glTexParameteriv(target,pname,params);
+ }
+
+ void TexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels)
+ {
+ glTexSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);
+ }
+
+ void Uniform1f (GLint location, GLfloat x)
+ {
+ glUniform1f(location,x);
+ }
+
+ void Uniform1fv (GLint location, GLsizei count, const GLfloat* v)
+ {
+ glUniform1fv(location,count,v);
+ }
+
+ void Uniform1i (GLint location, GLint x)
+ {
+ glUniform1i(location,x);
+ }
+
+ void Uniform1iv (GLint location, GLsizei count, const GLint* v)
+ {
+ glUniform1iv(location,count,v);
+ }
+
+ void Uniform2f (GLint location, GLfloat x, GLfloat y)
+ {
+ glUniform2f(location,x,y);
+ }
+
+ void Uniform2fv (GLint location, GLsizei count, const GLfloat* v)
+ {
+ glUniform2fv(location,count,v);
+ }
+
+ void Uniform2i (GLint location, GLint x, GLint y)
+ {
+ glUniform2i(location,x,y);
+ }
+
+ void Uniform2iv (GLint location, GLsizei count, const GLint* v)
+ {
+ glUniform2iv(location,count,v);
+ }
+
+ void Uniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z)
+ {
+ glUniform3f(location,x,y,z);
+ }
+
+ void Uniform3fv (GLint location, GLsizei count, const GLfloat* v)
+ {
+ glUniform3fv(location,count,v);
+ }
+
+ void Uniform3i (GLint location, GLint x, GLint y, GLint z)
+ {
+ glUniform3i(location,x,y,z);
+ }
+
+ void Uniform3iv (GLint location, GLsizei count, const GLint* v)
+ {
+ glUniform3iv(location,count,v);
+ }
+
+ void Uniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+ {
+ glUniform4f(location,x,y,z,w);
+ }
+
+ void Uniform4fv (GLint location, GLsizei count, const GLfloat* v)
+ {
+ glUniform4fv(location,count,v);
+ }
+
+ void Uniform4i (GLint location, GLint x, GLint y, GLint z, GLint w)
+ {
+ glUniform4i(location,x,y,z,w);
+ }
+
+ void Uniform4iv (GLint location, GLsizei count, const GLint* v)
+ {
+ glUniform4iv(location,count,v);
+ }
+
+ void UniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+ glUniformMatrix2fv(location,count,transpose,value);
+ }
+
+ void UniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+ glUniformMatrix3fv(location,count,transpose,value);
+ }
+
+ void UniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+ glUniformMatrix4fv(location,count,transpose,value);
+ }
+
+ void UseProgram (GLuint program)
+ {
+ glUseProgram(program);
+ }
+
+ void ValidateProgram (GLuint program)
+ {
+ glValidateProgram(program);
+ }
+
+ void VertexAttrib1f (GLuint indx, GLfloat x)
+ {
+ glVertexAttrib1f(indx,x);
+ }
+
+ void VertexAttrib1fv (GLuint indx, const GLfloat* values)
+ {
+ glVertexAttrib1fv(indx,values);
+ }
+
+ void VertexAttrib2f (GLuint indx, GLfloat x, GLfloat y)
+ {
+ glVertexAttrib2f(indx,x,y);
+ }
+
+ void VertexAttrib2fv (GLuint indx, const GLfloat* values)
+ {
+ glVertexAttrib2fv(indx,values);
+ }
+
+ void VertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z)
+ {
+ glVertexAttrib3f(indx,x,y,z);
+ }
+
+ void VertexAttrib3fv (GLuint indx, const GLfloat* values)
+ {
+ glVertexAttrib3fv(indx,values);
+ }
+
+ void VertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+ {
+ glVertexAttrib4f(indx,x,y,z,w);
+ }
+
+ void VertexAttrib4fv (GLuint indx, const GLfloat* values)
+ {
+ glVertexAttrib4fv(indx,values);
+ }
+
+ void VertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
+ {
+ glVertexAttribPointer(indx,size,type,normalized,stride,ptr);
+ }
+
+ void Viewport (GLint x, GLint y, GLsizei width, GLsizei height)
+ {
+ glViewport(x,y,width,height);
+ }
+
+ /* OpenGL ES 3.0 */
+
+ void ReadBuffer(GLenum mode)
+ {
+#if DALI_GLES_VERSION >= 30
+ glReadBuffer(mode);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDrawRangeElements(mode,start,end,count,type,indices);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels)
+ {
+#if DALI_GLES_VERSION >= 30
+ glTexImage3D(target,level,internalformat,width,height,depth,border,format,type,pixels);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels)
+ {
+#if DALI_GLES_VERSION >= 30
+ glTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,type,pixels);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+ {
+#if DALI_GLES_VERSION >= 30
+ glCopyTexSubImage3D(target,level,xoffset,yoffset,zoffset,x,y,width,height);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data)
+ {
+#if DALI_GLES_VERSION >= 30
+ glCompressedTexImage3D(target,level,internalformat,width,height,depth,border,imageSize,data);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data)
+ {
+#if DALI_GLES_VERSION >= 30
+ glCompressedTexSubImage3D(target,level,xoffset,yoffset,zoffset,width,height,depth,format,imageSize,data);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GenQueries(GLsizei n, GLuint* ids)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGenQueries(n,ids);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DeleteQueries(GLsizei n, const GLuint* ids)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDeleteQueries(n,ids);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean IsQuery(GLuint id)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glIsQuery(id);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BeginQuery(GLenum target, GLuint id)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBeginQuery(target,id);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void EndQuery(GLenum target)
+ {
+#if DALI_GLES_VERSION >= 30
+ glEndQuery(target);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetQueryiv(GLenum target, GLenum pname, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetQueryiv(target,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetQueryObjectuiv(id,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean UnmapBuffer(GLenum target)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glUnmapBuffer(target);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetBufferPointerv(target,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DrawBuffers(GLsizei n, const GLenum* bufs)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDrawBuffers(n,bufs);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix2x3fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix3x2fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix2x4fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix4x2fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix3x4fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformMatrix4x3fv(location,count,transpose,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBlitFramebuffer(srcX0,srcY0,srcX1,srcY1,dstX0,dstY0,dstX1,dstY1,mask,filter);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
+ {
+#if DALI_GLES_VERSION >= 30
+ glRenderbufferStorageMultisample(target,samples,internalformat,width,height);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)
+ {
+#if DALI_GLES_VERSION >= 30
+ glFramebufferTextureLayer(target,attachment,texture,level,layer);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glMapBufferRange(target,offset,length,access);
+#else
+ return NULL;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
+ {
+#if DALI_GLES_VERSION >= 30
+ glFlushMappedBufferRange(target,offset,length);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BindVertexArray(GLuint array)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBindVertexArray(array);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DeleteVertexArrays(GLsizei n, const GLuint* arrays)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDeleteVertexArrays(n,arrays);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GenVertexArrays(GLsizei n, GLuint* arrays)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGenVertexArrays(n,arrays);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean IsVertexArray(GLuint array)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glIsVertexArray(array);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetIntegeri_v(GLenum target, GLuint index, GLint* data)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetIntegeri_v(target,index,data);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BeginTransformFeedback(GLenum primitiveMode)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBeginTransformFeedback(primitiveMode);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void EndTransformFeedback(void)
+ {
+#if DALI_GLES_VERSION >= 30
+ glEndTransformFeedback();
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBindBufferRange(target,index,buffer,offset,size);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BindBufferBase(GLenum target, GLuint index, GLuint buffer)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBindBufferBase(target,index,buffer);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode)
+ {
+#if DALI_GLES_VERSION >= 30
+ glTransformFeedbackVaryings(program,count,varyings,bufferMode);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetTransformFeedbackVarying(program,index,bufSize,length,size,type,name);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribIPointer(index,size,type,stride,pointer);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetVertexAttribIiv(index,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetVertexAttribIuiv(index,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribI4i(index,x,y,z,w);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribI4ui(index,x,y,z,w);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribI4iv(GLuint index, const GLint* v)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribI4iv(index,v);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribI4uiv(GLuint index, const GLuint* v)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribI4uiv(index,v);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetUniformuiv(GLuint program, GLint location, GLuint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetUniformuiv(program,location,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLint GetFragDataLocation(GLuint program, const GLchar *name)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glGetFragDataLocation(program,name);
+#else
+ return -1;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform1ui(GLint location, GLuint v0)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform1ui(location,v0);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform2ui(GLint location, GLuint v0, GLuint v1)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform2ui(location,v0,v1);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform3ui(location,v0,v1,v2);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform4ui(location,v0,v1,v2,v3);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform1uiv(GLint location, GLsizei count, const GLuint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform1uiv(location,count,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform2uiv(GLint location, GLsizei count, const GLuint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform2uiv(location,count,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform3uiv(GLint location, GLsizei count, const GLuint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform3uiv(location,count,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void Uniform4uiv(GLint location, GLsizei count, const GLuint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniform4uiv(location,count,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glClearBufferiv(buffer,drawbuffer,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glClearBufferuiv(buffer,drawbuffer,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glClearBufferfv(buffer,drawbuffer,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)
+ {
+#if DALI_GLES_VERSION >= 30
+ glClearBufferfi(buffer,drawbuffer,depth,stencil);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ const GLubyte* GetStringi(GLenum name, GLuint index)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glGetStringi(name,index);
+#else
+ return NULL;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size)
+ {
+#if DALI_GLES_VERSION >= 30
+ glCopyBufferSubData(readTarget,writeTarget,readOffset,writeOffset,size);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetUniformIndices(program,uniformCount,uniformNames,uniformIndices);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetActiveUniformsiv(program,uniformCount,uniformIndices,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glGetUniformBlockIndex(program,uniformBlockName);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetActiveUniformBlockiv(program,uniformBlockIndex,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetActiveUniformBlockName(program,uniformBlockIndex,bufSize,length,uniformBlockName);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding)
+ {
+#if DALI_GLES_VERSION >= 30
+ glUniformBlockBinding(program,uniformBlockIndex,uniformBlockBinding);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDrawArraysInstanced(mode,first,count,instanceCount);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDrawElementsInstanced(mode,count,type,indices,instanceCount);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLsync FenceSync(GLenum condition, GLbitfield flags)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glFenceSync(condition,flags);
+#else
+ return NULL;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean IsSync(GLsync sync)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glIsSync(sync);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DeleteSync(GLsync sync)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDeleteSync(sync);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glClientWaitSync(sync,flags,timeout);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout)
+ {
+#if DALI_GLES_VERSION >= 30
+ glWaitSync(sync,flags,timeout);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetInteger64v(GLenum pname, GLint64* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetInteger64v(pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetSynciv(sync,pname,bufSize,length,values);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetInteger64i_v(GLenum target, GLuint index, GLint64* data)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetInteger64i_v(target,index,data);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetBufferParameteri64v(target,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GenSamplers(GLsizei count, GLuint* samplers)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGenSamplers(count,samplers);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DeleteSamplers(GLsizei count, const GLuint* samplers)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDeleteSamplers(count,samplers);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean IsSampler(GLuint sampler)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glIsSampler(sampler);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BindSampler(GLuint unit, GLuint sampler)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBindSampler(unit,sampler);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void SamplerParameteri(GLuint sampler, GLenum pname, GLint param)
+ {
+#if DALI_GLES_VERSION >= 30
+ glSamplerParameteri(sampler,pname,param);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param)
+ {
+#if DALI_GLES_VERSION >= 30
+ glSamplerParameteriv(sampler,pname,param);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
+ {
+#if DALI_GLES_VERSION >= 30
+ glSamplerParameterf(sampler,pname,param);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param)
+ {
+#if DALI_GLES_VERSION >= 30
+ glSamplerParameterfv(sampler,pname,param);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetSamplerParameteriv(sampler,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetSamplerParameterfv(sampler,pname,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void VertexAttribDivisor(GLuint index, GLuint divisor)
+ {
+#if DALI_GLES_VERSION >= 30
+ glVertexAttribDivisor(index,divisor);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void BindTransformFeedback(GLenum target, GLuint id)
+ {
+#if DALI_GLES_VERSION >= 30
+ glBindTransformFeedback(target,id);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids)
+ {
+#if DALI_GLES_VERSION >= 30
+ glDeleteTransformFeedbacks(n,ids);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GenTransformFeedbacks(GLsizei n, GLuint* ids)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGenTransformFeedbacks(n,ids);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ GLboolean IsTransformFeedback(GLuint id)
+ {
+#if DALI_GLES_VERSION >= 30
+ return glIsTransformFeedback(id);
+#else
+ return 0;
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void PauseTransformFeedback(void)
+ {
+#if DALI_GLES_VERSION >= 30
+ glPauseTransformFeedback();
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ResumeTransformFeedback(void)
+ {
+#if DALI_GLES_VERSION >= 30
+ glResumeTransformFeedback();
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary)
+ {
+#if DALI_GLES_VERSION >= 30
+ // if OpenGL ES 2.0 compatibility is need this can be implemented with
+ // glGetProgramBinaryOES
+ glGetProgramBinary(program,bufSize,length,binaryFormat,binary);
+#else
+ mGlExtensions.GetProgramBinaryOES(program, bufSize, length, binaryFormat, binary);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length)
+ {
+#if DALI_GLES_VERSION >= 30
+ // if OpenGL ES 2.0 compatibility is need this can be implemented with
+ // glProgramBinaryOES
+ glProgramBinary(program,binaryFormat,binary,length);
+#else
+ mGlExtensions.ProgramBinaryOES(program, binaryFormat, binary, length);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void ProgramParameteri(GLuint program, GLenum pname, GLint value)
+ {
+#if DALI_GLES_VERSION >= 30
+ glProgramParameteri(program,pname,value);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments)
+ {
+#if DALI_GLES_VERSION >= 30
+ glInvalidateFramebuffer(target,numAttachments,attachments);
+#else
+ mGlExtensions.DiscardFrameBuffer(target, numAttachments, attachments);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height)
+ {
+#if DALI_GLES_VERSION >= 30
+ glInvalidateSubFramebuffer(target,numAttachments,attachments,x,y,width,height);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
+ {
+#if DALI_GLES_VERSION >= 30
+ glTexStorage2D(target,levels,internalformat,width,height);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)
+ {
+#if DALI_GLES_VERSION >= 30
+ glTexStorage3D(target,levels,internalformat,width,height,depth);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+ void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params)
+ {
+#if DALI_GLES_VERSION >= 30
+ glGetInternalformativ(target,internalformat,pname,bufSize,params);
+#endif // DALI_GLES_VERSION >= 30
+ }
+
+private:
+ ECoreX::GlExtensions mGlExtensions;
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_GL_IMPLEMENTATION_H__
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/gles20/gl-proxy-implementation.h>
+
+// EXTERNAL INCLUDES
+#include <math.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+
+namespace
+{
+const int NUM_FRAMES_PER_SECOND( 60 );
+}
+
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+Sampler::Sampler( const char* description )
+: mDescription( description ),
+ mAccumulatedSquare( 0 ),
+ mAccumulated( 0 ),
+ mNumSamples( 0 ),
+ mMin( 0.0f ),
+ mMax( 0.0f ),
+ mCurrentFrameCount( 0 )
+{
+}
+
+void Sampler::Increment()
+{
+ mCurrentFrameCount++;
+}
+
+void Sampler::Reset()
+{
+ mAccumulatedSquare = 0;
+ mAccumulated = 0;
+ mNumSamples = 0;
+ mMin = 0.0f;
+ mMax = 0.0f;
+ mCurrentFrameCount = 0;
+}
+
+void Sampler::Accumulate()
+{
+ if( mNumSamples == 0 )
+ {
+ mMin = mCurrentFrameCount;
+ mMax = mCurrentFrameCount;
+ }
+ else
+ {
+ if( mCurrentFrameCount < mMin )
+ {
+ mMin = mCurrentFrameCount;
+ }
+ if( mCurrentFrameCount > mMax )
+ {
+ mMax = mCurrentFrameCount;
+ }
+ }
+
+ mNumSamples++;
+
+ mAccumulated += mCurrentFrameCount;
+ mAccumulatedSquare += ( mCurrentFrameCount * mCurrentFrameCount );
+ mCurrentFrameCount = 0;
+}
+const char* Sampler::GetDescription() const
+{
+ return mDescription;
+}
+
+float Sampler::GetMeanValue() const
+{
+ float meanValue = 0;
+ if( mNumSamples > 0 )
+ {
+ meanValue = static_cast<double>( mAccumulated ) / static_cast<double>( mNumSamples );
+ }
+ return meanValue;
+}
+
+float Sampler::GetStandardDeviation() const
+{
+ float standardDeviation = 0.0f;
+ if( mNumSamples > 0 )
+ {
+ standardDeviation = sqrtf( mNumSamples * mAccumulatedSquare - ( mAccumulated * mAccumulated ) ) / mNumSamples;
+ }
+ return standardDeviation;
+}
+
+float Sampler::GetMin() const
+{
+ return mMin;
+}
+
+float Sampler::GetMax() const
+{
+ return mMax;
+}
+
+uint64_t Sampler::GetCount() const
+{
+ return mAccumulated;
+}
+
+ObjectCounter::ObjectCounter( const char* description )
+: mDescription( description ),
+ mCount( 0 ),
+ mPeak( 0 )
+{}
+
+void ObjectCounter::Increment()
+{
+ ++mCount;
+ if( mCount > mPeak )
+ {
+ mPeak = mCount;
+ }
+}
+
+void ObjectCounter::Decrement()
+{
+ --mCount;
+}
+
+unsigned int ObjectCounter::GetCount() const
+{
+ return mCount;
+}
+unsigned int ObjectCounter::GetPeak() const
+{
+ return mPeak;
+}
+
+const char* ObjectCounter::GetDescription() const
+{
+ return mDescription;
+}
+
+GlProxyImplementation::GlProxyImplementation( EnvironmentOptions& environmentOptions )
+: mEnvironmentOptions( environmentOptions ),
+ mActiveTextureSampler( "ActiveTexture calls" ),
+ mClearSampler( "Clear calls" ),
+ mBindBufferSampler( "Bind buffers" ),
+ mBindTextureSampler( "Bind textures" ),
+ mDrawSampler( "Draw calls" ),
+ mUniformSampler( "Uniform sets" ),
+ mUseProgramSampler( "Used programs" ),
+ mBufferCount( "Buffer Count" ),
+ mTextureCount( "Texture Count" ),
+ mProgramCount( "Program Count" ),
+ mCurrentFrameCount( 0 ),
+ mTotalFrameCount( 0 )
+{
+}
+
+GlProxyImplementation::~GlProxyImplementation()
+{
+}
+
+void GlProxyImplementation::PreRender()
+{
+}
+
+void GlProxyImplementation::PostRender()
+{
+ // Accumulate counts in each sampler
+ AccumulateSamples();
+
+ // When we reach the desired frame count, output the averages from the samples
+ mTotalFrameCount++;
+ mCurrentFrameCount++;
+
+ if( mCurrentFrameCount >= mEnvironmentOptions.GetGlesCallTime() * NUM_FRAMES_PER_SECOND )
+ {
+ mCurrentFrameCount = 0;
+ LogResults();
+
+ if( !mEnvironmentOptions.GetGlesCallAccumulate() )
+ {
+ ResetSamplers();
+ }
+ }
+}
+
+void GlProxyImplementation::Clear( GLbitfield mask )
+{
+ mClearSampler.Increment();
+ GlImplementation::Clear(mask);
+}
+
+void GlProxyImplementation::GenBuffers(GLsizei n, GLuint* buffers)
+{
+ mBufferCount.Increment();
+ GlImplementation::GenBuffers( n, buffers );
+}
+
+void GlProxyImplementation::DeleteBuffers( GLsizei n, const GLuint* buffers )
+{
+ mBufferCount.Decrement();
+ GlImplementation::DeleteBuffers( n, buffers );
+}
+
+void GlProxyImplementation::BindBuffer( GLenum target, GLuint buffer )
+{
+ mBindBufferSampler.Increment();
+ GlImplementation::BindBuffer( target, buffer );
+}
+
+void GlProxyImplementation::GenTextures( GLsizei n, GLuint* textures )
+{
+ mTextureCount.Increment();
+ GlImplementation::GenTextures( n, textures );
+}
+
+void GlProxyImplementation::DeleteTextures( GLsizei n, const GLuint* textures )
+{
+ mTextureCount.Decrement();
+ GlImplementation::DeleteTextures( n, textures );
+}
+
+void GlProxyImplementation::ActiveTexture( GLenum texture )
+{
+ mActiveTextureSampler.Increment();
+ GlImplementation::ActiveTexture( texture );
+}
+
+void GlProxyImplementation::BindTexture( GLenum target, GLuint texture )
+{
+ mBindTextureSampler.Increment();
+ GlImplementation::BindTexture(target,texture);
+}
+
+void GlProxyImplementation::DrawArrays( GLenum mode, GLint first, GLsizei count )
+{
+ mDrawSampler.Increment();
+ GlImplementation::DrawArrays( mode, first, count );
+}
+
+void GlProxyImplementation::DrawElements( GLenum mode, GLsizei count, GLenum type, const void* indices )
+{
+ mDrawSampler.Increment();
+ GlImplementation::DrawElements( mode, count, type, indices );
+}
+
+void GlProxyImplementation::Uniform1f( GLint location, GLfloat x )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform1f( location, x );
+}
+
+void GlProxyImplementation::Uniform1fv( GLint location, GLsizei count, const GLfloat* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform1fv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform1i( GLint location, GLint x )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform1i( location, x );
+}
+
+void GlProxyImplementation::Uniform1iv( GLint location, GLsizei count, const GLint* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform1iv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform2f( GLint location, GLfloat x, GLfloat y)
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform2f( location, x, y );
+}
+
+void GlProxyImplementation::Uniform2fv( GLint location, GLsizei count, const GLfloat* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform2fv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform2i( GLint location, GLint x, GLint y )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform2i( location, x, y );
+}
+
+void GlProxyImplementation::Uniform2iv( GLint location, GLsizei count, const GLint* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform2iv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform3f( GLint location, GLfloat x, GLfloat y, GLfloat z )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform3f( location, x, y, z );
+}
+
+void GlProxyImplementation::Uniform3fv( GLint location, GLsizei count, const GLfloat* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform3fv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform3i( GLint location, GLint x, GLint y, GLint z )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform3i( location, x, y, z );
+}
+
+void GlProxyImplementation::Uniform3iv( GLint location, GLsizei count, const GLint* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform3iv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform4f( GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform4f( location, x, y, z, w );
+}
+
+void GlProxyImplementation::Uniform4fv( GLint location, GLsizei count, const GLfloat* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform4fv( location, count, v );
+}
+
+void GlProxyImplementation::Uniform4i( GLint location, GLint x, GLint y, GLint z, GLint w )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform4i( location, x, y, z, w );
+}
+
+void GlProxyImplementation::Uniform4iv( GLint location, GLsizei count, const GLint* v )
+{
+ mUniformSampler.Increment();
+ GlImplementation::Uniform4iv( location, count, v );
+}
+
+void GlProxyImplementation::UniformMatrix2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
+{
+ mUniformSampler.Increment();
+ GlImplementation::UniformMatrix2fv( location, count, transpose, value );
+}
+
+void GlProxyImplementation::UniformMatrix3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
+{
+ mUniformSampler.Increment();
+ GlImplementation::UniformMatrix3fv( location, count, transpose, value );
+}
+
+void GlProxyImplementation::UniformMatrix4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value )
+{
+ mUniformSampler.Increment();
+ GlImplementation::UniformMatrix4fv( location, count, transpose, value);
+}
+
+GLuint GlProxyImplementation::CreateProgram( void )
+{
+ mProgramCount.Increment();
+ return GlImplementation::CreateProgram();
+}
+
+void GlProxyImplementation::DeleteProgram( GLuint program )
+{
+ mProgramCount.Decrement();
+ GlImplementation::DeleteProgram( program );
+}
+
+void GlProxyImplementation::UseProgram( GLuint program )
+{
+ mUseProgramSampler.Increment();
+ GlImplementation::UseProgram( program );
+}
+
+void GlProxyImplementation::AccumulateSamples()
+{
+ // Accumulate counts in each sampler
+ mActiveTextureSampler.Accumulate();
+ mClearSampler.Accumulate();
+ mBindBufferSampler.Accumulate();
+ mBindTextureSampler.Accumulate();
+ mDrawSampler.Accumulate();
+ mUniformSampler.Accumulate();
+ mUseProgramSampler.Accumulate();
+}
+
+void GlProxyImplementation::LogResults()
+{
+ Debug::LogMessage( Debug::DebugInfo, "OpenGL ES statistics sampled over %d frames) operations per frame:\n", mTotalFrameCount );
+ LogCalls( mActiveTextureSampler );
+ LogCalls( mClearSampler );
+ LogCalls( mBindBufferSampler );
+ LogCalls( mBindTextureSampler );
+ LogCalls( mDrawSampler );
+ LogCalls( mUniformSampler );
+ LogCalls( mUseProgramSampler );
+ Debug::LogMessage( Debug::DebugInfo, "OpenGL ES Object Count:\n" );
+ LogObjectCounter( mBufferCount );
+ LogObjectCounter( mTextureCount );
+ LogObjectCounter( mProgramCount );
+}
+
+void GlProxyImplementation::LogCalls( const Sampler& sampler )
+{
+ Debug::LogMessage( Debug::DebugInfo, " %s : Mean %5.2f (Min:%5.2f, Max:%5.2f, StdDev:%5.2f, Actual:%d)\n",
+ sampler.GetDescription(),
+ sampler.GetMeanValue(), sampler.GetMin(), sampler.GetMax(),
+ sampler.GetStandardDeviation(),
+ sampler.GetCount() );
+}
+
+void GlProxyImplementation::LogObjectCounter( const ObjectCounter& sampler )
+{
+ Debug::LogMessage( Debug::DebugInfo, " %s : %u (Peak:%u)\n",
+ sampler.GetDescription(),
+ sampler.GetCount(),
+ sampler.GetPeak() );
+}
+
+void GlProxyImplementation::ResetSamplers()
+{
+ mActiveTextureSampler.Reset();
+ mClearSampler.Reset();
+ mBindBufferSampler.Reset();
+ mBindTextureSampler.Reset();
+ mDrawSampler.Reset();
+ mUniformSampler.Reset();
+ mUseProgramSampler.Reset();
+ mTotalFrameCount = 0;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
+#define __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/gl-implementation.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class EnvironmentOptions;
+
+/**
+ * Helper class to calculate the statistics for Open GLES calls
+ */
+class Sampler
+{
+public:
+
+ /**
+ * Constructor
+ * @param description to write to the log
+ */
+ Sampler( const char* description );
+
+ /**
+ * Increment the counter for this frame
+ */
+ void Increment();
+
+ /**
+ * Reset the counter
+ */
+ void Reset();
+
+ /**
+ * Accumulate the count onto statistics
+ */
+ void Accumulate();
+
+ /**
+ * @return the description of the sampler
+ */
+ const char* GetDescription() const;
+
+ /**
+ * @return the mean value
+ */
+ float GetMeanValue() const;
+
+ /**
+ * @return the standard deviation
+ */
+ float GetStandardDeviation() const;
+
+ /**
+ * @return the minimum value
+ */
+ float GetMin() const;
+
+ /**
+ * @return the maximum value
+ */
+ float GetMax() const;
+
+ /**
+ * @return the current count
+ */
+ uint64_t GetCount() const;
+
+private: // Data
+
+ const char* mDescription;
+
+ uint64_t mAccumulatedSquare;
+ uint64_t mAccumulated;
+ uint64_t mNumSamples;
+ float mMin;
+ float mMax;
+ unsigned int mCurrentFrameCount;
+};
+
+/**
+ * Helper class to calculate number of OpenGL objects
+ */
+class ObjectCounter
+{
+public:
+ ObjectCounter( const char* description );
+
+ /**
+ * Increment the counter
+ */
+ void Increment();
+
+ /**
+ * Decrement the counter
+ */
+ void Decrement();
+
+ /**
+ * @return The current number of objects
+ */
+ unsigned int GetCount() const;
+
+ /**
+ * @return The maximum number of objects created
+ */
+ unsigned int GetPeak() const;
+
+ /**
+ * @return the description of the sampler
+ */
+ const char* GetDescription() const;
+
+private:
+ const char* mDescription;
+ unsigned int mCount;
+ unsigned int mPeak;
+};
+
+/**
+ * GlProxyImplementation is a wrapper for the concrete implementation
+ * of GlAbstraction that also gathers statistical information.
+ */
+class GlProxyImplementation : public GlImplementation
+{
+public:
+
+ /**
+ * Constructor
+ * @param environmentOptions to check how often to log results
+ */
+ GlProxyImplementation( EnvironmentOptions& environmentOptions );
+
+ /**
+ * Virtual destructor
+ */
+ virtual ~GlProxyImplementation();
+
+ /**
+ * @copydoc GlAbstraction::PreRender();
+ */
+ virtual void PreRender();
+
+ /**
+ * @copydoc GlAbstraction::PostRender();
+ */
+ virtual void PostRender();
+
+ /* OpenGL ES 2.0 API */
+ virtual void Clear( GLbitfield mask );
+
+ virtual void GenBuffers( GLsizei n, GLuint* buffers );
+ virtual void DeleteBuffers( GLsizei n, const GLuint* buffers );
+ virtual void BindBuffer( GLenum target, GLuint buffer );
+
+ virtual void GenTextures( GLsizei n, GLuint* textures );
+ virtual void DeleteTextures( GLsizei n, const GLuint* textures );
+ virtual void ActiveTexture( GLenum texture );
+ virtual void BindTexture( GLenum target, GLuint texture );
+
+ virtual void DrawArrays( GLenum mode, GLint first, GLsizei count );
+ virtual void DrawElements( GLenum mode, GLsizei count, GLenum type, const void* indices );
+
+ virtual void Uniform1f ( GLint location, GLfloat x );
+ virtual void Uniform1fv( GLint location, GLsizei count, const GLfloat* v );
+ virtual void Uniform1i ( GLint location, GLint x );
+ virtual void Uniform1iv( GLint location, GLsizei count, const GLint* v );
+ virtual void Uniform2f ( GLint location, GLfloat x, GLfloat y );
+ virtual void Uniform2fv( GLint location, GLsizei count, const GLfloat* v );
+ virtual void Uniform2i ( GLint location, GLint x, GLint y );
+ virtual void Uniform2iv( GLint location, GLsizei count, const GLint* v );
+ virtual void Uniform3f ( GLint location, GLfloat x, GLfloat y, GLfloat z );
+ virtual void Uniform3fv( GLint location, GLsizei count, const GLfloat* v );
+ virtual void Uniform3i ( GLint location, GLint x, GLint y, GLint z );
+ virtual void Uniform3iv( GLint location, GLsizei count, const GLint* v );
+ virtual void Uniform4f ( GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w );
+ virtual void Uniform4fv( GLint location, GLsizei count, const GLfloat* v );
+ virtual void Uniform4i ( GLint location, GLint x, GLint y, GLint z, GLint w );
+ virtual void Uniform4iv( GLint location, GLsizei count, const GLint* v );
+ virtual void UniformMatrix2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
+ virtual void UniformMatrix3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
+ virtual void UniformMatrix4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value );
+
+ virtual GLuint CreateProgram( void );
+ virtual void DeleteProgram( GLuint program );
+ virtual void UseProgram( GLuint program );
+
+private: // Helpers
+
+ void AccumulateSamples();
+ void LogResults();
+ void LogCalls( const Sampler& sampler );
+ void LogObjectCounter( const ObjectCounter& sampler );
+ void ResetSamplers();
+
+private: // Data
+
+ EnvironmentOptions& mEnvironmentOptions;
+ Sampler mActiveTextureSampler;
+ Sampler mClearSampler;
+ Sampler mBindBufferSampler;
+ Sampler mBindTextureSampler;
+ Sampler mDrawSampler;
+ Sampler mUniformSampler;
+ Sampler mUseProgramSampler;
+ ObjectCounter mBufferCount;
+ ObjectCounter mTextureCount;
+ ObjectCounter mProgramCount;
+
+ int mCurrentFrameCount;
+ int mTotalFrameCount;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_GL_PROXY_IMPLEMENTATION_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+// CLASS HEADER
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+
+// EXTERNAL INCLUDES
+#if DALI_GLES_VERSION >= 30
+#include <GLES3/gl3.h>
+#include <GLES3/gl3ext.h>
+
+#else
+#include <GLES2/gl2.h>
+#endif // DALI_GLES_VERSION >= 30
+
+#include <GLES2/gl2ext.h>
+
+#include <EGL/eglext.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+// TBM surface support
+#ifndef EGL_NATIVE_SURFACE_TIZEN
+#define EGL_NATIVE_SURFACE_TIZEN 0x32A1
+#endif
+
+namespace
+{
+// function pointers assigned in InitializeEglImageKHR
+PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0;
+PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0;
+PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0;
+} // unnamed namespace
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl)
+: mEglImplementation(eglImpl),
+ mImageKHRInitialized(false),
+ mImageKHRInitializeFailed(false)
+{
+ DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" );
+}
+
+EglImageExtensions::~EglImageExtensions()
+{
+}
+
+void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer)
+{
+ if (mImageKHRInitialized == false)
+ {
+ InitializeEglImageKHR();
+ }
+
+ if (mImageKHRInitialized == false)
+ {
+ return NULL;
+ }
+
+ // Use the EGL image extension
+ const EGLint attribs[] =
+ {
+ EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
+ EGL_NONE
+ };
+
+ EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(),
+ EGL_NO_CONTEXT,
+ EGL_NATIVE_SURFACE_TIZEN,
+ clientBuffer,
+ attribs );
+
+ DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n");
+ if( EGL_NO_IMAGE_KHR == eglImage )
+ {
+ switch( eglGetError() )
+ {
+ case EGL_SUCCESS :
+ {
+ break;
+ }
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
+ break;
+ }
+ case EGL_BAD_CONTEXT:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" );
+ break;
+ }
+ case EGL_BAD_PARAMETER:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" );
+ break;
+ }
+ case EGL_BAD_MATCH:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" );
+ break;
+ }
+ case EGL_BAD_ACCESS:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" );
+ break;
+ }
+ case EGL_BAD_ALLOC:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" );
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+
+ return eglImage;
+}
+
+void EglImageExtensions::DestroyImageKHR(void* eglImageKHR)
+{
+ DALI_ASSERT_DEBUG( mImageKHRInitialized );
+
+ if( ! mImageKHRInitialized )
+ {
+ return;
+ }
+
+ if( eglImageKHR == NULL )
+ {
+ return;
+ }
+
+ EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
+
+ EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage);
+
+ if( EGL_FALSE == result )
+ {
+ switch( eglGetError() )
+ {
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
+ break;
+ }
+ case EGL_BAD_PARAMETER:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" );
+ break;
+ }
+ case EGL_BAD_ACCESS:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" );
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+}
+
+void EglImageExtensions::TargetTextureKHR(void* eglImageKHR)
+{
+ DALI_ASSERT_DEBUG( mImageKHRInitialized );
+
+ if( eglImageKHR != NULL )
+ {
+ EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
+
+#ifdef EGL_ERROR_CHECKING
+ GLint glError = glGetError();
+#endif
+
+ glEGLImageTargetTexture2DOESProc(GL_TEXTURE_EXTERNAL_OES, reinterpret_cast< GLeglImageOES >( eglImage ) );
+
+#ifdef EGL_ERROR_CHECKING
+ glError = glGetError();
+ if( GL_NO_ERROR != glError )
+ {
+ DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError );
+ }
+#endif
+ }
+}
+
+void EglImageExtensions::InitializeEglImageKHR()
+{
+ // avoid trying to reload extended KHR functions, if it fails the first time
+ if( ! mImageKHRInitializeFailed )
+ {
+ eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") );
+ eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") );
+ glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") );
+ }
+
+ if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc)
+ {
+ mImageKHRInitialized = true;
+ }
+ else
+ {
+ mImageKHRInitializeFailed = true;
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <vconf.h>
+#include <vconf-keys.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/common/vsync-monitor.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+// constants to keep code readability with unsigned int has to be used as boolean (due to multithreading)
+const unsigned int TRUE = 1u;
+const unsigned int FALSE = 0u;
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VSYNC_MONITOR");
+#endif
+
+const char * const DRM_DEVICE( "/dev/dri/card0" );
+const int FD_NONE( -1 );
+
+void ScreenStatusChanged(keynode_t* node, void* data)
+{
+ VSyncMonitor* vsyncMonitor( static_cast< VSyncMonitor* >( data ) );
+
+ int status = 0;
+ vconf_get_int( VCONFKEY_PM_STATE, &status );
+
+ // status values
+ // - VCONFKEY_PM_STATE_NORMAL : turn vsync on
+ // - VCONFKEY_PM_STATE_LCDDIM : turn vsync off
+ // - VCONFKEY_PM_STATE_LCDOFF : turn vsync off
+ // - VCONFKEY_PM_STATE_SLEEP : turn vsync off
+ const unsigned int screenOn( VCONFKEY_PM_STATE_NORMAL == status );
+
+ vsyncMonitor->SetHardwareVSyncAvailable( screenOn );
+
+ DALI_LOG_INFO( gLogFilter, Debug::Concise, "%s, Screen %s.\n", __PRETTY_FUNCTION__, screenOn ? "On" : "Off" );
+}
+
+} // unnamed namespace
+
+VSyncMonitor::VSyncMonitor()
+: mFileDescriptor( FD_NONE ),
+ mUseHardwareVSync( TRUE ),
+ mHardwareVSyncAvailable( FALSE )
+{
+ vconf_notify_key_changed( VCONFKEY_PM_STATE, ScreenStatusChanged, this );
+}
+
+VSyncMonitor::~VSyncMonitor()
+{
+ Terminate();
+
+ vconf_ignore_key_changed( VCONFKEY_PM_STATE, ScreenStatusChanged );
+}
+
+void VSyncMonitor::SetUseHardwareVSync( bool useHardware )
+{
+ mUseHardwareVSync = useHardware;
+}
+
+void VSyncMonitor::SetHardwareVSyncAvailable( bool hardwareVSyncAvailable )
+{
+ mHardwareVSyncAvailable = hardwareVSyncAvailable;
+}
+
+void VSyncMonitor::Initialize()
+{
+ DALI_ASSERT_DEBUG( mFileDescriptor == FD_NONE && "VSyncMonitor::Initialize() called twice" );
+
+ // Read initial 'use hardware' status
+ ScreenStatusChanged( NULL, this );
+
+ // open /dev node
+ mFileDescriptor = open( DRM_DEVICE, O_RDWR );
+
+ // setup vblank request - block and wait for next vblank
+ mVBlankInfo.request.type = DRM_VBLANK_NEXTONMISS;
+ mVBlankInfo.request.sequence = 0;
+ mVBlankInfo.request.signal = 0;
+
+ // setup vblank reply - block and wait for next vblank
+ mVBlankInfo.reply.type = DRM_VBLANK_NEXTONMISS;
+ mVBlankInfo.reply.sequence = 0;
+ mVBlankInfo.reply.tval_sec = 0;
+ mVBlankInfo.reply.tval_usec = 0;
+}
+
+void VSyncMonitor::Terminate()
+{
+ if( mFileDescriptor != FD_NONE )
+ {
+ close( mFileDescriptor );
+ mFileDescriptor = FD_NONE;
+ }
+}
+
+bool VSyncMonitor::UseHardware()
+{
+ return mUseHardwareVSync && mHardwareVSyncAvailable && (FD_NONE != mFileDescriptor );
+}
+
+bool VSyncMonitor::DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds )
+{
+ DALI_ASSERT_DEBUG( mFileDescriptor != FD_NONE && "ECoreX::VSyncMonitor is not initialized" );
+
+ if( 0 == drmWaitVBlank( mFileDescriptor, &mVBlankInfo ) )
+ {
+ frameNumber = mVBlankInfo.reply.sequence;
+ seconds = mVBlankInfo.reply.tval_sec;
+ microseconds = mVBlankInfo.reply.tval_usec;
+
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+// CLASS HEADER
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+
+// EXTERNAL INCLUDES
+#if DALI_GLES_VERSION >= 30
+#include <GLES3/gl3.h>
+#include <GLES3/gl3ext.h>
+
+#else
+#include <GLES2/gl2.h>
+#endif // DALI_GLES_VERSION >= 30
+
+#include <GLES2/gl2ext.h>
+
+#include <EGL/eglext.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+
+namespace
+{
+// function pointers assigned in InitializeEglImageKHR
+PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0;
+PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0;
+PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0;
+} // unnamed namespace
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl)
+: mEglImplementation(eglImpl),
+ mImageKHRInitialized(false),
+ mImageKHRInitializeFailed(false)
+{
+ DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" );
+}
+
+EglImageExtensions::~EglImageExtensions()
+{
+}
+
+void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer)
+{
+ if (mImageKHRInitialized == false)
+ {
+ InitializeEglImageKHR();
+ }
+
+ if (mImageKHRInitialized == false)
+ {
+ return NULL;
+ }
+
+ // Use the EGL image extension
+ const EGLint attribs[] =
+ {
+ EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
+ EGL_NONE
+ };
+
+// EGL constants use C casts
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(),
+ EGL_NO_CONTEXT,
+ EGL_NATIVE_PIXMAP_KHR,
+ clientBuffer,
+ attribs );
+
+ DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n");
+ if( EGL_NO_IMAGE_KHR == eglImage )
+ {
+ switch( eglGetError() )
+ {
+ case EGL_SUCCESS :
+ {
+ break;
+ }
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
+ break;
+ }
+ case EGL_BAD_CONTEXT:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" );
+ break;
+ }
+ case EGL_BAD_PARAMETER:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" );
+ break;
+ }
+ case EGL_BAD_MATCH:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" );
+ break;
+ }
+ case EGL_BAD_ACCESS:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" );
+ break;
+ }
+ case EGL_BAD_ALLOC:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" );
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+#pragma GCC diagnostic pop
+
+ return eglImage;
+}
+
+void EglImageExtensions::DestroyImageKHR(void* eglImageKHR)
+{
+ DALI_ASSERT_DEBUG( mImageKHRInitialized );
+
+ if( ! mImageKHRInitialized )
+ {
+ return;
+ }
+
+ if( eglImageKHR == NULL )
+ {
+ return;
+ }
+
+ EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
+
+ EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage);
+
+ if( EGL_FALSE == result )
+ {
+ switch( eglGetError() )
+ {
+ case EGL_BAD_DISPLAY:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" );
+ break;
+ }
+ case EGL_BAD_PARAMETER:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" );
+ break;
+ }
+ case EGL_BAD_ACCESS:
+ {
+ DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" );
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+}
+
+void EglImageExtensions::TargetTextureKHR(void* eglImageKHR)
+{
+ DALI_ASSERT_DEBUG( mImageKHRInitialized );
+
+ if( eglImageKHR != NULL )
+ {
+ EGLImageKHR eglImage = static_cast<EGLImageKHR>(eglImageKHR);
+
+#ifdef EGL_ERROR_CHECKING
+ GLint glError = glGetError();
+#endif
+
+ glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast< GLeglImageOES >( eglImage ) );
+
+#ifdef EGL_ERROR_CHECKING
+ glError = glGetError();
+ if( GL_NO_ERROR != glError )
+ {
+ DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError );
+ }
+#endif
+ }
+}
+
+void EglImageExtensions::InitializeEglImageKHR()
+{
+ // avoid trying to reload extended KHR functions, if it fails the first time
+ if( ! mImageKHRInitializeFailed )
+ {
+ eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") );
+ eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") );
+ glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") );
+ }
+
+ if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc)
+ {
+ mImageKHRInitialized = true;
+ }
+ else
+ {
+ mImageKHRInitializeFailed = true;
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/graphics/common/vsync-monitor.h>
+
+// EXTERNAL INCLUDES
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+// constants to keep code readability with unsigned int has to be used as boolean (due to multithreading)
+const unsigned int TRUE = 1u;
+const unsigned int FALSE = 0u;
+
+const int FD_NONE( -1 );
+
+} // unnamed namespace
+
+VSyncMonitor::VSyncMonitor()
+: mFileDescriptor( FD_NONE ),
+ mUseHardwareVSync( FALSE ),
+ mHardwareVSyncAvailable( FALSE )
+{
+}
+
+VSyncMonitor::~VSyncMonitor()
+{
+ Terminate();
+}
+
+void VSyncMonitor::SetUseHardwareVSync( bool useHardware )
+{
+ mUseHardwareVSync = useHardware;
+}
+
+void VSyncMonitor::SetHardwareVSyncAvailable( bool hardwareVSyncAvailable )
+{
+ mHardwareVSyncAvailable = hardwareVSyncAvailable;
+}
+
+void VSyncMonitor::Initialize()
+{
+ DALI_ASSERT_DEBUG( mFileDescriptor == FD_NONE && "VSyncMonitor::Initialize() called twice" );
+
+ // setup vblank request - block and wait for next vblank
+ mVBlankInfo.request.type = DRM_VBLANK_NEXTONMISS;
+ mVBlankInfo.request.sequence = 0;
+ mVBlankInfo.request.signal = 0;
+
+ // setup vblank reply - block and wait for next vblank
+ mVBlankInfo.reply.type = DRM_VBLANK_NEXTONMISS;
+ mVBlankInfo.reply.sequence = 0;
+ mVBlankInfo.reply.tval_sec = 0;
+ mVBlankInfo.reply.tval_usec = 0;
+}
+
+void VSyncMonitor::Terminate()
+{
+}
+
+bool VSyncMonitor::UseHardware()
+{
+ return mUseHardwareVSync && mHardwareVSyncAvailable && (FD_NONE != mFileDescriptor );
+}
+
+
+bool VSyncMonitor::DoSync( unsigned int& frameNumber, unsigned int& seconds, unsigned int& microseconds )
+{
+ DALI_ASSERT_DEBUG( mFileDescriptor != FD_NONE && "ECoreX::VSyncMonitor is not initialized" );
+
+ if( 0 == drmWaitVBlank( mFileDescriptor, &mVBlankInfo ) )
+ {
+ frameNumber = mVBlankInfo.reply.sequence;
+ seconds = mVBlankInfo.reply.tval_sec;
+ microseconds = mVBlankInfo.reply.tval_usec;
+
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/haptics/common/feedback-player-impl.h>
+
+// EXTERNAL INCLUDES
+#include <fstream>
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+// Type Registration
+Dali::BaseHandle Create()
+{
+ return FeedbackPlayer::Get();
+}
+
+Dali::TypeRegistration FEEDBACK_PLAYER_TYPE( typeid(Dali::FeedbackPlayer), typeid(Dali::BaseHandle), Create );
+
+} // unnamed namespace
+
+Dali::FeedbackPlayer FeedbackPlayer::New()
+{
+ Dali::FeedbackPlayer player = Dali::FeedbackPlayer( new FeedbackPlayer() );
+ return player;
+}
+
+Dali::FeedbackPlayer FeedbackPlayer::Get()
+{
+ Dali::FeedbackPlayer player;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::FeedbackPlayer ) );
+ if ( handle )
+ {
+ // If so, downcast the handle
+ player = Dali::FeedbackPlayer( dynamic_cast< FeedbackPlayer* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ player = Dali::FeedbackPlayer( New() );
+ service.Register( typeid( player ), player );
+ }
+ }
+
+ return player;
+}
+
+void FeedbackPlayer::PlayMonotone( unsigned int duration )
+{
+ mPlugin.PlayHapticMonotone( duration );
+}
+
+void FeedbackPlayer::PlayFile( const std::string& filePath )
+{
+ mPlugin.PlayHaptic( filePath );
+}
+
+void FeedbackPlayer::Stop()
+{
+ mPlugin.StopHaptic();
+}
+
+int FeedbackPlayer::PlaySound( const std::string& filename )
+{
+ return mPlugin.PlaySound(filename);
+}
+
+void FeedbackPlayer::StopSound( int handle )
+{
+ mPlugin.StopSound(handle);
+}
+
+void FeedbackPlayer::PlayFeedbackPattern( int type, int pattern )
+{
+ mPlugin.PlayFeedbackPattern(type, pattern);
+}
+
+bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data)
+{
+ bool loaded = false;
+
+ std::ifstream stream(filename.c_str());
+
+ if( stream.is_open() )
+ {
+ data.assign((std::istreambuf_iterator<char>(stream)),
+ std::istreambuf_iterator<char>());
+ loaded = true;
+ }
+
+ return loaded;
+}
+
+FeedbackPlayer::FeedbackPlayer()
+: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME )
+{
+}
+
+FeedbackPlayer::~FeedbackPlayer()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_FEEDBACK_PLAYER_H__
+#define __DALI_INTERNAL_FEEDBACK_PLAYER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/feedback-player.h>
+#include <dali/internal/haptics/common/feedback-plugin-proxy.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class FeedbackPluginProxy;
+
+/**
+ * Plays haptic effects.
+ */
+class FeedbackPlayer : public Dali::BaseObject
+{
+
+public:
+
+ /**
+ * Create a FeedbackPlayer.
+ * This should only be called once by the Adaptor class.
+ * @return A newly created FeedbackPlayer.
+ */
+ static Dali::FeedbackPlayer New();
+
+ /**
+ * Retrieve a handle to the FeedbackPlayer. This creates an instance if none has been created.
+ * @return A handle to the FeedbackPlayer.
+ */
+ static Dali::FeedbackPlayer Get();
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::PlayMonotone()
+ */
+ void PlayMonotone(unsigned int duration);
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::PlayFile()
+ */
+ void PlayFile( const std::string& filePath );
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::Stop()
+ */
+ void Stop();
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::PlaySound()
+ */
+ int PlaySound( const std::string& fileName );
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::StopSound()
+ */
+ void StopSound( int handle );
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::PlayFeedbackPattern()
+ */
+ void PlayFeedbackPattern( int type, int pattern );
+
+ /**
+ * @copydoc Dali::FeedbackPlayer::LoadFile()
+ */
+ bool LoadFile(const std::string& filename, std::string& data);
+
+private:
+
+ /**
+ * Private Constructor; see also FeedbackPlayer::New()
+ */
+ FeedbackPlayer();
+
+ /**
+ * Virtual Destructor
+ */
+ virtual ~FeedbackPlayer();
+
+ // Undefined
+ FeedbackPlayer(const FeedbackPlayer&);
+
+ // Undefined
+ FeedbackPlayer& operator=(FeedbackPlayer&);
+
+private:
+
+ FeedbackPluginProxy mPlugin;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::FeedbackPlayer& GetImplementation(Dali::FeedbackPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" );
+
+ BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::FeedbackPlayer&>(handle);
+}
+
+inline const Internal::Adaptor::FeedbackPlayer& GetImplementation(const Dali::FeedbackPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" );
+
+ const BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::FeedbackPlayer&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_FEEDBACK_PLAYER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/haptics/common/feedback-plugin-proxy.h>
+
+// EXTERNAL INCLUDES
+#include <dlfcn.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#if _GLIBCXX_USE_CXX11_ABI
+const char * const FeedbackPluginProxy::DEFAULT_OBJECT_NAME( "libdali-feedback-plugin.so" );
+#else
+const char * const FeedbackPluginProxy::DEFAULT_OBJECT_NAME( "libdali-feedback-plugin-cxx03.so" );
+#endif
+
+FeedbackPluginProxy::FeedbackPluginProxy( const std::string& sharedObjectName )
+: mInitializeAttempted( false ),
+ mLibHandle( NULL ),
+ mSharedObjectName( sharedObjectName ),
+ mCreatePluginFunctionPtr( NULL ),
+ mFeedbackPlugin( NULL )
+{
+ // Lazily initialize when sound/haptic is first played
+}
+
+FeedbackPluginProxy::~FeedbackPluginProxy()
+{
+ if( mFeedbackPlugin )
+ {
+ delete mFeedbackPlugin;
+ mFeedbackPlugin = NULL;
+
+ if( mLibHandle && dlclose( mLibHandle ) )
+ {
+ DALI_LOG_ERROR( "Error closing dali feedback plugin library: %s\n", dlerror() );
+ }
+ }
+}
+
+void FeedbackPluginProxy::PlayHaptic( const std::string& filePath )
+{
+ // Lazy initialization
+ Initialize();
+
+ if( mFeedbackPlugin )
+ {
+ mFeedbackPlugin->PlayHaptic( filePath );
+ }
+}
+
+void FeedbackPluginProxy::PlayHapticMonotone( unsigned int duration )
+{
+ // Lazy initialization
+ Initialize();
+
+ if( mFeedbackPlugin )
+ {
+ mFeedbackPlugin->PlayHapticMonotone( duration );
+ }
+}
+
+void FeedbackPluginProxy::StopHaptic()
+{
+ // Must already have been initialized to play haptic
+ if( mFeedbackPlugin )
+ {
+ mFeedbackPlugin->StopHaptic();
+ }
+}
+
+int FeedbackPluginProxy::PlaySound( const std::string& fileName )
+{
+ // Lazy initialization
+ Initialize();
+
+ if( mFeedbackPlugin )
+ {
+ return mFeedbackPlugin->PlaySound( fileName );
+ }
+
+ return 0;
+}
+
+void FeedbackPluginProxy::StopSound( int handle )
+{
+ // Must already have been initialized to play sound
+ if ( mFeedbackPlugin )
+ {
+ mFeedbackPlugin->StopSound( handle );
+ }
+}
+
+void FeedbackPluginProxy::PlayFeedbackPattern( int type, int pattern )
+{
+ // Lazy initialization
+ Initialize();
+
+ if( mFeedbackPlugin )
+ {
+ mFeedbackPlugin->PlayFeedbackPattern( type, pattern );
+ }
+}
+
+void FeedbackPluginProxy::Initialize()
+{
+ // Only attempt to load dll once
+ if ( !mInitializeAttempted )
+ {
+ mInitializeAttempted = true;
+
+ mLibHandle = dlopen( mSharedObjectName.c_str(), RTLD_NOW | RTLD_GLOBAL );
+ if( !mLibHandle )
+ {
+ DALI_LOG_ERROR( "Cannot load dali feedback plugin library error: %s\n", dlerror() );
+ return;
+ }
+
+ // reset errors
+ dlerror();
+
+ // load plugin
+ mCreatePluginFunctionPtr = reinterpret_cast<CreateFeedbackPlugin*>(dlsym(mLibHandle, "CreateFeedbackPlugin"));
+ if(!mCreatePluginFunctionPtr)
+ {
+ DALI_LOG_ERROR("Cannot load symbol CreateFeedbackPlugin(): %s\n", dlerror());
+ return;
+ }
+
+ // reset errors
+ dlerror();
+
+ mFeedbackPlugin = mCreatePluginFunctionPtr();
+
+ if(!mFeedbackPlugin)
+ {
+ DALI_LOG_ERROR("Call to function CreateFeedbackPlugin() failed\n");
+ }
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
+#define __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/feedback-plugin.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+typedef Dali::FeedbackPlugin::SoundStopCallBack SoundStopCallBack;
+typedef Dali::FeedbackPlugin::CreateFeedbackPlugin CreateFeedbackPlugin;
+
+/**
+ * Proxy class to dynamically load, use and unload feedback plugin.
+ */
+class FeedbackPluginProxy
+{
+public:
+
+ /**
+ * The default feedback plugin proxy.
+ */
+ static const char * const DEFAULT_OBJECT_NAME;
+
+public:
+
+ /**
+ * Constructor.
+ */
+ FeedbackPluginProxy( const std::string& sharedObjectName );
+
+ /**
+ * The destructor
+ */
+ ~FeedbackPluginProxy();
+
+ /**
+ * @copydoc Dali::Integration::FeedbackPlugin::PlayHaptic()
+ */
+ void PlayHaptic( const std::string& filePath );
+
+ /**
+ * @copydoc Dali::FeedbackPlugin::PlayHapticMonotone()
+ */
+ void PlayHapticMonotone( unsigned int duration );
+
+ /**
+ * @copydoc Dali::FeedbackPlugin::StopHaptic()
+ */
+ void StopHaptic();
+
+ /**
+ * @copydoc Dali::FeedbackPlugin::PlaySound()
+ */
+ int PlaySound( const std::string& fileName );
+
+ /**
+ * @copydoc Dali::FeedbackPlugin::StopSound()
+ */
+ void StopSound( int handle );
+
+ /**
+ * @copydoc Dali::FeedbackPlugin::PlayFeedbackPattern()
+ */
+ void PlayFeedbackPattern( int type, int pattern );
+
+private:
+
+ /**
+ * Dynamically loads the feedback plugin.
+ */
+ void Initialize();
+
+private:
+
+ bool mInitializeAttempted;
+ void* mLibHandle;
+ std::string mSharedObjectName;
+ CreateFeedbackPlugin* mCreatePluginFunctionPtr;
+ Dali::FeedbackPlugin* mFeedbackPlugin;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H__
--- /dev/null
+
+
+# module: haptics, backend: common
+adaptor_haptics_common_src_files=\
+ ${adaptor_haptics_dir}/common/feedback-player-impl.cpp \
+ ${adaptor_haptics_dir}/common/feedback-plugin-proxy.cpp
+
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dali/internal/imaging/common/pixel-manipulation.h>
+#include <dali/internal/imaging/common/alpha-mask.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+#include <dali/public-api/images/image-operations.h> // For ImageDimensions
+#include <dali/internal/imaging/common/image-operations.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask )
+{
+ int srcAlphaByteOffset=0;
+ int srcAlphaMask=0;
+ Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat();
+
+ if( Pixel::HasAlpha(srcPixelFormat) )
+ {
+ Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask );
+ }
+ else if( srcPixelFormat == Pixel::L8 )
+ {
+ srcAlphaMask=0xFF;
+ }
+
+ int destAlphaByteOffset=0;
+ int destAlphaMask=0;
+ Dali::Pixel::GetAlphaOffsetAndMask( buffer.GetPixelFormat(), destAlphaByteOffset, destAlphaMask );
+
+ unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat );
+ unsigned char* srcBuffer = mask.GetBuffer();
+ unsigned char* destBuffer = buffer.GetBuffer();
+
+ unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( buffer.GetPixelFormat() );
+
+ int srcOffset=0;
+ int destOffset=0;
+
+ float srcAlphaValue = 1.0f;
+
+ for( unsigned int row = 0; row < buffer.GetHeight(); ++row )
+ {
+ for( unsigned int col = 0; col < buffer.GetWidth(); ++col )
+ {
+ unsigned char alpha = srcBuffer[srcOffset + srcAlphaByteOffset] & srcAlphaMask;
+ srcAlphaValue = float(alpha)/255.0f;
+
+ unsigned char destAlpha = destBuffer[destOffset + destAlphaByteOffset] & destAlphaMask;
+ float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f);
+ destAlpha = destAlphaValue;
+ destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask;
+ destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask );
+
+ srcOffset += srcBytesPerPixel;
+ destOffset += destBytesPerPixel;
+ }
+ }
+}
+
+PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask )
+{
+ // Set up source alpha offsets
+ int srcAlphaByteOffset=0;
+ int srcAlphaMask=0;
+ Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat();
+
+ if( Pixel::HasAlpha(srcPixelFormat) )
+ {
+ Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask );
+ }
+ else if( srcPixelFormat == Pixel::L8 )
+ {
+ srcAlphaMask=0xFF;
+ }
+
+ unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat );
+ unsigned char* srcBuffer = mask.GetBuffer();
+
+ // Set up source color offsets
+ Dali::Pixel::Format srcColorPixelFormat = buffer.GetPixelFormat();
+ unsigned int srcColorBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcColorPixelFormat );
+
+ // Setup destination offsets
+ Dali::Pixel::Format destPixelFormat = Dali::Pixel::RGBA8888;
+ unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( destPixelFormat );
+ int destAlphaByteOffset=0;
+ int destAlphaMask=0;
+ Dali::Pixel::GetAlphaOffsetAndMask( destPixelFormat, destAlphaByteOffset, destAlphaMask );
+
+ PixelBufferPtr newPixelBuffer = PixelBuffer::New( buffer.GetWidth(), buffer.GetHeight(),
+ destPixelFormat );
+ unsigned char* destBuffer = newPixelBuffer->GetBuffer();
+ unsigned char* oldBuffer = buffer.GetBuffer();
+
+ int srcAlphaOffset=0;
+ int srcColorOffset=0;
+ int destOffset=0;
+ bool hasAlpha = Dali::Pixel::HasAlpha(buffer.GetPixelFormat());
+
+ float srcAlphaValue = 1.0f;
+ unsigned char destAlpha = 0;
+
+ for( unsigned int row = 0; row < buffer.GetHeight(); ++row )
+ {
+ for( unsigned int col = 0; col < buffer.GetWidth(); ++col )
+ {
+ unsigned char alpha = srcBuffer[srcAlphaOffset + srcAlphaByteOffset] & srcAlphaMask;
+ srcAlphaValue = float(alpha)/255.0f;
+
+ ConvertColorChannelsToRGBA8888(oldBuffer, srcColorOffset, srcColorPixelFormat, destBuffer, destOffset );
+
+ if( hasAlpha )
+ {
+ destAlpha = ConvertAlphaChannelToA8( oldBuffer, srcColorOffset, srcColorPixelFormat );
+ float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f);
+ destAlpha = destAlphaValue;
+ }
+ else
+ {
+ destAlpha = floorf(Clamp(srcAlphaValue * 255.0f, 0.0f, 255.0f));
+ }
+
+ destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask;
+ destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask );
+
+ srcColorOffset += srcColorBytesPerPixel;
+ srcAlphaOffset += srcBytesPerPixel;
+ destOffset += destBytesPerPixel;
+ }
+ }
+
+ return newPixelBuffer;
+}
+
+} //namespace Adaptor
+
+}// namespace Internal
+
+}// namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
+#define DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * Apply the mask to a buffer's alpha channel
+ * @param[in] buffer The buffer to apply the mask to
+ * @param[in] mask The mask to apply
+ */
+void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask );
+
+/**
+ * Create a new PixelBuffer with an alpha channel large enough to handle the alpha from
+ * the mask, converting the color values to the new size, and either multiplying the mask's
+ * alpha into the existing alpha value, or writing the mask's alpha value directly into
+ * the new buffer's alpha channel.
+ *
+ * @param[in] buffer The buffer to apply the mask to
+ * @param[in] mask The mask to apply
+ * @return A new pixel buffer containing the masked image
+ */
+PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask );
+
+} //namespace Adaptor
+} //namespace Internal
+} //namespace Dali
+
+#endif // DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// HEADER
+#include <dali/internal/imaging/common/file-download.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <pthread.h>
+#include <curl/curl.h>
+#include <openssl/crypto.h>
+#include <cstring>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/file-writer.h>
+
+#ifdef TPK_CURL_ENABLED
+#include <tpkp_curl.h>
+#endif // TPK_CURL_ENABLED
+
+using namespace Dali::Integration;
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace // unnamed namespace
+{
+
+const int CONNECTION_TIMEOUT_SECONDS( 30L );
+const long VERBOSE_MODE = 0L; // 0 == off, 1 == on
+const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on
+const long EXCLUDE_HEADER = 0L;
+const long INCLUDE_HEADER = 1L;
+const long INCLUDE_BODY = 0L;
+const long EXCLUDE_BODY = 1L;
+
+/**
+ * Curl library environment. Direct initialize ensures it's constructed before adaptor
+ * or application creates any threads.
+ */
+static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment;
+
+void ConfigureCurlOptions( CURL* curlHandle, const std::string& url )
+{
+ curl_easy_setopt( curlHandle, CURLOPT_URL, url.c_str() );
+ curl_easy_setopt( curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE );
+
+ // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual )
+ // Removed CURLOPT_FAILONERROR option
+ curl_easy_setopt( curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS );
+ curl_easy_setopt( curlHandle, CURLOPT_HEADER, INCLUDE_HEADER );
+ curl_easy_setopt( curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY );
+
+#ifdef TPK_CURL_ENABLED
+ // Apply certificate pinning on Tizen
+ curl_easy_setopt( curlHandle, CURLOPT_SSL_CTX_FUNCTION, tpkp_curl_ssl_ctx_callback );
+#endif // TPK_CURL_ENABLED
+}
+
+// Without a write function or a buffer (file descriptor) to write to, curl will pump out
+// header/body contents to stdout
+size_t DummyWrite(char *ptr, size_t size, size_t nmemb, void *userdata)
+{
+ return size * nmemb;
+}
+
+struct ChunkData
+{
+ std::vector< uint8_t > data;
+};
+
+size_t ChunkLoader(char *ptr, size_t size, size_t nmemb, void *userdata)
+{
+ std::vector<ChunkData>* chunks = static_cast<std::vector<ChunkData>*>( userdata );
+ int numBytes = size*nmemb;
+ chunks->push_back( ChunkData() );
+ ChunkData& chunkData = (*chunks)[chunks->size()-1];
+ chunkData.data.reserve( numBytes );
+ memcpy( &chunkData.data[0], ptr, numBytes );
+ return numBytes;
+}
+
+
+CURLcode DownloadFileDataWithSize( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t dataSize )
+{
+ CURLcode result( CURLE_OK );
+
+ // create
+ Dali::Internal::Platform::FileWriter fileWriter( dataBuffer, dataSize );
+ FILE* dataBufferFilePointer = fileWriter.GetFile();
+ if( NULL != dataBufferFilePointer )
+ {
+ // we only want the body which contains the file data
+ curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
+ curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
+
+ // disable the write callback, and get curl to write directly into our data buffer
+ curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, NULL );
+ curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer );
+
+ // synchronous request of the body data
+ result = curl_easy_perform( curlHandle );
+ }
+ return result;
+}
+
+CURLcode DownloadFileDataByChunk( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize )
+{
+ // create
+ std::vector< ChunkData > chunks;
+
+ // we only want the body which contains the file data
+ curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
+ curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
+
+ // Enable the write callback.
+ curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader );
+ curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, &chunks );
+
+ // synchronous request of the body data
+ CURLcode result = curl_easy_perform( curlHandle );
+
+ // chunks should now contain all of the chunked data. Reassemble into a single vector
+ dataSize = 0;
+ for( size_t i=0; i<chunks.size() ; ++i )
+ {
+ dataSize += chunks[i].data.capacity();
+ }
+ dataBuffer.Resize(dataSize);
+
+ size_t offset = 0;
+ for( size_t i=0; i<chunks.size() ; ++i )
+ {
+ memcpy( &dataBuffer[offset], &chunks[i].data[0], chunks[i].data.capacity() );
+ offset += chunks[i].data.capacity();
+ }
+
+ return result;
+}
+
+bool DownloadFile( CURL* curlHandle,
+ const std::string& url,
+ Dali::Vector<uint8_t>& dataBuffer,
+ size_t& dataSize,
+ size_t maximumAllowedSizeBytes )
+{
+ CURLcode result( CURLE_OK );
+ double size(0);
+
+ // setup curl to download just the header so we can extract the content length
+ ConfigureCurlOptions( curlHandle, url );
+
+ curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite);
+
+ // perform the request to get the header
+ result = curl_easy_perform( curlHandle );
+
+ if( result != CURLE_OK)
+ {
+ DALI_LOG_WARNING( "Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result );
+ return false;
+ }
+
+ // get the content length, -1 == size is not known
+ curl_easy_getinfo( curlHandle,CURLINFO_CONTENT_LENGTH_DOWNLOAD , &size );
+
+
+ if( size >= maximumAllowedSizeBytes )
+ {
+ DALI_LOG_WARNING( "File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str() );
+ return false;
+ }
+ else if( size > 0 )
+ {
+ // If we know the size up front, allocate once and avoid chunk copies.
+ dataSize = static_cast<size_t>( size );
+ result = DownloadFileDataWithSize( curlHandle, dataBuffer, dataSize );
+ }
+ else
+ {
+ result = DownloadFileDataByChunk( curlHandle, dataBuffer, dataSize );
+ }
+
+ if( result != CURLE_OK )
+ {
+ DALI_LOG_WARNING( "Failed to download image file \"%s\" with error code %d\n", url.c_str(), result );
+ return false;
+ }
+ return true;
+}
+
+
+} // unnamed namespace
+
+
+namespace Network
+{
+
+std::mutex* CurlEnvironment::mMutexs = NULL;
+
+CurlEnvironment::CurlEnvironment()
+{
+ // Must be called before we attempt any loads. e.g. by using curl_easy_init()
+ // and before we start any threads.
+ curl_global_init(CURL_GLOBAL_ALL);
+
+ // libcurl with openssl needs locking_function and thread id for threadsafe
+ // https://curl.haxx.se/libcurl/c/threadsafe.html
+ // https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
+ // SetLockingFunction sets locking_function and get thread id by the guide.
+ SetLockingFunction();
+}
+
+CurlEnvironment::~CurlEnvironment()
+{
+ UnsetLockingFunction();
+
+ curl_global_cleanup();
+}
+
+// libcurl with openssl needs locking_function and thread id for threadsafe
+// https://curl.haxx.se/libcurl/c/threadsafe.html
+// https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
+void CurlEnvironment::OnOpenSSLLocking( int mode, int n, const char* file, int line )
+{
+ if( mode & CRYPTO_LOCK )
+ {
+ mMutexs[n].lock();
+ }
+ else
+ {
+ mMutexs[n].unlock();
+ }
+}
+
+unsigned long CurlEnvironment::GetThreadId()
+{
+ // If dali uses c++ thread, we may replace pthread_self() to this_thread::get_id()
+ return static_cast< unsigned long >( pthread_self() );
+}
+
+void CurlEnvironment::SetLockingFunction()
+{
+ if( mMutexs != NULL )
+ {
+ return;
+ }
+
+ mMutexs = new std::mutex[ CRYPTO_num_locks() ];
+
+ CRYPTO_set_id_callback( &CurlEnvironment::GetThreadId );
+ CRYPTO_set_locking_callback( &CurlEnvironment::OnOpenSSLLocking );
+}
+
+void CurlEnvironment::UnsetLockingFunction()
+{
+ if( mMutexs == NULL )
+ {
+ return;
+ }
+
+ CRYPTO_set_id_callback( NULL );
+ CRYPTO_set_locking_callback( NULL );
+ delete [] mMutexs;
+ mMutexs = NULL;
+}
+
+bool DownloadRemoteFileIntoMemory( const std::string& url,
+ Dali::Vector<uint8_t>& dataBuffer,
+ size_t& dataSize,
+ size_t maximumAllowedSizeBytes )
+{
+ if( url.empty() )
+ {
+ DALI_LOG_WARNING("empty url requested \n");
+ return false;
+ }
+
+ // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download
+ // thread we need to explicity call curl_global_init() on startup from a single thread.
+
+ CURL* curlHandle = curl_easy_init();
+
+ bool result = DownloadFile( curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes);
+
+ // clean up session
+ curl_easy_cleanup( curlHandle );
+
+#ifdef TPK_CURL_ENABLED
+ // Clean up tpkp(the module for certificate pinning) resources on Tizen
+ tpkp_curl_cleanup();
+#endif // TPK_CURL_ENABLED
+
+ return result;
+}
+
+} // namespace Network
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// EXTERNAL INCLUDES
+#include <memory.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/gaussian-blur.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+
+
+void ConvoluteAndTranspose( unsigned char* inBuffer,
+ unsigned char* outBuffer,
+ const unsigned int bufferWidth,
+ const unsigned int bufferHeight,
+ const float blurRadius )
+{
+ // Calculate the weights for gaussian blur
+ int radius = static_cast<int>( std::ceil( blurRadius ) );
+ int rows = radius * 2 + 1;
+
+ float sigma = ( blurRadius < Math::MACHINE_EPSILON_1 ) ? 0.0f : blurRadius * 0.4f + 0.6f; // The same equation used by Android
+ float sigma22 = 2.0f * sigma * sigma;
+ float sqrtSigmaPi2 = std::sqrt( 2.0f * Math::PI ) * sigma;
+ float radius2 = radius * radius;
+ float normalizeFactor = 0.0f;
+
+ float* weightMatrix = new float[rows];
+ int index = 0;
+
+ for ( int row = -radius; row <= radius; row++ )
+ {
+ float distance = row * row;
+ if ( distance > radius2 )
+ {
+ weightMatrix[index] = 0.0f;
+ }
+ else
+ {
+ weightMatrix[index] = static_cast<float>( std::exp( -( distance ) / sigma22 ) / sqrtSigmaPi2 );
+ }
+ normalizeFactor += weightMatrix[index];
+ index++;
+ }
+
+ for ( int i = 0; i < rows; i++ )
+ {
+ weightMatrix[i] /= normalizeFactor;
+ }
+
+ // Perform the convolution and transposition using the weights
+ int columns = rows;
+ int columns2 = columns / 2;
+ for ( unsigned int y = 0; y < bufferHeight; y++ )
+ {
+ unsigned int targetPixelIndex = y;
+ unsigned int ioffset = y * bufferWidth;
+ for ( unsigned int x = 0; x < bufferWidth; x++ )
+ {
+ float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f;
+ int weightColumnOffset = columns2;
+ for ( int column = -columns2; column <= columns2; column++ )
+ {
+ float weight = weightMatrix[weightColumnOffset + column];
+ if ( fabsf( weight ) > Math::MACHINE_EPSILON_1 )
+ {
+ int ix = x + column;
+ ix = std::max( 0, std::min( ix, static_cast<int>( bufferWidth - 1 ) ) );
+ unsigned int sourcePixelIndex = ioffset + ix;
+ r += weight * inBuffer[sourcePixelIndex*4];
+ g += weight * inBuffer[sourcePixelIndex*4+1];
+ b += weight * inBuffer[sourcePixelIndex*4+2];
+ a += weight * inBuffer[sourcePixelIndex*4+3];
+ }
+ }
+
+ outBuffer[targetPixelIndex*4] = std::max( 0, std::min( static_cast<int>( r + 0.5f ), 255 ) );
+ outBuffer[targetPixelIndex*4+1] = std::max( 0, std::min( static_cast<int>( g + 0.5f ), 255 ) );
+ outBuffer[targetPixelIndex*4+2] = std::max( 0, std::min( static_cast<int>( b + 0.5f ), 255 ) );
+ outBuffer[targetPixelIndex*4+3] = std::max( 0, std::min( static_cast<int>( a + 0.5f ), 255 ) );
+
+ targetPixelIndex += bufferHeight;
+ }
+ }
+
+ delete [] weightMatrix;
+}
+
+void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius )
+{
+ unsigned int bufferWidth = buffer.GetWidth();
+ unsigned int bufferHeight = buffer.GetHeight();
+
+ // Create a temporary buffer for the two-pass blur
+ PixelBufferPtr softShadowImageBuffer = PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
+ memcpy( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), 4u * bufferWidth * bufferHeight );
+
+ // We perform the blur first but write its output image buffer transposed, so that we
+ // can just do it in two passes. The first pass blurs horizontally and transposes, the
+ // second pass does the same, but as the image is now transposed, it's really doing a
+ // vertical blur. The second transposition makes the image the right way up again. This
+ // is much faster than doing a 2D convolution.
+ ConvoluteAndTranspose( buffer.GetBuffer(), softShadowImageBuffer->GetBuffer(), bufferWidth, bufferHeight, blurRadius );
+ ConvoluteAndTranspose( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), bufferHeight, bufferWidth, blurRadius );
+
+ // On leaving scope, softShadowImageBuffer will get destroyed.
+}
+
+} //namespace Adaptor
+
+}// namespace Internal
+
+}// namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
+#define DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Perform a one dimension Gaussian blur convolution and write its output buffer transposed.
+ *
+ * @param[in] inBuffer The input buffer with the source image
+ * @param[in] outBuffer The output buffer with the Gaussian blur applied and transposed
+ * @param[in] bufferWidth The width of the buffer
+ * @param[in] bufferHeight The height of the buffer
+ * @param[in] blurRadius The radius for Gaussian blur
+ */
+void ConvoluteAndTranspose( unsigned char* inBuffer, unsigned char* outBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight, const float blurRadius );
+
+/**
+ * Perform Gaussian blur on a buffer.
+ *
+ * A Gaussian blur is generated by replacing each pixel’s color values with the average of the surrounding pixels’
+ * colors. This region is a circle with the given radius. Thus, a bigger radius yields a blurrier image.
+ *
+ * @note The pixel format of the buffer must be RGBA8888
+ *
+ * @param[in] buffer The buffer to apply the Gaussian blur to
+ * @param[in] blurRadius The radius for Gaussian blur
+ */
+void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius );
+
+} //namespace Adaptor
+
+} //namespace Internal
+
+} //namespace Dali
+
+#endif // DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/http-utils.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+const unsigned int MIN_HTTP_URL_LENGTH = 12; // assume we have a least http://xx/yy
+const char HTTP_URL[] = "http://";
+const char HTTPS_URL[] = "https://";
+}
+
+bool Network::IsHttpUrl( const std::string& path )
+{
+ if( path.size() <= MIN_HTTP_URL_LENGTH )
+ {
+ return false;
+ }
+
+ if( ( strncasecmp( path.c_str(), HTTP_URL, sizeof(HTTP_URL) -1 ) == 0 ) ||
+ ( strncasecmp( path.c_str(), HTTPS_URL, sizeof(HTTPS_URL) -1 ) == 0 ) )
+ {
+ return true;
+ }
+
+ return false;
+}
+
+} // TizenPlatform
+
+} // Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <dali/internal/imaging/common/image-loader.h>
+
+#include <dali/devel-api/common/ref-counted-dali-vector.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+#include <dali/internal/imaging/common/loader-astc.h>
+#include <dali/internal/imaging/common/loader-bmp.h>
+#include <dali/internal/imaging/common/loader-gif.h>
+#include <dali/internal/imaging/common/loader-ico.h>
+#include <dali/internal/imaging/common/loader-jpeg.h>
+#include <dali/internal/imaging/common/loader-ktx.h>
+#include <dali/internal/imaging/common/loader-png.h>
+#include <dali/internal/imaging/common/loader-wbmp.h>
+#include <dali/internal/imaging/common/image-operations.h>
+#include <dali/internal/imaging/common/image-loader-input.h>
+#include <dali/internal/system/common/file-reader.h>
+
+using namespace Dali::Integration;
+
+namespace Dali
+{
+namespace TizenPlatform
+{
+
+namespace
+{
+typedef bool (*LoadBitmapFunction)( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& pixelData );
+typedef bool (*LoadBitmapHeaderFunction)( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+#if defined(DEBUG_ENABLED)
+Integration::Log::Filter* gLogFilter = Debug::Filter::New( Debug::Concise, false, "LOG_IMAGE_LOADING" );
+#endif
+
+/**
+ * Stores the magic bytes, and the loader and header functions used for each image loader.
+ */
+struct BitmapLoader
+{
+ unsigned char magicByte1; ///< The first byte in the file should be this
+ unsigned char magicByte2; ///< The second byte in the file should be this
+ LoadBitmapFunction loader; ///< The function which decodes the file
+ LoadBitmapHeaderFunction header; ///< The function which decodes the header of the file
+ Bitmap::Profile profile; ///< The kind of bitmap to be created
+ /// (addressable packed pixels or an opaque compressed blob).
+};
+
+/**
+ * Enum for file formats, has to be in sync with BITMAP_LOADER_LOOKUP_TABLE
+ */
+enum FileFormats
+{
+ // Unknown file format
+ FORMAT_UNKNOWN = -1,
+
+ // formats that use magic bytes
+ FORMAT_PNG = 0,
+ FORMAT_JPEG,
+ FORMAT_BMP,
+ FORMAT_GIF,
+ FORMAT_KTX,
+ FORMAT_ASTC,
+ FORMAT_ICO,
+ FORMAT_MAGIC_BYTE_COUNT,
+
+ // formats after this one do not use magic bytes
+ FORMAT_WBMP = FORMAT_MAGIC_BYTE_COUNT,
+ FORMAT_TOTAL_COUNT
+};
+
+/**
+ * A lookup table containing all the bitmap loaders with the appropriate information.
+ * Has to be in sync with enum FileFormats
+ */
+const BitmapLoader BITMAP_LOADER_LOOKUP_TABLE[FORMAT_TOTAL_COUNT] =
+{
+ { Png::MAGIC_BYTE_1, Png::MAGIC_BYTE_2, LoadBitmapFromPng, LoadPngHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+ { Jpeg::MAGIC_BYTE_1, Jpeg::MAGIC_BYTE_2, LoadBitmapFromJpeg, LoadJpegHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+ { Bmp::MAGIC_BYTE_1, Bmp::MAGIC_BYTE_2, LoadBitmapFromBmp, LoadBmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+ { Gif::MAGIC_BYTE_1, Gif::MAGIC_BYTE_2, LoadBitmapFromGif, LoadGifHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+ { Ktx::MAGIC_BYTE_1, Ktx::MAGIC_BYTE_2, LoadBitmapFromKtx, LoadKtxHeader, Bitmap::BITMAP_COMPRESSED },
+ { Astc::MAGIC_BYTE_1, Astc::MAGIC_BYTE_2, LoadBitmapFromAstc, LoadAstcHeader, Bitmap::BITMAP_COMPRESSED },
+ { Ico::MAGIC_BYTE_1, Ico::MAGIC_BYTE_2, LoadBitmapFromIco, LoadIcoHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+ { 0x0, 0x0, LoadBitmapFromWbmp, LoadWbmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
+};
+
+const unsigned int MAGIC_LENGTH = 2;
+
+/**
+ * This code tries to predict the file format from the filename to help with format picking.
+ */
+struct FormatExtension
+{
+ const std::string extension;
+ FileFormats format;
+};
+
+const FormatExtension FORMAT_EXTENSIONS[] =
+{
+ { ".png", FORMAT_PNG },
+ { ".jpg", FORMAT_JPEG },
+ { ".bmp", FORMAT_BMP },
+ { ".gif", FORMAT_GIF },
+ { ".ktx", FORMAT_KTX },
+ { ".astc", FORMAT_ASTC },
+ { ".ico", FORMAT_ICO },
+ { ".wbmp", FORMAT_WBMP }
+};
+
+const unsigned int FORMAT_EXTENSIONS_COUNT = sizeof(FORMAT_EXTENSIONS) / sizeof(FormatExtension);
+
+FileFormats GetFormatHint( const std::string& filename )
+{
+ FileFormats format = FORMAT_UNKNOWN;
+
+ for ( unsigned int i = 0; i < FORMAT_EXTENSIONS_COUNT; ++i )
+ {
+ unsigned int length = FORMAT_EXTENSIONS[i].extension.size();
+ if ( ( filename.size() > length ) &&
+ ( 0 == filename.compare( filename.size() - length, length, FORMAT_EXTENSIONS[i].extension ) ) )
+ {
+ format = FORMAT_EXTENSIONS[i].format;
+ break;
+ }
+ }
+
+ return format;
+}
+
+/**
+ * Checks the magic bytes of the file first to determine which Image decoder to use to decode the
+ * bitmap.
+ * @param[in] fp The file to decode
+ * @param[in] format Hint about what format to try first
+ * @param[out] loader Set with the function to use to decode the image
+ * @param[out] header Set with the function to use to decode the header
+ * @param[out] profile The kind of bitmap to hold the bits loaded for the bitmap.
+ * @return true, if we can decode the image, false otherwise
+ */
+bool GetBitmapLoaderFunctions( FILE *fp,
+ FileFormats format,
+ LoadBitmapFunction& loader,
+ LoadBitmapHeaderFunction& header,
+ Bitmap::Profile& profile )
+{
+ unsigned char magic[MAGIC_LENGTH];
+ size_t read = fread(magic, sizeof(unsigned char), MAGIC_LENGTH, fp);
+
+ // Reset to the start of the file.
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking to start of file\n");
+ }
+
+ if (read != MAGIC_LENGTH)
+ {
+ return false;
+ }
+
+ bool loaderFound = false;
+ const BitmapLoader *lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
+ ImageLoader::Input defaultInput( fp );
+
+ // try hinted format first
+ if ( format != FORMAT_UNKNOWN )
+ {
+ lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + format;
+ if ( format >= FORMAT_MAGIC_BYTE_COUNT ||
+ ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] ) )
+ {
+ unsigned int width = 0;
+ unsigned int height = 0;
+ loaderFound = lookupPtr->header( fp, width, height );
+ }
+ }
+
+ // then try to get a match with formats that have magic bytes
+ if ( false == loaderFound )
+ {
+ for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
+ lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
+ ++lookupPtr )
+ {
+ if ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] )
+ {
+ // to seperate ico file format and wbmp file format
+ unsigned int width = 0;
+ unsigned int height = 0;
+ loaderFound = lookupPtr->header(fp, width, height);
+ }
+ if (loaderFound)
+ {
+ break;
+ }
+ }
+ }
+
+ // finally try formats that do not use magic bytes
+ if ( false == loaderFound )
+ {
+ for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
+ lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_TOTAL_COUNT;
+ ++lookupPtr )
+ {
+ // to seperate ico file format and wbmp file format
+ unsigned int width = 0;
+ unsigned int height = 0;
+ loaderFound = lookupPtr->header(fp, width, height);
+ if (loaderFound)
+ {
+ break;
+ }
+ }
+ }
+
+ // if a loader was found set the outputs
+ if ( loaderFound )
+ {
+ loader = lookupPtr->loader;
+ header = lookupPtr->header;
+ profile = lookupPtr->profile;
+ }
+
+ // Reset to the start of the file.
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking to start of file\n");
+ }
+
+ return loaderFound;
+}
+
+} // anonymous namespace
+
+
+namespace ImageLoader
+{
+
+bool ConvertStreamToBitmap( const BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer )
+{
+ DALI_LOG_TRACE_METHOD( gLogFilter );
+
+ bool result = false;
+
+ if (fp != NULL)
+ {
+ LoadBitmapFunction function;
+ LoadBitmapHeaderFunction header;
+
+ Bitmap::Profile profile;
+
+ if ( GetBitmapLoaderFunctions( fp,
+ GetFormatHint( path ),
+ function,
+ header,
+ profile ) )
+ {
+ const ScalingParameters scalingParameters( resource.size, resource.scalingMode, resource.samplingMode );
+ const ImageLoader::Input input( fp, scalingParameters, resource.orientationCorrection );
+
+ // Run the image type decoder:
+ result = function( input, pixelBuffer );
+
+ if (!result)
+ {
+ DALI_LOG_WARNING( "Unable to convert %s\n", path.c_str() );
+ pixelBuffer.Reset();
+ }
+
+ pixelBuffer = Internal::Platform::ApplyAttributesToBitmap( pixelBuffer, resource.size, resource.scalingMode, resource.samplingMode );
+ }
+ else
+ {
+ DALI_LOG_WARNING( "Image Decoder for %s unavailable\n", path.c_str() );
+ }
+ }
+
+ return result;
+}
+
+ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path )
+{
+ ResourcePointer result;
+ Dali::Devel::PixelBuffer bitmap;
+
+ Internal::Platform::FileReader fileReader( path );
+ FILE * const fp = fileReader.GetFile();
+ if( fp != NULL )
+ {
+ bool success = ConvertStreamToBitmap(resource, path, fp, bitmap);
+ if (success && bitmap)
+ {
+ Bitmap::Profile profile{Bitmap::Profile::BITMAP_2D_PACKED_PIXELS};
+
+ // For backward compatibility the Bitmap must be created
+ auto retval = Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD);
+
+ DALI_LOG_SET_OBJECT_STRING( retval, path );
+
+ retval->GetPackedPixelsProfile()->ReserveBuffer(
+ bitmap.GetPixelFormat(),
+ bitmap.GetWidth(),
+ bitmap.GetHeight(),
+ bitmap.GetWidth(),
+ bitmap.GetHeight()
+ );
+
+ auto& impl = Dali::GetImplementation(bitmap);
+
+ std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer());
+ result.Reset(retval);
+ }
+ }
+ return result;
+}
+
+///@ToDo: Rename GetClosestImageSize() functions. Make them use the orientation correction and scaling information. Requires jpeg loader to tell us about reorientation. [Is there still a requirement for this functionality at all?]
+ImageDimensions GetClosestImageSize( const std::string& filename,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection )
+{
+ unsigned int width = 0;
+ unsigned int height = 0;
+
+ Internal::Platform::FileReader fileReader( filename );
+ FILE *fp = fileReader.GetFile();
+ if (fp != NULL)
+ {
+ LoadBitmapFunction loaderFunction;
+ LoadBitmapHeaderFunction headerFunction;
+ Bitmap::Profile profile;
+
+ if ( GetBitmapLoaderFunctions( fp,
+ GetFormatHint(filename),
+ loaderFunction,
+ headerFunction,
+ profile ) )
+ {
+ const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
+
+ const bool read_res = headerFunction( input, width, height );
+ if(!read_res)
+ {
+ DALI_LOG_WARNING("Image Decoder failed to read header for %s\n", filename.c_str());
+ }
+ }
+ else
+ {
+ DALI_LOG_WARNING("Image Decoder for %s unavailable\n", filename.c_str());
+ }
+ }
+ return ImageDimensions( width, height );
+}
+
+ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection )
+{
+ unsigned int width = 0;
+ unsigned int height = 0;
+
+ // Get the blob of binary data that we need to decode:
+ DALI_ASSERT_DEBUG( resourceBuffer );
+ Dali::RefCountedVector<uint8_t>* const encodedBlob = reinterpret_cast<Dali::RefCountedVector<uint8_t>*>( resourceBuffer.Get() );
+
+ if( encodedBlob != 0 )
+ {
+ if( encodedBlob->GetVector().Size() )
+ {
+ // Open a file handle on the memory buffer:
+ Internal::Platform::FileReader fileReader( encodedBlob->GetVector() );
+ FILE *fp = fileReader.GetFile();
+ if ( fp != NULL )
+ {
+ LoadBitmapFunction loaderFunction;
+ LoadBitmapHeaderFunction headerFunction;
+ Bitmap::Profile profile;
+
+ if ( GetBitmapLoaderFunctions( fp,
+ FORMAT_UNKNOWN,
+ loaderFunction,
+ headerFunction,
+ profile ) )
+ {
+ const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
+ const bool read_res = headerFunction( input, width, height );
+ if( !read_res )
+ {
+ DALI_LOG_WARNING( "Image Decoder failed to read header for resourceBuffer\n" );
+ }
+ }
+ }
+ }
+ }
+ return ImageDimensions( width, height );
+}
+
+} // ImageLoader
+} // TizenPlatform
+} // Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
+#define __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/images/image-operations.h>
+#include <dali/integration-api/resource-types.h>
+#include <dali/integration-api/bitmap.h>
+#include <dali/public-api/images/pixel-data.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <string>
+
+namespace Dali
+{
+namespace Integration
+{
+typedef IntrusivePtr<Dali::RefObject> ResourcePointer;
+} // Integration
+
+namespace TizenPlatform
+{
+namespace ImageLoader
+{
+/**
+ * Convert a file stream into a bitmap.
+ * @param[in] resource The resource to convert.
+ * @param[in] path The path to the resource.
+ * @param[in] fp File Pointer. Closed on exit.
+ * @param[out] bitmap Pointer to write bitmap to
+ * @return true on success, false on failure
+ */
+bool ConvertStreamToBitmap( const Integration::BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer );
+
+/**
+ * Convert a bitmap and write to a file stream.
+ * @param[in] path The path to the resource.
+ * @param[in] fp File Pointer. Closed on exit.
+ * @param[out] pixelData Reference to PixelData object.
+ * @return true on success, false on failure
+ */
+bool ConvertBitmapToStream( std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer );
+
+/**
+ * Loads an image synchronously
+ * @param resource details of the image
+ * @param path to the image
+ * @return bitmap
+ */
+Integration::ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path );
+
+/**
+ * @returns the closest image size
+ */
+ImageDimensions GetClosestImageSize( const std::string& filename,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection );
+
+/**
+ * @returns the closest image size
+ */
+ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection );
+
+} // ImageLoader
+} // TizenPlatform
+} // Dali
+
+#endif // __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/imaging/common/image-operations.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+#include <stddef.h>
+#include <cmath>
+#include <limits>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/public-api/math/vector2.h>
+#include <third-party/resampler/resampler.h>
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+
+// INTERNAL INCLUDES
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Platform
+{
+
+namespace
+{
+
+// The BORDER_FILL_VALUE is a single byte value that is used for horizontal and vertical borders.
+// A value of 0x00 gives us transparency for pixel buffers with an alpha channel, or black otherwise.
+// We can optionally use a Vector4 color here, but at reduced fill speed.
+const uint8_t BORDER_FILL_VALUE( 0x00 );
+// A maximum size limit for newly created bitmaps. ( 1u << 16 ) - 1 is chosen as we are using 16bit words for dimensions.
+const unsigned int MAXIMUM_TARGET_BITMAP_SIZE( ( 1u << 16 ) - 1 );
+
+// Constants used by the ImageResampler.
+const float DEFAULT_SOURCE_GAMMA = 1.75f; ///< Default source gamma value used in the Resampler() function. Partial gamma correction looks better on mips. Set to 1.0 to disable gamma correction.
+const float FILTER_SCALE = 1.f; ///< Default filter scale value used in the Resampler() function. Filter scale - values < 1.0 cause aliasing, but create sharper looking mips.
+
+using Integration::Bitmap;
+using Integration::BitmapPtr;
+typedef unsigned char PixelBuffer;
+
+/**
+ * @brief 4 byte pixel structure.
+ */
+struct Pixel4Bytes
+{
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+ uint8_t a;
+} __attribute__((packed, aligned(4))); //< Tell the compiler it is okay to use a single 32 bit load.
+
+/**
+ * @brief RGB888 pixel structure.
+ */
+struct Pixel3Bytes
+{
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+} __attribute__((packed, aligned(1)));
+
+/**
+ * @brief RGB565 pixel typedefed from a short.
+ *
+ * Access fields by manual shifting and masking.
+ */
+typedef uint16_t PixelRGB565;
+
+/**
+ * @brief a Pixel composed of two independent byte components.
+ */
+struct Pixel2Bytes
+{
+ uint8_t l;
+ uint8_t a;
+} __attribute__((packed, aligned(2))); //< Tell the compiler it is okay to use a single 16 bit load.
+
+
+#if defined(DEBUG_ENABLED)
+/**
+ * Disable logging of image operations or make it verbose from the commandline
+ * as follows (e.g., for dali demo app):
+ * <code>
+ * LOG_IMAGE_OPERATIONS=0 dali-demo #< off
+ * LOG_IMAGE_OPERATIONS=3 dali-demo #< on, verbose
+ * </code>
+ */
+Debug::Filter* gImageOpsLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_IMAGE_OPERATIONS" );
+#endif
+
+/** @return The greatest even number less than or equal to the argument. */
+inline unsigned int EvenDown( const unsigned int a )
+{
+ const unsigned int evened = a & ~1u;
+ return evened;
+}
+
+/**
+ * @brief Log bad parameters.
+ */
+void ValidateScalingParameters( const unsigned int inputWidth,
+ const unsigned int inputHeight,
+ const unsigned int desiredWidth,
+ const unsigned int desiredHeight )
+{
+ if( desiredWidth > inputWidth || desiredHeight > inputHeight )
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Upscaling not supported (%u, %u -> %u, %u).\n", inputWidth, inputHeight, desiredWidth, desiredHeight );
+ }
+
+ if( desiredWidth == 0u || desiredHeight == 0u )
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Downscaling to a zero-area target is pointless.\n" );
+ }
+
+ if( inputWidth == 0u || inputHeight == 0u )
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Zero area images cannot be scaled\n" );
+ }
+}
+
+/**
+ * @brief Do debug assertions common to all scanline halving functions.
+ * @note Inline and in anon namespace so should boil away in release builds.
+ */
+inline void DebugAssertScanlineParameters( const uint8_t * const pixels, const unsigned int width )
+{
+ DALI_ASSERT_DEBUG( pixels && "Null pointer." );
+ DALI_ASSERT_DEBUG( width > 1u && "Can't average fewer than two pixels." );
+ DALI_ASSERT_DEBUG( width < 131072u && "Unusually wide image: are you sure you meant to pass that value in?" );
+}
+
+/**
+ * @brief Assertions on params to functions averaging pairs of scanlines.
+ * @note Inline as intended to boil away in release.
+ */
+inline void DebugAssertDualScanlineParameters( const uint8_t * const scanline1,
+ const uint8_t * const scanline2,
+ uint8_t* const outputScanline,
+ const size_t widthInComponents )
+{
+ DALI_ASSERT_DEBUG( scanline1 && "Null pointer." );
+ DALI_ASSERT_DEBUG( scanline2 && "Null pointer." );
+ DALI_ASSERT_DEBUG( outputScanline && "Null pointer." );
+ DALI_ASSERT_DEBUG( ((scanline1 >= scanline2 + widthInComponents) || (scanline2 >= scanline1 + widthInComponents )) && "Scanlines alias." );
+ DALI_ASSERT_DEBUG( ((outputScanline >= (scanline2 + widthInComponents)) || (scanline2 >= (scanline1 + widthInComponents))) && "Scanline 2 aliases output." );
+}
+
+/**
+ * @brief Converts a scaling mode to the definition of which dimensions matter when box filtering as a part of that mode.
+ */
+BoxDimensionTest DimensionTestForScalingMode( FittingMode::Type fittingMode )
+{
+ BoxDimensionTest dimensionTest;
+ dimensionTest = BoxDimensionTestEither;
+
+ switch( fittingMode )
+ {
+ // Shrink to fit attempts to make one or zero dimensions smaller than the
+ // desired dimensions and one or two dimensions exactly the same as the desired
+ // ones, so as long as one dimension is larger than the desired size, box
+ // filtering can continue even if the second dimension is smaller than the
+ // desired dimensions:
+ case FittingMode::SHRINK_TO_FIT:
+ {
+ dimensionTest = BoxDimensionTestEither;
+ break;
+ }
+ // Scale to fill mode keeps both dimensions at least as large as desired:
+ case FittingMode::SCALE_TO_FILL:
+ {
+ dimensionTest = BoxDimensionTestBoth;
+ break;
+ }
+ // Y dimension is irrelevant when downscaling in FIT_WIDTH mode:
+ case FittingMode::FIT_WIDTH:
+ {
+ dimensionTest = BoxDimensionTestX;
+ break;
+ }
+ // X Dimension is ignored by definition in FIT_HEIGHT mode:
+ case FittingMode::FIT_HEIGHT:
+ {
+ dimensionTest = BoxDimensionTestY;
+ break;
+ }
+ }
+
+ return dimensionTest;
+}
+
+/**
+ * @brief Work out the dimensions for a uniform scaling of the input to map it
+ * into the target while effecting ShinkToFit scaling mode.
+ */
+ImageDimensions FitForShrinkToFit( ImageDimensions target, ImageDimensions source )
+{
+ // Scale the input by the least extreme of the two dimensions:
+ const float widthScale = target.GetX() / float(source.GetX());
+ const float heightScale = target.GetY() / float(source.GetY());
+ const float scale = widthScale < heightScale ? widthScale : heightScale;
+
+ // Do no scaling at all if the result would increase area:
+ if( scale >= 1.0f )
+ {
+ return source;
+ }
+
+ return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
+}
+
+/**
+ * @brief Work out the dimensions for a uniform scaling of the input to map it
+ * into the target while effecting SCALE_TO_FILL scaling mode.
+ * @note An image scaled into the output dimensions will need either top and
+ * bottom or left and right to be cropped away unless the source was pre-cropped
+ * to match the destination aspect ratio.
+ */
+ImageDimensions FitForScaleToFill( ImageDimensions target, ImageDimensions source )
+{
+ DALI_ASSERT_DEBUG( source.GetX() > 0 && source.GetY() > 0 && "Zero-area rectangles should not be passed-in" );
+ // Scale the input by the least extreme of the two dimensions:
+ const float widthScale = target.GetX() / float(source.GetX());
+ const float heightScale = target.GetY() / float(source.GetY());
+ const float scale = widthScale > heightScale ? widthScale : heightScale;
+
+ // Do no scaling at all if the result would increase area:
+ if( scale >= 1.0f )
+ {
+ return source;
+ }
+
+ return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
+}
+
+/**
+ * @brief Work out the dimensions for a uniform scaling of the input to map it
+ * into the target while effecting FIT_WIDTH scaling mode.
+ */
+ImageDimensions FitForFitWidth( ImageDimensions target, ImageDimensions source )
+{
+ DALI_ASSERT_DEBUG( source.GetX() > 0 && "Cant fit a zero-dimension rectangle." );
+ const float scale = target.GetX() / float(source.GetX());
+
+ // Do no scaling at all if the result would increase area:
+ if( scale >= 1.0f )
+ {
+ return source;
+ }
+ return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
+}
+
+/**
+ * @brief Work out the dimensions for a uniform scaling of the input to map it
+ * into the target while effecting FIT_HEIGHT scaling mode.
+ */
+ImageDimensions FitForFitHeight( ImageDimensions target, ImageDimensions source )
+{
+ DALI_ASSERT_DEBUG( source.GetY() > 0 && "Cant fit a zero-dimension rectangle." );
+ const float scale = target.GetY() / float(source.GetY());
+
+ // Do no scaling at all if the result would increase area:
+ if( scale >= 1.0f )
+ {
+ return source;
+ }
+
+ return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
+}
+
+/**
+ * @brief Generate the rectangle to use as the target of a pixel sampling pass
+ * (e.g., nearest or linear).
+ */
+ImageDimensions FitToScalingMode( ImageDimensions requestedSize, ImageDimensions sourceSize, FittingMode::Type fittingMode )
+{
+ ImageDimensions fitDimensions;
+ switch( fittingMode )
+ {
+ case FittingMode::SHRINK_TO_FIT:
+ {
+ fitDimensions = FitForShrinkToFit( requestedSize, sourceSize );
+ break;
+ }
+ case FittingMode::SCALE_TO_FILL:
+ {
+ fitDimensions = FitForScaleToFill( requestedSize, sourceSize );
+ break;
+ }
+ case FittingMode::FIT_WIDTH:
+ {
+ fitDimensions = FitForFitWidth( requestedSize, sourceSize );
+ break;
+ }
+ case FittingMode::FIT_HEIGHT:
+ {
+ fitDimensions = FitForFitHeight( requestedSize, sourceSize );
+ break;
+ }
+ }
+
+ return fitDimensions;
+}
+
+/**
+ * @brief Calculate the number of lines on the X and Y axis that need to be
+ * either added or removed with repect to the specified fitting mode.
+ * (e.g., nearest or linear).
+ * @param[in] sourceSize The size of the source image
+ * @param[in] fittingMode The fitting mode to use
+ * @param[in/out] requestedSize The target size that the image will be fitted to.
+ * If the source image is smaller than the requested size, the source is not scaled up.
+ * So we reduce the target size while keeping aspect by lowering resolution.
+ * @param[out] scanlinesToCrop The number of scanlines to remove from the image (can be negative to represent Y borders required)
+ * @param[out] columnsToCrop The number of columns to remove from the image (can be negative to represent X borders required)
+ */
+void CalculateBordersFromFittingMode( ImageDimensions sourceSize, FittingMode::Type fittingMode, ImageDimensions& requestedSize, int& scanlinesToCrop, int& columnsToCrop )
+{
+ const unsigned int sourceWidth( sourceSize.GetWidth() );
+ const unsigned int sourceHeight( sourceSize.GetHeight() );
+ const float targetAspect( static_cast< float >( requestedSize.GetWidth() ) / static_cast< float >( requestedSize.GetHeight() ) );
+ int finalWidth = 0;
+ int finalHeight = 0;
+
+ switch( fittingMode )
+ {
+ case FittingMode::FIT_WIDTH:
+ {
+ finalWidth = sourceWidth;
+ finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
+
+ columnsToCrop = 0;
+ scanlinesToCrop = -( finalHeight - sourceHeight );
+ break;
+ }
+
+ case FittingMode::FIT_HEIGHT:
+ {
+ finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
+ finalHeight = sourceHeight;
+
+ columnsToCrop = -( finalWidth - sourceWidth );
+ scanlinesToCrop = 0;
+ break;
+ }
+
+ case FittingMode::SHRINK_TO_FIT:
+ {
+ const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) );
+ if( sourceAspect > targetAspect )
+ {
+ finalWidth = sourceWidth;
+ finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
+
+ columnsToCrop = 0;
+ scanlinesToCrop = -( finalHeight - sourceHeight );
+ }
+ else
+ {
+ finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
+ finalHeight = sourceHeight;
+
+ columnsToCrop = -( finalWidth - sourceWidth );
+ scanlinesToCrop = 0;
+ }
+ break;
+ }
+
+ case FittingMode::SCALE_TO_FILL:
+ {
+ const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) );
+ if( sourceAspect > targetAspect )
+ {
+ finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
+ finalHeight = sourceHeight;
+
+ columnsToCrop = -( finalWidth - sourceWidth );
+ scanlinesToCrop = 0;
+ }
+ else
+ {
+ finalWidth = sourceWidth;
+ finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
+
+ columnsToCrop = 0;
+ scanlinesToCrop = -( finalHeight - sourceHeight );
+ }
+ break;
+ }
+ }
+
+ requestedSize.SetWidth( finalWidth );
+ requestedSize.SetHeight( finalHeight );
+}
+
+/**
+ * @brief Construct a pixel buffer object from a copy of the pixel array passed in.
+ */
+Dali::Devel::PixelBuffer MakePixelBuffer( const uint8_t * const pixels, Pixel::Format pixelFormat, unsigned int width, unsigned int height )
+{
+ DALI_ASSERT_DEBUG( pixels && "Null bitmap buffer to copy." );
+
+ // Allocate a pixel buffer to hold the image passed in:
+ auto newBitmap = Dali::Devel::PixelBuffer::New( width, height, pixelFormat );
+
+ // Copy over the pixels from the downscaled image that was generated in-place in the pixel buffer of the input bitmap:
+ memcpy( newBitmap.GetBuffer(), pixels, width * height * Pixel::GetBytesPerPixel( pixelFormat ) );
+ return newBitmap;
+}
+
+/**
+ * @brief Work out the desired width and height, accounting for zeros.
+ *
+ * @param[in] bitmapWidth Width of image before processing.
+ * @param[in] bitmapHeight Height of image before processing.
+ * @param[in] requestedWidth Width of area to scale image into. Can be zero.
+ * @param[in] requestedHeight Height of area to scale image into. Can be zero.
+ * @return Dimensions of area to scale image into after special rules are applied.
+ */
+ImageDimensions CalculateDesiredDimensions( unsigned int bitmapWidth, unsigned int bitmapHeight, unsigned int requestedWidth, unsigned int requestedHeight )
+{
+ unsigned int maxSize = Dali::GetMaxTextureSize();
+
+ // If no dimensions have been requested, default to the source ones:
+ if( requestedWidth == 0 && requestedHeight == 0 )
+ {
+ if( bitmapWidth <= maxSize && bitmapHeight <= maxSize )
+ {
+ return ImageDimensions( bitmapWidth, bitmapHeight );
+ }
+ else
+ {
+ // Calculate the size from the max texture size and the source image aspect ratio
+ if( bitmapWidth > bitmapHeight )
+ {
+ return ImageDimensions( maxSize, bitmapHeight * maxSize / static_cast< float >( bitmapWidth ) + 0.5f );
+ }
+ else
+ {
+ return ImageDimensions( bitmapWidth * maxSize / static_cast< float >( bitmapHeight ) + 0.5f, maxSize );
+ }
+ }
+ }
+
+ // If both dimensions have values requested, use them both:
+ if( requestedWidth != 0 && requestedHeight != 0 )
+ {
+ if( requestedWidth <= maxSize && requestedHeight <= maxSize )
+ {
+ return ImageDimensions( requestedWidth, requestedHeight );
+ }
+ else
+ {
+ // Calculate the size from the max texture size and the source image aspect ratio
+ if( requestedWidth > requestedHeight )
+ {
+ return ImageDimensions( maxSize, requestedHeight * maxSize / static_cast< float >( requestedWidth ) + 0.5f );
+ }
+ else
+ {
+ return ImageDimensions( requestedWidth * maxSize / static_cast< float >( requestedHeight ) + 0.5f, maxSize );
+ }
+ }
+ }
+
+ // Only one of the dimensions has been requested. Calculate the other from
+ // the requested one and the source image aspect ratio:
+ if( requestedWidth != 0 )
+ {
+ requestedWidth = std::min( requestedWidth, maxSize );
+ return ImageDimensions( requestedWidth, bitmapHeight / float(bitmapWidth) * requestedWidth + 0.5f );
+ }
+
+ requestedHeight = std::min( requestedHeight, maxSize );
+ return ImageDimensions( bitmapWidth / float(bitmapHeight) * requestedHeight + 0.5f, requestedHeight );
+}
+
+} // namespace - unnamed
+
+ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions )
+{
+ return CalculateDesiredDimensions( rawDimensions.GetWidth(), rawDimensions.GetHeight(), requestedDimensions.GetWidth(), requestedDimensions.GetHeight() ) ;
+}
+
+/**
+ * @brief Apply cropping and padding for specified fitting mode.
+ *
+ * Once the bitmap has been (optionally) downscaled to an appropriate size, this method performs alterations
+ * based on the fitting mode.
+ *
+ * This will add vertical or horizontal borders if necessary.
+ * Crop the source image data vertically or horizontally if necessary.
+ * The aspect of the source image is preserved.
+ * If the source image is smaller than the desired size, the algorithm will modify the the newly created
+ * bitmaps dimensions to only be as large as necessary, as a memory saving optimization. This will cause
+ * GPU scaling to be performed at render time giving the same result with less texture traversal.
+ *
+ * @param[in] bitmap The source pixel buffer to perform modifications on.
+ * @param[in] desiredDimensions The target dimensions to aim to fill based on the fitting mode.
+ * @param[in] fittingMode The fitting mode to use.
+ *
+ * @return A new bitmap with the padding and cropping required for fitting mode applied.
+ * If no modification is needed or possible, the passed in bitmap is returned.
+ */
+Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode );
+
+/**
+ * @brief Adds horizontal or vertical borders to the source image.
+ *
+ * @param[in] targetPixels The destination image pointer to draw the borders on.
+ * @param[in] bytesPerPixel The number of bytes per pixel of the target pixel buffer.
+ * @param[in] targetDimensions The dimensions of the destination image.
+ * @param[in] padDimensions The columns and scanlines to pad with borders.
+ */
+void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions );
+
+Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode )
+{
+ if( bitmap )
+ {
+ // Calculate the desired box, accounting for a possible zero component:
+ const ImageDimensions desiredDimensions = CalculateDesiredDimensions( bitmap.GetWidth(), bitmap.GetHeight(), dimensions.GetWidth(), dimensions.GetHeight() );
+
+ // If a different size than the raw one has been requested, resize the image
+ // maximally using a repeated box filter without making it smaller than the
+ // requested size in either dimension:
+ bitmap = DownscaleBitmap( bitmap, desiredDimensions, fittingMode, samplingMode );
+
+ // Cut the bitmap according to the desired width and height so that the
+ // resulting bitmap has the same aspect ratio as the desired dimensions.
+ // Add crop and add borders if necessary depending on fitting mode.
+ if( bitmap )
+ {
+ bitmap = CropAndPadForFittingMode( bitmap, desiredDimensions, fittingMode );
+ }
+ }
+
+ return bitmap;
+}
+
+Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode )
+{
+ const unsigned int inputWidth = bitmap.GetWidth();
+ const unsigned int inputHeight = bitmap.GetHeight();
+
+ if( desiredDimensions.GetWidth() < 1u || desiredDimensions.GetHeight() < 1u )
+ {
+ DALI_LOG_WARNING( "Image scaling aborted as desired dimensions too small (%u, %u).\n", desiredDimensions.GetWidth(), desiredDimensions.GetHeight() );
+ }
+ else if( inputWidth != desiredDimensions.GetWidth() || inputHeight != desiredDimensions.GetHeight() )
+ {
+ // Calculate any padding or cropping that needs to be done based on the fitting mode.
+ // Note: If the desired size is larger than the original image, the desired size will be
+ // reduced while maintaining the aspect, in order to save unnecessary memory usage.
+ int scanlinesToCrop = 0;
+ int columnsToCrop = 0;
+
+ CalculateBordersFromFittingMode( ImageDimensions( inputWidth, inputHeight ), fittingMode, desiredDimensions, scanlinesToCrop, columnsToCrop );
+
+ unsigned int desiredWidth( desiredDimensions.GetWidth() );
+ unsigned int desiredHeight( desiredDimensions.GetHeight() );
+
+ // Action the changes by making a new bitmap with the central part of the loaded one if required.
+ if( scanlinesToCrop != 0 || columnsToCrop != 0 )
+ {
+ // Split the adding and removing of scanlines and columns into separate variables,
+ // so we can use one piece of generic code to action the changes.
+ unsigned int scanlinesToPad = 0;
+ unsigned int columnsToPad = 0;
+ if( scanlinesToCrop < 0 )
+ {
+ scanlinesToPad = -scanlinesToCrop;
+ scanlinesToCrop = 0;
+ }
+ if( columnsToCrop < 0 )
+ {
+ columnsToPad = -columnsToCrop;
+ columnsToCrop = 0;
+ }
+
+ // If there is no filtering, then the final image size can become very large, exit if larger than maximum.
+ if( ( desiredWidth > MAXIMUM_TARGET_BITMAP_SIZE ) || ( desiredHeight > MAXIMUM_TARGET_BITMAP_SIZE ) ||
+ ( columnsToPad > MAXIMUM_TARGET_BITMAP_SIZE ) || ( scanlinesToPad > MAXIMUM_TARGET_BITMAP_SIZE ) )
+ {
+ DALI_LOG_WARNING( "Image scaling aborted as final dimensions too large (%u, %u).\n", desiredWidth, desiredHeight );
+ return bitmap;
+ }
+
+ // Create new PixelBuffer with the desired size.
+ const auto pixelFormat = bitmap.GetPixelFormat();
+
+ auto croppedBitmap = Devel::PixelBuffer::New( desiredWidth, desiredHeight, pixelFormat );
+
+ // Add some pre-calculated offsets to the bitmap pointers so this is not done within a loop.
+ // The cropping is added to the source pointer, and the padding is added to the destination.
+ const auto bytesPerPixel = Pixel::GetBytesPerPixel( pixelFormat );
+ const PixelBuffer * const sourcePixels = bitmap.GetBuffer() + ( ( ( ( scanlinesToCrop / 2 ) * inputWidth ) + ( columnsToCrop / 2 ) ) * bytesPerPixel );
+ PixelBuffer * const targetPixels = croppedBitmap.GetBuffer();
+ PixelBuffer * const targetPixelsActive = targetPixels + ( ( ( ( scanlinesToPad / 2 ) * desiredWidth ) + ( columnsToPad / 2 ) ) * bytesPerPixel );
+ DALI_ASSERT_DEBUG( sourcePixels && targetPixels );
+
+ // Copy the image data to the new bitmap.
+ // Optimize to a single memcpy if the left and right edges don't need a crop or a pad.
+ unsigned int outputSpan( desiredWidth * bytesPerPixel );
+ if( columnsToCrop == 0 && columnsToPad == 0 )
+ {
+ memcpy( targetPixelsActive, sourcePixels, ( desiredHeight - scanlinesToPad ) * outputSpan );
+ }
+ else
+ {
+ // The width needs to change (due to either a crop or a pad), so we copy a scanline at a time.
+ // Precalculate any constants to optimize the inner loop.
+ const unsigned int inputSpan( inputWidth * bytesPerPixel );
+ const unsigned int copySpan( ( desiredWidth - columnsToPad ) * bytesPerPixel );
+ const unsigned int scanlinesToCopy( desiredHeight - scanlinesToPad );
+
+ for( unsigned int y = 0; y < scanlinesToCopy; ++y )
+ {
+ memcpy( &targetPixelsActive[ y * outputSpan ], &sourcePixels[ y * inputSpan ], copySpan );
+ }
+ }
+
+ // Add vertical or horizontal borders to the final image (if required).
+ desiredDimensions.SetWidth( desiredWidth );
+ desiredDimensions.SetHeight( desiredHeight );
+ AddBorders( croppedBitmap.GetBuffer(), bytesPerPixel, desiredDimensions, ImageDimensions( columnsToPad, scanlinesToPad ) );
+ // Overwrite the loaded bitmap with the cropped version
+ bitmap = croppedBitmap;
+ }
+ }
+
+ return bitmap;
+}
+
+void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions )
+{
+ // Assign ints for faster access.
+ unsigned int desiredWidth( targetDimensions.GetWidth() );
+ unsigned int desiredHeight( targetDimensions.GetHeight() );
+ unsigned int columnsToPad( padDimensions.GetWidth() );
+ unsigned int scanlinesToPad( padDimensions.GetHeight() );
+ unsigned int outputSpan( desiredWidth * bytesPerPixel );
+
+ // Add letterboxing (symmetrical borders) if needed.
+ if( scanlinesToPad > 0 )
+ {
+ // Add a top border. Note: This is (deliberately) rounded down if padding is an odd number.
+ memset( targetPixels, BORDER_FILL_VALUE, ( scanlinesToPad / 2 ) * outputSpan );
+
+ // We subtract scanlinesToPad/2 from scanlinesToPad so that we have the correct
+ // offset for odd numbers (as the top border is 1 pixel smaller in these cases.
+ unsigned int bottomBorderHeight = scanlinesToPad - ( scanlinesToPad / 2 );
+
+ // Bottom border.
+ memset( &targetPixels[ ( desiredHeight - bottomBorderHeight ) * outputSpan ], BORDER_FILL_VALUE, bottomBorderHeight * outputSpan );
+ }
+ else if( columnsToPad > 0 )
+ {
+ // Add a left and right border.
+ // Left:
+ // Pre-calculate span size outside of loop.
+ unsigned int leftBorderSpanWidth( ( columnsToPad / 2 ) * bytesPerPixel );
+ for( unsigned int y = 0; y < desiredHeight; ++y )
+ {
+ memset( &targetPixels[ y * outputSpan ], BORDER_FILL_VALUE, leftBorderSpanWidth );
+ }
+
+ // Right:
+ // Pre-calculate the initial x offset as it is always the same for a small optimization.
+ // We subtract columnsToPad/2 from columnsToPad so that we have the correct
+ // offset for odd numbers (as the left border is 1 pixel smaller in these cases.
+ unsigned int rightBorderWidth = columnsToPad - ( columnsToPad / 2 );
+ PixelBuffer * const destPixelsRightBorder( targetPixels + ( ( desiredWidth - rightBorderWidth ) * bytesPerPixel ) );
+ unsigned int rightBorderSpanWidth = rightBorderWidth * bytesPerPixel;
+
+ for( unsigned int y = 0; y < desiredHeight; ++y )
+ {
+ memset( &destPixelsRightBorder[ y * outputSpan ], BORDER_FILL_VALUE, rightBorderSpanWidth );
+ }
+ }
+}
+
+Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap,
+ ImageDimensions desired,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode )
+{
+ // Source dimensions as loaded from resources (e.g. filesystem):
+ auto bitmapWidth = bitmap.GetWidth();
+ auto bitmapHeight = bitmap.GetHeight();
+ // Desired dimensions (the rectangle to fit the source image to):
+ auto desiredWidth = desired.GetWidth();
+ auto desiredHeight = desired.GetHeight();
+
+ Dali::Devel::PixelBuffer outputBitmap { bitmap };
+
+ // If a different size than the raw one has been requested, resize the image:
+ if(
+ (desiredWidth > 0.0f) && (desiredHeight > 0.0f) &&
+ ((desiredWidth < bitmapWidth) || (desiredHeight < bitmapHeight)) )
+ {
+ auto pixelFormat = bitmap.GetPixelFormat();
+
+ // Do the fast power of 2 iterated box filter to get to roughly the right side if the filter mode requests that:
+ unsigned int shrunkWidth = -1, shrunkHeight = -1;
+ DownscaleInPlacePow2( bitmap.GetBuffer(), pixelFormat, bitmapWidth, bitmapHeight, desiredWidth, desiredHeight, fittingMode, samplingMode, shrunkWidth, shrunkHeight );
+
+ // Work out the dimensions of the downscaled bitmap, given the scaling mode and desired dimensions:
+ const ImageDimensions filteredDimensions = FitToScalingMode( ImageDimensions( desiredWidth, desiredHeight ), ImageDimensions( shrunkWidth, shrunkHeight ), fittingMode );
+ const unsigned int filteredWidth = filteredDimensions.GetWidth();
+ const unsigned int filteredHeight = filteredDimensions.GetHeight();
+
+ // Run a filter to scale down the bitmap if it needs it:
+ bool filtered = false;
+ if( filteredWidth < shrunkWidth || filteredHeight < shrunkHeight )
+ {
+ if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR ||
+ samplingMode == SamplingMode::NEAREST || samplingMode == SamplingMode::BOX_THEN_NEAREST )
+ {
+ outputBitmap = Dali::Devel::PixelBuffer::New( filteredWidth, filteredHeight, pixelFormat );
+
+ if( outputBitmap )
+ {
+ if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR )
+ {
+ LinearSample( bitmap.GetBuffer(), ImageDimensions(shrunkWidth, shrunkHeight), pixelFormat, outputBitmap.GetBuffer(), filteredDimensions );
+ }
+ else
+ {
+ PointSample( bitmap.GetBuffer(), shrunkWidth, shrunkHeight, pixelFormat, outputBitmap.GetBuffer(), filteredWidth, filteredHeight );
+ }
+ filtered = true;
+ }
+ }
+ }
+ // Copy out the 2^x downscaled, box-filtered pixels if no secondary filter (point or linear) was applied:
+ if( filtered == false && ( shrunkWidth < bitmapWidth || shrunkHeight < bitmapHeight ) )
+ {
+ outputBitmap = MakePixelBuffer( bitmap.GetBuffer(), pixelFormat, shrunkWidth, shrunkHeight );
+ }
+ }
+
+ return outputBitmap;
+}
+
+namespace
+{
+/**
+ * @brief Returns whether to keep box filtering based on whether downscaled dimensions will overshoot the desired ones aty the next step.
+ * @param test Which combination of the two dimensions matter for terminating the filtering.
+ * @param scaledWidth The width of the current downscaled image.
+ * @param scaledHeight The height of the current downscaled image.
+ * @param desiredWidth The target width for the downscaling.
+ * @param desiredHeight The target height for the downscaling.
+ */
+bool ContinueScaling( BoxDimensionTest test, unsigned int scaledWidth, unsigned int scaledHeight, unsigned int desiredWidth, unsigned int desiredHeight )
+{
+ bool keepScaling = false;
+ const unsigned int nextWidth = scaledWidth >> 1u;
+ const unsigned int nextHeight = scaledHeight >> 1u;
+
+ if( nextWidth >= 1u && nextHeight >= 1u )
+ {
+ switch( test )
+ {
+ case BoxDimensionTestEither:
+ {
+ keepScaling = nextWidth >= desiredWidth || nextHeight >= desiredHeight;
+ break;
+ }
+ case BoxDimensionTestBoth:
+ {
+ keepScaling = nextWidth >= desiredWidth && nextHeight >= desiredHeight;
+ break;
+ }
+ case BoxDimensionTestX:
+ {
+ keepScaling = nextWidth >= desiredWidth;
+ break;
+ }
+ case BoxDimensionTestY:
+ {
+ keepScaling = nextHeight >= desiredHeight;
+ break;
+ }
+ }
+ }
+
+ return keepScaling;
+}
+
+/**
+ * @brief A shared implementation of the overall iterative box filter
+ * downscaling algorithm.
+ *
+ * Specialise this for particular pixel formats by supplying the number of bytes
+ * per pixel and two functions: one for averaging pairs of neighbouring pixels
+ * on a single scanline, and a second for averaging pixels at corresponding
+ * positions on different scanlines.
+ **/
+template<
+ int BYTES_PER_PIXEL,
+ void (*HalveScanlineInPlace)( unsigned char * const pixels, const unsigned int width ),
+ void (*AverageScanlines) ( const unsigned char * const scanline1, const unsigned char * const __restrict__ scanline2, unsigned char* const outputScanline, const unsigned int width )
+>
+void DownscaleInPlacePow2Generic( unsigned char * const pixels,
+ const unsigned int inputWidth,
+ const unsigned int inputHeight,
+ const unsigned int desiredWidth,
+ const unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned& outWidth,
+ unsigned& outHeight )
+{
+ if( pixels == 0 )
+ {
+ return;
+ }
+ ValidateScalingParameters( inputWidth, inputHeight, desiredWidth, desiredHeight );
+
+ // Scale the image until it would be smaller than desired, stopping if the
+ // resulting height or width would be less than 1:
+ unsigned int scaledWidth = inputWidth, scaledHeight = inputHeight;
+ while( ContinueScaling( dimensionTest, scaledWidth, scaledHeight, desiredWidth, desiredHeight ) )
+ {
+ const unsigned int lastWidth = scaledWidth;
+ scaledWidth >>= 1u;
+ scaledHeight >>= 1u;
+
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Scaling to %u\t%u.\n", scaledWidth, scaledHeight );
+
+ const unsigned int lastScanlinePair = scaledHeight - 1;
+
+ // Scale pairs of scanlines until any spare one at the end is dropped:
+ for( unsigned int y = 0; y <= lastScanlinePair; ++y )
+ {
+ // Scale two scanlines horizontally:
+ HalveScanlineInPlace( &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], lastWidth );
+ HalveScanlineInPlace( &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], lastWidth );
+
+ // Scale vertical pairs of pixels while the last two scanlines are still warm in
+ // the CPU cache(s):
+ // Note, better access patterns for cache-coherence are possible for very large
+ // images but even a 4k wide RGB888 image will use just 24kB of cache (4k pixels
+ // * 3 Bpp * 2 scanlines) for two scanlines on the first iteration.
+ AverageScanlines(
+ &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL],
+ &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL],
+ &pixels[y * scaledWidth * BYTES_PER_PIXEL],
+ scaledWidth );
+ }
+ }
+
+ ///@note: we could finish off with one of two mutually exclusive passes, one squashing horizontally as far as possible, and the other vertically, if we knew a following cpu point or bilinear filter would restore the desired aspect ratio.
+ outWidth = scaledWidth;
+ outHeight = scaledHeight;
+}
+
+}
+
+void HalveScanlineInPlaceRGB888( unsigned char * const pixels, const unsigned int width )
+{
+ DebugAssertScanlineParameters( pixels, width );
+
+ const unsigned int lastPair = EvenDown( width - 2 );
+
+ for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
+ {
+ // Load all the byte pixel components we need:
+ const unsigned int c11 = pixels[pixel * 3];
+ const unsigned int c12 = pixels[pixel * 3 + 1];
+ const unsigned int c13 = pixels[pixel * 3 + 2];
+ const unsigned int c21 = pixels[pixel * 3 + 3];
+ const unsigned int c22 = pixels[pixel * 3 + 4];
+ const unsigned int c23 = pixels[pixel * 3 + 5];
+
+ // Save the averaged byte pixel components:
+ pixels[outPixel * 3] = AverageComponent( c11, c21 );
+ pixels[outPixel * 3 + 1] = AverageComponent( c12, c22 );
+ pixels[outPixel * 3 + 2] = AverageComponent( c13, c23 );
+ }
+}
+
+void HalveScanlineInPlaceRGBA8888( unsigned char * const pixels, const unsigned int width )
+{
+ DebugAssertScanlineParameters( pixels, width );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
+
+ uint32_t* const alignedPixels = reinterpret_cast<uint32_t*>(pixels);
+
+ const unsigned int lastPair = EvenDown( width - 2 );
+
+ for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
+ {
+ const uint32_t averaged = AveragePixelRGBA8888( alignedPixels[pixel], alignedPixels[pixel + 1] );
+ alignedPixels[outPixel] = averaged;
+ }
+}
+
+void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width )
+{
+ DebugAssertScanlineParameters( pixels, width );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
+
+ uint16_t* const alignedPixels = reinterpret_cast<uint16_t*>(pixels);
+
+ const unsigned int lastPair = EvenDown( width - 2 );
+
+ for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
+ {
+ const uint32_t averaged = AveragePixelRGB565( alignedPixels[pixel], alignedPixels[pixel + 1] );
+ alignedPixels[outPixel] = averaged;
+ }
+}
+
+void HalveScanlineInPlace2Bytes( unsigned char * const pixels, const unsigned int width )
+{
+ DebugAssertScanlineParameters( pixels, width );
+
+ const unsigned int lastPair = EvenDown( width - 2 );
+
+ for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
+ {
+ // Load all the byte pixel components we need:
+ const unsigned int c11 = pixels[pixel * 2];
+ const unsigned int c12 = pixels[pixel * 2 + 1];
+ const unsigned int c21 = pixels[pixel * 2 + 2];
+ const unsigned int c22 = pixels[pixel * 2 + 3];
+
+ // Save the averaged byte pixel components:
+ pixels[outPixel * 2] = AverageComponent( c11, c21 );
+ pixels[outPixel * 2 + 1] = AverageComponent( c12, c22 );
+ }
+}
+
+void HalveScanlineInPlace1Byte( unsigned char * const pixels, const unsigned int width )
+{
+ DebugAssertScanlineParameters( pixels, width );
+
+ const unsigned int lastPair = EvenDown( width - 2 );
+
+ for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
+ {
+ // Load all the byte pixel components we need:
+ const unsigned int c1 = pixels[pixel];
+ const unsigned int c2 = pixels[pixel + 1];
+
+ // Save the averaged byte pixel component:
+ pixels[outPixel] = AverageComponent( c1, c2 );
+ }
+}
+
+/**
+ * @ToDo: Optimise for ARM using a 4 bytes at a time loop wrapped around the single ARMV6 instruction: UHADD8 R4, R0, R5. Note, this is not neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro, or extra power for clocking-up the idle copro.
+ * if (widthInComponents >= 7) { word32* aligned1 = scanline1 + 3 & 3; word32* aligned1_end = scanline1 + widthInPixels & 3; while(aligned1 < aligned1_end) { UHADD8 *aligned1++, *aligned2++, *alignedoutput++ } .. + 0 to 3 spare pixels at each end.
+ */
+void AverageScanlines1( const unsigned char * const scanline1,
+ const unsigned char * const __restrict__ scanline2,
+ unsigned char* const outputScanline,
+ const unsigned int width )
+{
+ DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width );
+
+ for( unsigned int component = 0; component < width; ++component )
+ {
+ outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
+ }
+}
+
+void AverageScanlines2( const unsigned char * const scanline1,
+ const unsigned char * const __restrict__ scanline2,
+ unsigned char* const outputScanline,
+ const unsigned int width )
+{
+ DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 );
+
+ for( unsigned int component = 0; component < width * 2; ++component )
+ {
+ outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
+ }
+}
+
+void AverageScanlines3( const unsigned char * const scanline1,
+ const unsigned char * const __restrict__ scanline2,
+ unsigned char* const outputScanline,
+ const unsigned int width )
+{
+ DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 3 );
+
+ for( unsigned int component = 0; component < width * 3; ++component )
+ {
+ outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
+ }
+}
+
+void AverageScanlinesRGBA8888( const unsigned char * const scanline1,
+ const unsigned char * const __restrict__ scanline2,
+ unsigned char * const outputScanline,
+ const unsigned int width )
+{
+ DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 4 );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline1) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline2) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(outputScanline) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
+
+ const uint32_t* const alignedScanline1 = reinterpret_cast<const uint32_t*>(scanline1);
+ const uint32_t* const alignedScanline2 = reinterpret_cast<const uint32_t*>(scanline2);
+ uint32_t* const alignedOutput = reinterpret_cast<uint32_t*>(outputScanline);
+
+ for( unsigned int pixel = 0; pixel < width; ++pixel )
+ {
+ alignedOutput[pixel] = AveragePixelRGBA8888( alignedScanline1[pixel], alignedScanline2[pixel] );
+ }
+}
+
+void AverageScanlinesRGB565( const unsigned char * const scanline1,
+ const unsigned char * const __restrict__ scanline2,
+ unsigned char * const outputScanline,
+ const unsigned int width )
+{
+ DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline1) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline2) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(outputScanline) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
+
+ const uint16_t* const alignedScanline1 = reinterpret_cast<const uint16_t*>(scanline1);
+ const uint16_t* const alignedScanline2 = reinterpret_cast<const uint16_t*>(scanline2);
+ uint16_t* const alignedOutput = reinterpret_cast<uint16_t*>(outputScanline);
+
+ for( unsigned int pixel = 0; pixel < width; ++pixel )
+ {
+ alignedOutput[pixel] = AveragePixelRGB565( alignedScanline1[pixel], alignedScanline2[pixel] );
+ }
+}
+
+/// Dispatch to pixel format appropriate box filter downscaling functions.
+void DownscaleInPlacePow2( unsigned char * const pixels,
+ Pixel::Format pixelFormat,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ unsigned& outWidth,
+ unsigned& outHeight )
+{
+ outWidth = inputWidth;
+ outHeight = inputHeight;
+ // Perform power of 2 iterated 4:1 box filtering if the requested filter mode requires it:
+ if( samplingMode == SamplingMode::BOX || samplingMode == SamplingMode::BOX_THEN_NEAREST || samplingMode == SamplingMode::BOX_THEN_LINEAR )
+ {
+ // Check the pixel format is one that is supported:
+ if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
+ {
+ const BoxDimensionTest dimensionTest = DimensionTestForScalingMode( fittingMode );
+
+ if( pixelFormat == Pixel::RGBA8888 )
+ {
+ Internal::Platform::DownscaleInPlacePow2RGBA8888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+ }
+ else if( pixelFormat == Pixel::RGB888 )
+ {
+ Internal::Platform::DownscaleInPlacePow2RGB888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+ }
+ else if( pixelFormat == Pixel::RGB565 )
+ {
+ Internal::Platform::DownscaleInPlacePow2RGB565( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+ }
+ else if( pixelFormat == Pixel::LA88 )
+ {
+ Internal::Platform::DownscaleInPlacePow2ComponentPair( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+ }
+ else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
+ {
+ Internal::Platform::DownscaleInPlacePow2SingleBytePerPixel( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+ }
+ else
+ {
+ DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
+ }
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not shrunk: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
+ }
+}
+
+void DownscaleInPlacePow2RGB888( unsigned char *pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned& outWidth,
+ unsigned& outHeight )
+{
+ DownscaleInPlacePow2Generic<3, HalveScanlineInPlaceRGB888, AverageScanlines3>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+}
+
+void DownscaleInPlacePow2RGBA8888( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned& outWidth,
+ unsigned& outHeight )
+{
+ DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
+ DownscaleInPlacePow2Generic<4, HalveScanlineInPlaceRGBA8888, AverageScanlinesRGBA8888>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+}
+
+void DownscaleInPlacePow2RGB565( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight )
+{
+ DownscaleInPlacePow2Generic<2, HalveScanlineInPlaceRGB565, AverageScanlinesRGB565>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+}
+
+/**
+ * @copydoc DownscaleInPlacePow2RGB888
+ *
+ * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565.
+ */
+void DownscaleInPlacePow2ComponentPair( unsigned char *pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned& outWidth,
+ unsigned& outHeight )
+{
+ DownscaleInPlacePow2Generic<2, HalveScanlineInPlace2Bytes, AverageScanlines2>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+}
+
+void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight )
+{
+ DownscaleInPlacePow2Generic<1, HalveScanlineInPlace1Byte, AverageScanlines1>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
+}
+
+namespace
+{
+
+/**
+ * @brief Point sample an image to a new resolution (like GL_NEAREST).
+ *
+ * Template is used purely as a type-safe code generator in this one
+ * compilation unit. Generated code is inlined into type-specific wrapper
+ * functions below which are exported to rest of module.
+ */
+template<typename PIXEL>
+inline void PointSampleAddressablePixels( const uint8_t * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ uint8_t * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ DALI_ASSERT_DEBUG( ((desiredWidth <= inputWidth && desiredHeight <= inputHeight) ||
+ outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL) || outPixels <= inPixels - desiredWidth * desiredHeight * sizeof(PIXEL)) &&
+ "The input and output buffers must not overlap for an upscaling.");
+ DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
+ DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
+
+ if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
+ {
+ return;
+ }
+ const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
+ PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
+ const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
+ const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
+
+ unsigned int inY = 0;
+ for( unsigned int outY = 0; outY < desiredHeight; ++outY )
+ {
+ // Round fixed point y coordinate to nearest integer:
+ const unsigned int integerY = (inY + (1u << 15u)) >> 16u;
+ const PIXEL* const inScanline = &inAligned[inputWidth * integerY];
+ PIXEL* const outScanline = &outAligned[desiredWidth * outY];
+
+ DALI_ASSERT_DEBUG( integerY < inputHeight );
+ DALI_ASSERT_DEBUG( reinterpret_cast<const uint8_t*>(inScanline) < ( inPixels + inputWidth * inputHeight * sizeof(PIXEL) ) );
+ DALI_ASSERT_DEBUG( reinterpret_cast<uint8_t*>(outScanline) < ( outPixels + desiredWidth * desiredHeight * sizeof(PIXEL) ) );
+
+ unsigned int inX = 0;
+ for( unsigned int outX = 0; outX < desiredWidth; ++outX )
+ {
+ // Round the fixed-point x coordinate to an integer:
+ const unsigned int integerX = (inX + (1u << 15u)) >> 16u;
+ const PIXEL* const inPixelAddress = &inScanline[integerX];
+ const PIXEL pixel = *inPixelAddress;
+ outScanline[outX] = pixel;
+ inX += deltaX;
+ }
+ inY += deltaY;
+ }
+}
+
+}
+
+// RGBA8888
+void PointSample4BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ PointSampleAddressablePixels<uint32_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+}
+
+// RGB565, LA88
+void PointSample2BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ PointSampleAddressablePixels<uint16_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+}
+
+// L8, A8
+void PointSample1BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ PointSampleAddressablePixels<uint8_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+}
+
+/* RGB888
+ * RGB888 is a special case as its pixels are not aligned addressable units.
+ */
+void PointSample3BPP( const uint8_t * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ uint8_t * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
+ {
+ return;
+ }
+ const unsigned int BYTES_PER_PIXEL = 3;
+
+ // Generate fixed-point 16.16 deltas in input image coordinates:
+ const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
+ const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
+
+ // Step through output image in whole integer pixel steps while tracking the
+ // corresponding locations in the input image using 16.16 fixed-point
+ // coordinates:
+ unsigned int inY = 0; //< 16.16 fixed-point input image y-coord.
+ for( unsigned int outY = 0; outY < desiredHeight; ++outY )
+ {
+ const unsigned int integerY = (inY + (1u << 15u)) >> 16u;
+ const uint8_t* const inScanline = &inPixels[inputWidth * integerY * BYTES_PER_PIXEL];
+ uint8_t* const outScanline = &outPixels[desiredWidth * outY * BYTES_PER_PIXEL];
+ unsigned int inX = 0; //< 16.16 fixed-point input image x-coord.
+
+ for( unsigned int outX = 0; outX < desiredWidth * BYTES_PER_PIXEL; outX += BYTES_PER_PIXEL )
+ {
+ // Round the fixed-point input coordinate to the address of the input pixel to sample:
+ const unsigned int integerX = (inX + (1u << 15u)) >> 16u;
+ const uint8_t* const inPixelAddress = &inScanline[integerX * BYTES_PER_PIXEL];
+
+ // Issue loads for all pixel color components up-front:
+ const unsigned int c0 = inPixelAddress[0];
+ const unsigned int c1 = inPixelAddress[1];
+ const unsigned int c2 = inPixelAddress[2];
+ ///@ToDo: Optimise - Benchmark one 32bit load that will be unaligned 2/3 of the time + 3 rotate and masks, versus these three aligned byte loads, versus using an RGB packed, aligned(1) struct and letting compiler pick a strategy.
+
+ // Output the pixel components:
+ outScanline[outX] = c0;
+ outScanline[outX + 1] = c1;
+ outScanline[outX + 2] = c2;
+
+ // Increment the fixed-point input coordinate:
+ inX += deltaX;
+ }
+
+ inY += deltaY;
+ }
+}
+
+// Dispatch to a format-appropriate point sampling function:
+void PointSample( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ Pixel::Format pixelFormat,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight )
+{
+ // Check the pixel format is one that is supported:
+ if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
+ {
+ if( pixelFormat == Pixel::RGB888 )
+ {
+ PointSample3BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+ }
+ else if( pixelFormat == Pixel::RGBA8888 )
+ {
+ PointSample4BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+ }
+ else if( pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 )
+ {
+ PointSample2BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+ }
+ else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
+ {
+ PointSample1BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
+ }
+ else
+ {
+ DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not point sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
+ }
+}
+
+// Linear sampling group below
+
+namespace
+{
+
+/** @brief Blend 4 pixels together using horizontal and vertical weights. */
+inline uint8_t BilinearFilter1BPPByte( uint8_t tl, uint8_t tr, uint8_t bl, uint8_t br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ return BilinearFilter1Component( tl, tr, bl, br, fractBlendHorizontal, fractBlendVertical );
+}
+
+/** @copydoc BilinearFilter1BPPByte */
+inline Pixel2Bytes BilinearFilter2Bytes( Pixel2Bytes tl, Pixel2Bytes tr, Pixel2Bytes bl, Pixel2Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ Pixel2Bytes pixel;
+ pixel.l = BilinearFilter1Component( tl.l, tr.l, bl.l, br.l, fractBlendHorizontal, fractBlendVertical );
+ pixel.a = BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical );
+ return pixel;
+}
+
+/** @copydoc BilinearFilter1BPPByte */
+inline Pixel3Bytes BilinearFilterRGB888( Pixel3Bytes tl, Pixel3Bytes tr, Pixel3Bytes bl, Pixel3Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ Pixel3Bytes pixel;
+ pixel.r = BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical );
+ pixel.g = BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical );
+ pixel.b = BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical );
+ return pixel;
+}
+
+/** @copydoc BilinearFilter1BPPByte */
+inline PixelRGB565 BilinearFilterRGB565( PixelRGB565 tl, PixelRGB565 tr, PixelRGB565 bl, PixelRGB565 br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ const PixelRGB565 pixel = (BilinearFilter1Component( tl >> 11u, tr >> 11u, bl >> 11u, br >> 11u, fractBlendHorizontal, fractBlendVertical ) << 11u) +
+ (BilinearFilter1Component( (tl >> 5u) & 63u, (tr >> 5u) & 63u, (bl >> 5u) & 63u, (br >> 5u) & 63u, fractBlendHorizontal, fractBlendVertical ) << 5u) +
+ BilinearFilter1Component( tl & 31u, tr & 31u, bl & 31u, br & 31u, fractBlendHorizontal, fractBlendVertical );
+ return pixel;
+}
+
+/** @copydoc BilinearFilter1BPPByte */
+inline Pixel4Bytes BilinearFilter4Bytes( Pixel4Bytes tl, Pixel4Bytes tr, Pixel4Bytes bl, Pixel4Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ Pixel4Bytes pixel;
+ pixel.r = BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical );
+ pixel.g = BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical );
+ pixel.b = BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical );
+ pixel.a = BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical );
+ return pixel;
+}
+
+/**
+ * @brief Generic version of bilinear sampling image resize function.
+ * @note Limited to one compilation unit and exposed through type-specific
+ * wrapper functions below.
+ */
+template<
+ typename PIXEL,
+ PIXEL (*BilinearFilter) ( PIXEL tl, PIXEL tr, PIXEL bl, PIXEL br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ),
+ bool DEBUG_ASSERT_ALIGNMENT
+>
+inline void LinearSampleGeneric( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ const unsigned int inputWidth = inputDimensions.GetWidth();
+ const unsigned int inputHeight = inputDimensions.GetHeight();
+ const unsigned int desiredWidth = desiredDimensions.GetWidth();
+ const unsigned int desiredHeight = desiredDimensions.GetHeight();
+
+ DALI_ASSERT_DEBUG( ((outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL)) ||
+ (inPixels >= outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))) &&
+ "Input and output buffers cannot overlap.");
+ if( DEBUG_ASSERT_ALIGNMENT )
+ {
+ DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
+ DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
+ }
+
+ if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
+ {
+ return;
+ }
+ const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
+ PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
+ const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
+ const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
+
+ unsigned int inY = 0;
+ for( unsigned int outY = 0; outY < desiredHeight; ++outY )
+ {
+ PIXEL* const outScanline = &outAligned[desiredWidth * outY];
+
+ // Find the two scanlines to blend and the weight to blend with:
+ const unsigned int integerY1 = inY >> 16u;
+ const unsigned int integerY2 = integerY1 >= inputHeight ? integerY1 : integerY1 + 1;
+ const unsigned int inputYWeight = inY & 65535u;
+
+ DALI_ASSERT_DEBUG( integerY1 < inputHeight );
+ DALI_ASSERT_DEBUG( integerY2 < inputHeight );
+
+ const PIXEL* const inScanline1 = &inAligned[inputWidth * integerY1];
+ const PIXEL* const inScanline2 = &inAligned[inputWidth * integerY2];
+
+ unsigned int inX = 0;
+ for( unsigned int outX = 0; outX < desiredWidth; ++outX )
+ {
+ // Work out the two pixel scanline offsets for this cluster of four samples:
+ const unsigned int integerX1 = inX >> 16u;
+ const unsigned int integerX2 = integerX1 >= inputWidth ? integerX1 : integerX1 + 1;
+
+ // Execute the loads:
+ const PIXEL pixel1 = inScanline1[integerX1];
+ const PIXEL pixel2 = inScanline2[integerX1];
+ const PIXEL pixel3 = inScanline1[integerX2];
+ const PIXEL pixel4 = inScanline2[integerX2];
+ ///@ToDo Optimise - for 1 and 2 and 4 byte types to execute a single 2, 4, or 8 byte load per pair (caveat clamping) and let half of them be unaligned.
+
+ // Weighted bilinear filter:
+ const unsigned int inputXWeight = inX & 65535u;
+ outScanline[outX] = BilinearFilter( pixel1, pixel3, pixel2, pixel4, inputXWeight, inputYWeight );
+
+ inX += deltaX;
+ }
+ inY += deltaY;
+ }
+}
+
+}
+
+// Format-specific linear scaling instantiations:
+
+void LinearSample1BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ LinearSampleGeneric<uint8_t, BilinearFilter1BPPByte, false>( inPixels, inputDimensions, outPixels, desiredDimensions );
+}
+
+void LinearSample2BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ LinearSampleGeneric<Pixel2Bytes, BilinearFilter2Bytes, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
+}
+
+void LinearSampleRGB565( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ LinearSampleGeneric<PixelRGB565, BilinearFilterRGB565, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
+}
+
+void LinearSample3BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ LinearSampleGeneric<Pixel3Bytes, BilinearFilterRGB888, false>( inPixels, inputDimensions, outPixels, desiredDimensions );
+}
+
+void LinearSample4BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ LinearSampleGeneric<Pixel4Bytes, BilinearFilter4Bytes, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
+}
+
+
+void Resample( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions,
+ Resampler::Filter filterType,
+ int numChannels, bool hasAlpha )
+{
+ // Got from the test.cpp of the ImageResampler lib.
+ const float ONE_DIV_255 = 1.0f / 255.0f;
+ const int MAX_UNSIGNED_CHAR = std::numeric_limits<uint8_t>::max();
+ const int LINEAR_TO_SRGB_TABLE_SIZE = 4096;
+ const int ALPHA_CHANNEL = hasAlpha ? (numChannels-1) : 0;
+
+ static bool loadColorSpaces = true;
+ static float srgbToLinear[MAX_UNSIGNED_CHAR + 1];
+ static unsigned char linearToSrgb[LINEAR_TO_SRGB_TABLE_SIZE];
+
+ if( loadColorSpaces ) // Only create the color space conversions on the first execution
+ {
+ loadColorSpaces = false;
+
+ for( int i = 0; i <= MAX_UNSIGNED_CHAR; ++i )
+ {
+ srgbToLinear[i] = pow( static_cast<float>( i ) * ONE_DIV_255, DEFAULT_SOURCE_GAMMA );
+ }
+
+ const float invLinearToSrgbTableSize = 1.0f / static_cast<float>( LINEAR_TO_SRGB_TABLE_SIZE );
+ const float invSourceGamma = 1.0f / DEFAULT_SOURCE_GAMMA;
+
+ for( int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i )
+ {
+ int k = static_cast<int>( 255.0f * pow( static_cast<float>( i ) * invLinearToSrgbTableSize, invSourceGamma ) + 0.5f );
+ if( k < 0 )
+ {
+ k = 0;
+ }
+ else if( k > MAX_UNSIGNED_CHAR )
+ {
+ k = MAX_UNSIGNED_CHAR;
+ }
+ linearToSrgb[i] = static_cast<unsigned char>( k );
+ }
+ }
+
+ Resampler* resamplers[numChannels];
+ Vector<float> samples[numChannels];
+
+ const int srcWidth = inputDimensions.GetWidth();
+ const int srcHeight = inputDimensions.GetHeight();
+ const int dstWidth = desiredDimensions.GetWidth();
+ const int dstHeight = desiredDimensions.GetHeight();
+
+ // Now create a Resampler instance for each component to process. The first instance will create new contributor tables, which are shared by the resamplers
+ // used for the other components (a memory and slight cache efficiency optimization).
+ resamplers[0] = new Resampler( srcWidth,
+ srcHeight,
+ dstWidth,
+ dstHeight,
+ Resampler::BOUNDARY_CLAMP,
+ 0.0f, // sample_low,
+ 1.0f, // sample_high. Clamp output samples to specified range, or disable clamping if sample_low >= sample_high.
+ filterType, // The type of filter.
+ NULL, // Pclist_x,
+ NULL, // Pclist_y. Optional pointers to contributor lists from another instance of a Resampler.
+ FILTER_SCALE, // src_x_ofs,
+ FILTER_SCALE ); // src_y_ofs. Offset input image by specified amount (fractional values okay).
+ samples[0].Resize( srcWidth );
+ for( int i = 1; i < numChannels; ++i )
+ {
+ resamplers[i] = new Resampler( srcWidth,
+ srcHeight,
+ dstWidth,
+ dstHeight,
+ Resampler::BOUNDARY_CLAMP,
+ 0.0f,
+ 1.0f,
+ filterType,
+ resamplers[0]->get_clist_x(),
+ resamplers[0]->get_clist_y(),
+ FILTER_SCALE,
+ FILTER_SCALE );
+ samples[i].Resize( srcWidth );
+ }
+
+ const int srcPitch = srcWidth * numChannels;
+ const int dstPitch = dstWidth * numChannels;
+ int dstY = 0;
+
+ for( int srcY = 0; srcY < srcHeight; ++srcY )
+ {
+ const unsigned char* pSrc = &inPixels[srcY * srcPitch];
+
+ for( int x = 0; x < srcWidth; ++x )
+ {
+ for( int c = 0; c < numChannels; ++c )
+ {
+ if( c == ALPHA_CHANNEL && hasAlpha )
+ {
+ samples[c][x] = *pSrc++ * ONE_DIV_255;
+ }
+ else
+ {
+ samples[c][x] = srgbToLinear[*pSrc++];
+ }
+ }
+ }
+
+ for( int c = 0; c < numChannels; ++c )
+ {
+ if( !resamplers[c]->put_line( &samples[c][0] ) )
+ {
+ DALI_ASSERT_DEBUG( !"Out of memory" );
+ }
+ }
+
+ for(;;)
+ {
+ int compIndex;
+ for( compIndex = 0; compIndex < numChannels; ++compIndex )
+ {
+ const float* pOutputSamples = resamplers[compIndex]->get_line();
+ if( !pOutputSamples )
+ {
+ break;
+ }
+
+ const bool isAlphaChannel = ( compIndex == ALPHA_CHANNEL && hasAlpha );
+ DALI_ASSERT_DEBUG( dstY < dstHeight );
+ unsigned char* pDst = &outPixels[dstY * dstPitch + compIndex];
+
+ for( int x = 0; x < dstWidth; ++x )
+ {
+ if( isAlphaChannel )
+ {
+ int c = static_cast<int>( 255.0f * pOutputSamples[x] + 0.5f );
+ if( c < 0 )
+ {
+ c = 0;
+ }
+ else if( c > MAX_UNSIGNED_CHAR )
+ {
+ c = MAX_UNSIGNED_CHAR;
+ }
+ *pDst = static_cast<unsigned char>( c );
+ }
+ else
+ {
+ int j = static_cast<int>( LINEAR_TO_SRGB_TABLE_SIZE * pOutputSamples[x] + 0.5f );
+ if( j < 0 )
+ {
+ j = 0;
+ }
+ else if( j >= LINEAR_TO_SRGB_TABLE_SIZE )
+ {
+ j = LINEAR_TO_SRGB_TABLE_SIZE - 1;
+ }
+ *pDst = linearToSrgb[j];
+ }
+
+ pDst += numChannels;
+ }
+ }
+ if( compIndex < numChannels )
+ {
+ break;
+ }
+
+ ++dstY;
+ }
+ }
+
+ // Delete the resamplers.
+ for( int i = 0; i < numChannels; ++i )
+ {
+ delete resamplers[i];
+ }
+}
+
+void LanczosSample4BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 4, true );
+}
+
+void LanczosSample1BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions )
+{
+ // For L8 images
+ Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 1, false );
+}
+
+// Dispatch to a format-appropriate linear sampling function:
+void LinearSample( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inDimensions,
+ Pixel::Format pixelFormat,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions outDimensions )
+{
+ // Check the pixel format is one that is supported:
+ if( pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::RGB565 )
+ {
+ if( pixelFormat == Pixel::RGB888 )
+ {
+ LinearSample3BPP( inPixels, inDimensions, outPixels, outDimensions );
+ }
+ else if( pixelFormat == Pixel::RGBA8888 )
+ {
+ LinearSample4BPP( inPixels, inDimensions, outPixels, outDimensions );
+ }
+ else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
+ {
+ LinearSample1BPP( inPixels, inDimensions, outPixels, outDimensions );
+ }
+ else if( pixelFormat == Pixel::LA88 )
+ {
+ LinearSample2BPP( inPixels, inDimensions, outPixels, outDimensions );
+ }
+ else if ( pixelFormat == Pixel::RGB565 )
+ {
+ LinearSampleRGB565( inPixels, inDimensions, outPixels, outDimensions );
+ }
+ else
+ {
+ DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not linear sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
+ }
+}
+
+} /* namespace Platform */
+} /* namespace Internal */
+} /* namespace Dali */
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_
+#define DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_
+
+// EXTERNAL INCLUDES
+#include <stdint.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/bitmap.h>
+#include <dali/public-api/images/image-operations.h>
+#include <third-party/resampler/resampler.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Platform
+{
+
+/**
+ * @brief Identify which combination of x and y dimensions matter in terminating iterative box filtering.
+ */
+enum BoxDimensionTest
+{
+ BoxDimensionTestEither,
+ BoxDimensionTestBoth,
+ BoxDimensionTestX,
+ BoxDimensionTestY
+};
+
+/**
+ * @brief The integer dimensions of an image or a region of an image packed into
+ * 16 bits per component.
+ * @note This can only be used for images of up to 65535 x 65535 pixels.
+ */
+typedef Uint16Pair ImageDimensions;
+
+/**
+ * @brief Work out the true desired width and height, accounting for special
+ * rules for zeros in either or both input requested dimensions.
+ *
+ * @param[in] rawDimensions Width and height of image before processing.
+ * @param[in] requestedDimensions Width and height of area to scale image into. Can be zero.
+ * @return Dimensions of area to scale image into after special rules are applied.
+ */
+ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions );
+
+/**
+ * @defgroup BitmapOperations Bitmap-to-Bitmap Image operations.
+ * @{
+ */
+
+/**
+ * @brief Apply requested attributes to bitmap.
+ *
+ * This is the top-level function which runs the on-load image post-processing
+ * pipeline. Bitmaps enter here as loaded from the file system by the file
+ * loaders and leave downscaled and filtered as requested by the application,
+ * ready for use.
+ *
+ * @param[in] bitmap The input bitmap.
+ * @param[in] requestedAttributes Attributes which should be applied to bitmap.
+ * @return A bitmap which results from applying the requested attributes to the
+ * bitmap passed-in, or the original bitmap passed in if the attributes
+ * have no effect.
+ */
+Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode = FittingMode::DEFAULT, SamplingMode::Type samplingMode = SamplingMode::DEFAULT );
+
+/**
+ * @brief Apply downscaling to a bitmap according to requested attributes.
+ * @note The input bitmap pixel buffer may be modified and used as scratch working space for efficiency, so it must be discarded.
+ **/
+Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap,
+ ImageDimensions desired,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode );
+/**@}*/
+
+/**
+ * @defgroup ImageBufferScalingAlgorithms Pixel buffer-level scaling algorithms.
+ * @{
+ */
+
+/**
+ * @brief Destructive in-place downscaling by a power of 2 factor.
+ *
+ * A box filter with a 2x2 kernel is repeatedly applied as long as the result
+ * of the next downscaling step would not be smaller than the desired
+ * dimensions.
+ * @param[in,out] pixels The buffer both to read from and write the result to.
+ * @param[in] pixelFormat The format of the image pointed at by pixels.
+ * @param[in] inputWidth The width of the input image.
+ * @param[in] inputHeight The height of the input image.
+ * @param[in] desiredWidth The width the client is requesting.
+ * @param[in] desiredHeight The height the client is requesting.
+ * @param[out] outWidth The resulting width after downscaling.
+ * @param[out] outHeight The resulting height after downscaling.
+ */
+void DownscaleInPlacePow2( unsigned char * const pixels,
+ Pixel::Format pixelFormat,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ unsigned& outWidth,
+ unsigned& outHeight );
+
+/**
+ * @brief Destructive in-place downscaling by a power of 2 factor.
+ *
+ * A box filter with a 2x2 kernel is repeatedly applied as long as the result
+ * of the next downscaling step would not be smaller than the desired
+ * dimensions.
+ * @param[in,out] pixels The buffer both to read from and write the result to.
+ * @param[in] inputWidth The width of the input image.
+ * @param[in] inputHeight The height of the input image.
+ * @param[in] desiredWidth The width the client is requesting.
+ * @param[in] desiredHeight The height the client is requesting.
+ * @param[out] outWidth The resulting width after downscaling.
+ * @param[out] outHeight The resulting height after downscaling.
+ */
+void DownscaleInPlacePow2RGB888( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight );
+
+/**
+ * @copydoc DownscaleInPlacePow2RGB888
+ */
+void DownscaleInPlacePow2RGBA8888( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight );
+
+/**
+ * @copydoc DownscaleInPlacePow2RGB888
+ *
+ * For the 2-byte packed 16 bit format RGB565.
+ */
+void DownscaleInPlacePow2RGB565( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight );
+
+/**
+ * @copydoc DownscaleInPlacePow2RGB888
+ *
+ * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565.
+ */
+void DownscaleInPlacePow2ComponentPair( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight );
+
+/**
+ * @copydoc DownscaleInPlacePow2RGB888
+ *
+ * For single-byte formats such as lum8 or alpha8.
+ */
+void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight,
+ BoxDimensionTest dimensionTest,
+ unsigned int& outWidth,
+ unsigned int& outHeight );
+
+/**
+ * @brief Rescales an input image into the exact output dimensions passed-in.
+ *
+ * Uses point sampling, equivalent to GL_NEAREST texture filter mode, for the
+ * fastest results, at the expense of aliasing (noisy images) when downscaling.
+ * @note inPixels is allowed to alias outPixels if this is a downscaling,
+ * but not for upscaling.
+ */
+void PointSample( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ Pixel::Format pixelFormat,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight );
+
+/**
+ * @copydoc PointSample
+ *
+ * Specialised for 4-byte formats like RGBA8888 and BGRA8888.
+ */
+void PointSample4BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight );
+
+/**
+ * @copydoc PointSample
+ *
+ * Specialised for 3-byte formats like RGB888 and BGR888.
+ */
+void PointSample3BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight );
+
+/**
+ * @copydoc PointSample
+ *
+ * Specialised for 2-byte formats like LA88.
+ */
+void PointSample2BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight );
+
+/**
+ * @copydoc PointSample
+ *
+ * Specialised for 1-byte formats like L8 and A8.
+ */
+void PointSample1BPP( const unsigned char * inPixels,
+ unsigned int inputWidth,
+ unsigned int inputHeight,
+ unsigned char * outPixels,
+ unsigned int desiredWidth,
+ unsigned int desiredHeight );
+
+/**
+ * @brief Resample input image to output image using a bilinear filter.
+ *
+ * Each output pixel is formed of a weighted sum of a 2x2 block of four input
+ * pixels
+ * @pre inPixels must not alias outPixels. The input image should be a totally
+ * separate buffer from the input one.
+ */
+void LinearSample( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inDimensions,
+ Pixel::Format pixelFormat,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions outDimensions );
+
+/**
+ * @copydoc LinearSample
+ *
+ * Specialised for one byte per pixel formats.
+ */
+void LinearSample1BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @copydoc LinearSample
+ *
+ * Specialised for two byte per pixel formats.
+ */
+void LinearSample2BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @copydoc LinearSample
+ *
+ * Specialised for RGB565 16 bit pixel format.
+ */
+void LinearSampleRGB565( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @copydoc LinearSample
+ *
+ * Specialised for three byte per pixel formats like RGB888.
+ */
+void LinearSample3BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @copydoc LinearSample
+ *
+ * Specialised for four byte per pixel formats like RGBA8888.
+ * @note, If used on RGBA8888, the A component will be blended independently.
+ */
+void LinearSample4BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @brief Resamples the input image with the Lanczos algorithm.
+ *
+ * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
+ * separate buffer from the output buffer.
+ *
+ * @param[in] inPixels Pointer to the input image buffer.
+ * @param[in] inputDimensions The input dimensions of the image.
+ * @param[out] outPixels Pointer to the output image buffer.
+ * @param[in] desiredDimensions The output dimensions of the image.
+ */
+void LanczosSample4BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @brief Resamples the input image with the Lanczos algorithm.
+ *
+ * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
+ * separate buffer from the output buffer.
+ *
+ * @param[in] inPixels Pointer to the input image buffer.
+ * @param[in] inputDimensions The input dimensions of the image.
+ * @param[out] outPixels Pointer to the output image buffer.
+ * @param[in] desiredDimensions The output dimensions of the image.
+ */
+void LanczosSample1BPP( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions );
+
+/**
+ * @brief Resamples the input image with the Lanczos algorithm.
+ *
+ * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
+ * separate buffer from the output buffer.
+ *
+ * @param[in] inPixels Pointer to the input image buffer.
+ * @param[in] inputDimensions The input dimensions of the image.
+ * @param[out] outPixels Pointer to the output image buffer.
+ * @param[in] desiredDimensions The output dimensions of the image.
+ */
+void Resample( const unsigned char * __restrict__ inPixels,
+ ImageDimensions inputDimensions,
+ unsigned char * __restrict__ outPixels,
+ ImageDimensions desiredDimensions,
+ Resampler::Filter filterType,
+ int numChannels, bool hasAlpha );
+
+
+/**@}*/
+
+/**
+ * @defgroup ScalingAlgorithmFragments Composable subunits of the scaling algorithms.
+ * @{
+ */
+
+/**
+ * @brief Average adjacent pairs of pixels, overwriting the input array.
+ * @param[in,out] pixels The array of pixels to work on.
+ * @param[i] width The number of pixels in the array passed-in.
+ */
+void HalveScanlineInPlaceRGB888( unsigned char * pixels, unsigned int width );
+
+/**
+ * @copydoc HalveScanlineInPlaceRGB888
+ */
+void HalveScanlineInPlaceRGBA8888( unsigned char * pixels, unsigned int width );
+
+/**
+ * @copydoc HalveScanlineInPlaceRGB888
+ */
+void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width );
+
+/**
+ * @copydoc HalveScanlineInPlaceRGB888
+ */
+void HalveScanlineInPlace2Bytes( unsigned char * pixels, unsigned int width );
+
+/**
+ * @copydoc HalveScanlineInPlaceRGB888
+ */
+void HalveScanlineInPlace1Byte( unsigned char * pixels, unsigned int width );
+
+/**
+ * @brief Average pixels at corresponding offsets in two scanlines.
+ *
+ * outputScanline is allowed to alias scanline1.
+ * @param[in] scanline1 First scanline of pixels to average.
+ * @param[in] scanline2 Second scanline of pixels to average.
+ * @param[out] outputScanline Destination for the averaged pixels.
+ * @param[in] width The widths of all the scanlines passed-in.
+ */
+void AverageScanlines1( const unsigned char * scanline1,
+ const unsigned char * scanline2,
+ unsigned char* outputScanline,
+ /** Image width in pixels (1 byte == 1 pixel: e.g. lum8 or alpha8).*/
+ unsigned int width );
+
+/**
+ * @copydoc AverageScanlines1
+ */
+void AverageScanlines2( const unsigned char * scanline1,
+ const unsigned char * scanline2,
+ unsigned char* outputScanline,
+ /** Image width in pixels (2 bytes == 1 pixel: e.g. lum8alpha8).*/
+ unsigned int width );
+
+/**
+ * @copydoc AverageScanlines1
+ */
+void AverageScanlines3( const unsigned char * scanline1,
+ const unsigned char * scanline2,
+ unsigned char* outputScanline,
+ /** Image width in pixels (3 bytes == 1 pixel: e.g. RGB888).*/
+ unsigned int width );
+
+/**
+ * @copydoc AverageScanlines1
+ */
+void AverageScanlinesRGBA8888( const unsigned char * scanline1,
+ const unsigned char * scanline2,
+ unsigned char * outputScanline,
+ unsigned int width );
+
+/**
+ * @copydoc AverageScanlines1
+ */
+void AverageScanlinesRGB565( const unsigned char * scanline1,
+ const unsigned char * scanline2,
+ unsigned char* outputScanline,
+ unsigned int width );
+/**@}*/
+
+/**
+ * @defgroup TestableInlines Inline functions exposed in header to allow unit testing.
+ * @{
+ */
+
+/**
+ * @brief Average two integer arguments.
+ * @return The average of two uint arguments.
+ * @param[in] a First component to average.
+ * @param[in] b Second component to average.
+ **/
+inline unsigned int AverageComponent( unsigned int a, unsigned int b )
+{
+ unsigned int avg = (a + b) >> 1u;
+ return avg;
+}
+
+/**
+ * @brief Average a pair of RGBA8888 pixels.
+ * @return The average of two RGBA8888 pixels.
+ * @param[in] a First pixel to average.
+ * @param[in] b Second pixel to average
+ **/
+inline uint32_t AveragePixelRGBA8888( uint32_t a, uint32_t b )
+{
+ const unsigned int avg =
+ ((AverageComponent( (a & 0xff000000) >> 1u, (b & 0xff000000) >> 1u ) << 1u) & 0xff000000 ) +
+ (AverageComponent( a & 0x00ff0000, b & 0x00ff0000 ) & 0x00ff0000 ) +
+ (AverageComponent( a & 0x0000ff00, b & 0x0000ff00 ) & 0x0000ff00 ) +
+ (AverageComponent( a & 0x000000ff, b & 0x000000ff ) );
+ return avg;
+ ///@ToDo: Optimise by trying return (((a ^ b) & 0xfefefefeUL) >> 1) + (a & b);
+ ///@ToDo: Optimise for ARM using the single ARMV6 instruction: UHADD8 R4, R0, R5. This is not Neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro.
+}
+
+/**
+ * @brief Average a pair of RGB565 pixels.
+ * @param a[in] Low 16 bits hold a color value as RGB565 to average with parameter b.
+ * @param b[in] Low 16 bits hold a color value as RGB565 to average with parameter a.
+ * @return The average color of the two RGB565 pixels passed in, in the low 16 bits of the returned value.
+ **/
+inline uint32_t AveragePixelRGB565( uint32_t a, uint32_t b )
+{
+ const unsigned int avg =
+ (AverageComponent( a & 0xf800, b & 0xf800 ) & 0xf800 ) +
+ (AverageComponent( a & 0x7e0, b & 0x7e0 ) & 0x7e0 ) +
+ (AverageComponent( a & 0x1f, b & 0x1f ) );
+ return avg;
+}
+
+/** @return The weighted blend of two integers as a 16.16 fixed-point number, given a 0.16 fixed-point blending factor. */
+inline unsigned int WeightedBlendIntToFixed1616(unsigned int a, unsigned int b, unsigned int fractBlend )
+{
+ DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." );
+ const unsigned int weightedAFixed = a * (65535u - fractBlend);
+ const unsigned int weightedBFixed = b * fractBlend;
+ const unsigned blended = (weightedAFixed + weightedBFixed);
+ return blended;
+}
+
+/** @brief Blend two 16.16 inputs to give a 16.32 output. */
+inline uint64_t WeightedBlendFixed1616ToFixed1632(unsigned int a, unsigned int b, unsigned int fractBlend )
+{
+ DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." );
+ // Blend while promoting intermediates to 16.32 fixed point:
+ const uint64_t weightedAFixed = uint64_t(a) * (65535u - fractBlend);
+ const uint64_t weightedBFixed = uint64_t(b) * fractBlend;
+ const uint64_t blended = (weightedAFixed + weightedBFixed);
+ return blended;
+}
+
+/**
+ * @brief Blend 4 taps into one value using horizontal and vertical weights.
+ */
+inline unsigned int BilinearFilter1Component(unsigned int tl, unsigned int tr, unsigned int bl, unsigned int br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
+{
+ DALI_ASSERT_DEBUG( fractBlendHorizontal <= 65535u && "Factor should be in 0.16 fixed-point." );
+ DALI_ASSERT_DEBUG( fractBlendVertical <= 65535u && "Factor should be in 0.16 fixed-point." );
+
+ const unsigned int topBlend = WeightedBlendIntToFixed1616( tl, tr, fractBlendHorizontal );
+ const unsigned int botBlend = WeightedBlendIntToFixed1616( bl, br, fractBlendHorizontal );
+ const uint64_t blended2x2 = WeightedBlendFixed1616ToFixed1632( topBlend, botBlend, fractBlendVertical );
+ const unsigned int rounded = (blended2x2 + (1u << 31u) ) >> 32u;
+ return rounded;
+}
+
+/**@}*/
+
+} /* namespace Platform */
+} /* namespace Internal */
+} /* namespace Dali */
+
+#endif /* DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_ */
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/loader-astc.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+#include <dali/public-api/common/compile-time-assert.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/images/pixel.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+namespace TizenPlatform
+{
+namespace
+{
+
+// Max width or height of an image.
+const unsigned MAX_TEXTURE_DIMENSION = 4096;
+// Max bytes of image data allowed. Not a precise number, just a sanity check.
+const unsigned MAX_IMAGE_DATA_SIZE = MAX_TEXTURE_DIMENSION * MAX_TEXTURE_DIMENSION;
+
+// Minimum and maximum possible sizes for ASTC blocks.
+const unsigned int MINIMUM_ASTC_BLOCK_SIZE = 4;
+const unsigned int MAXIMUM_ASTC_BLOCK_SIZE = 12;
+
+typedef uint8_t Byte;
+
+// This bytes identify an ASTC native file.
+const Byte FileIdentifier[] = {
+ 0x13, 0xAB, 0xA1, 0x5C
+};
+
+
+/**
+ * @brief This struct defines the ASTC file header values. From ASTC specifications.
+ * Packed attribute stops the structure from being aligned to compiler defaults
+ * so we can be sure of reading the whole header from file in one call to fread().
+ * Note: members to not conform to coding standards in order to be consistent with ASTC spec.
+ */
+struct AstcFileHeader
+{
+ unsigned char magic[ 4 ];
+ unsigned char blockdim_x;
+ unsigned char blockdim_y;
+ unsigned char blockdim_z;
+ unsigned char xsize[ 3 ];
+ unsigned char ysize[ 3 ];
+ unsigned char zsize[ 3 ];
+} __attribute__ ( (__packed__));
+
+using namespace Pixel;
+
+/**
+ * @brief This table allows fast conversion from an ASTC block size ([height][width]) to a pixel format.
+ * This could be done within a switch, but this way we have a constant time function.
+ * Note: As 4 is the minimum block size, 4 is subtracted from both the width and height to optimise size.
+ * IE. Table format is: Increasing order of block width from left-to-right: 4 -> 12
+ * Increasing order of block height from top-to-bottom: 4 -> 12
+ */
+Pixel::Format AstcLinearBlockSizeToPixelFormatTable[][( MAXIMUM_ASTC_BLOCK_SIZE - MINIMUM_ASTC_BLOCK_SIZE ) + 1] = {
+ { COMPRESSED_RGBA_ASTC_4x4_KHR, COMPRESSED_RGBA_ASTC_5x4_KHR, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
+ { INVALID, COMPRESSED_RGBA_ASTC_5x5_KHR, COMPRESSED_RGBA_ASTC_6x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x5_KHR, INVALID, INVALID },
+ { INVALID, INVALID, COMPRESSED_RGBA_ASTC_6x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x6_KHR, INVALID, INVALID },
+ { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
+ { INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_8x8_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x8_KHR, INVALID, INVALID },
+ { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
+ { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_10x10_KHR, INVALID, COMPRESSED_RGBA_ASTC_12x10_KHR },
+ { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
+ { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_12x12_KHR }
+};
+
+/**
+ * @brief Uses header information to return the respective ASTC pixel format.
+ *
+ * @param[in] header A populated AstcFileHeader struct
+ * @return The pixel format, or INVALID if the block size was invalid
+ */
+Pixel::Format GetAstcPixelFormat( AstcFileHeader& header )
+{
+ // Check the block size is valid. This will also prevent an invalid read from the conversion table.
+ if( ( header.blockdim_x < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_x > MAXIMUM_ASTC_BLOCK_SIZE ) ||
+ ( header.blockdim_y < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_y > MAXIMUM_ASTC_BLOCK_SIZE ) )
+ {
+ return Pixel::INVALID;
+ }
+
+ // Read the equivalent pixel format from the conversion table.
+ return AstcLinearBlockSizeToPixelFormatTable[ header.blockdim_y - MINIMUM_ASTC_BLOCK_SIZE ][ header.blockdim_x - MINIMUM_ASTC_BLOCK_SIZE ];
+}
+
+/**
+ * @brief Internal method to load ASTC header info from a file.
+ *
+ * @param[in] filePointer The file pointer to the ASTC file to read
+ * @param[out] width The width is output to this value
+ * @param[out] height The height is output to this value
+ * @param[out] fileHeader This will be populated with the header data
+ * @return True if the file is valid, false otherwise
+ */
+bool LoadAstcHeader( FILE * const filePointer, unsigned int& width, unsigned int& height, AstcFileHeader& fileHeader )
+{
+ // Pull the bytes of the file header in as a block:
+ const unsigned int readLength = sizeof( AstcFileHeader );
+ if( fread( &fileHeader, 1, readLength, filePointer ) != readLength )
+ {
+ return false;
+ }
+
+ // Check the header contains the ASTC native file identifier.
+ bool headerIsValid = memcmp( fileHeader.magic, FileIdentifier, sizeof( fileHeader.magic ) ) == 0;
+ if( !headerIsValid )
+ {
+ DALI_LOG_ERROR( "File is not a valid ASTC native file\n" );
+ // Return here as otherwise, if not a valid ASTC file, we are likely to pick up other header errors spuriously.
+ return false;
+ }
+
+ // Convert the 3-byte values for width and height to a single resultant value.
+ width = fileHeader.xsize[0] | ( fileHeader.xsize[1] << 8 ) | ( fileHeader.xsize[2] << 16 );
+ height = fileHeader.ysize[0] | ( fileHeader.ysize[1] << 8 ) | ( fileHeader.ysize[2] << 16 );
+
+ const unsigned int zDepth = fileHeader.zsize[0] + ( fileHeader.zsize[1] << 8 ) + ( fileHeader.zsize[2] << 16 );
+
+ // Check image dimensions are within limits.
+ if( ( width > MAX_TEXTURE_DIMENSION ) || ( height > MAX_TEXTURE_DIMENSION ) )
+ {
+ DALI_LOG_ERROR( "ASTC file has larger than supported dimensions: %d,%d\n", width, height );
+ headerIsValid = false;
+ }
+
+ // Confirm the ASTC block does not have any Z depth.
+ if( zDepth != 1 )
+ {
+ DALI_LOG_ERROR( "ASTC files with z size other than 1 are not supported. Z size is: %d\n", zDepth );
+ headerIsValid = false;
+ }
+
+ return headerIsValid;
+}
+
+} // Unnamed namespace.
+
+
+// File loading API entry-point:
+bool LoadAstcHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ AstcFileHeader fileHeader;
+ return LoadAstcHeader( input.file, width, height, fileHeader );
+}
+
+// File loading API entry-point:
+bool LoadBitmapFromAstc( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ FILE* const filePointer = input.file;
+ if( !filePointer )
+ {
+ DALI_LOG_ERROR( "Null file handle passed to ASTC compressed bitmap file loader.\n" );
+ return false;
+ }
+
+ // Load the header info.
+ AstcFileHeader fileHeader;
+ unsigned int width, height;
+
+ if( !LoadAstcHeader( filePointer, width, height, fileHeader ) )
+ {
+ DALI_LOG_ERROR( "Could not load ASTC Header from file.\n" );
+ return false;
+ }
+
+ // Retrieve the pixel format from the ASTC block size.
+ Pixel::Format pixelFormat = GetAstcPixelFormat( fileHeader );
+ if( pixelFormat == Pixel::INVALID )
+ {
+ DALI_LOG_ERROR( "No internal pixel format supported for ASTC file pixel format.\n" );
+ return false;
+ }
+
+ // Retrieve the file size.
+ if( fseek( filePointer, 0L, SEEK_END ) )
+ {
+ DALI_LOG_ERROR( "Could not seek through file.\n" );
+ return false;
+ }
+
+ off_t fileSize = ftell( filePointer );
+ if( fileSize == -1L )
+ {
+ DALI_LOG_ERROR( "Could not determine ASTC file size.\n" );
+ return false;
+ }
+
+ if( fseek( filePointer, sizeof( AstcFileHeader ), SEEK_SET ) )
+ {
+ DALI_LOG_ERROR( "Could not seek through file.\n" );
+ return false;
+ }
+
+ // Data size is file size - header size.
+ size_t imageByteCount = fileSize - sizeof( AstcFileHeader );
+
+ // Sanity-check the image data is not too large and that it is at less than 2 bytes per texel:
+ if( ( imageByteCount > MAX_IMAGE_DATA_SIZE ) || ( imageByteCount > ( ( static_cast< size_t >( width ) * height ) << 1 ) ) )
+ {
+ DALI_LOG_ERROR( "ASTC file has too large image-data field.\n" );
+ return false;
+ }
+
+ // allocate pixel data
+ bitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
+
+ // Compressed format won't allocate the buffer
+ auto pixels = bitmap.GetBuffer();
+ if( !pixels )
+ {
+ // allocate buffer manually
+ auto& impl = GetImplementation( bitmap );
+ impl.AllocateFixedSize( imageByteCount );
+ pixels = bitmap.GetBuffer();
+ }
+
+ // Load the image data.
+ const size_t bytesRead = fread( pixels, 1, imageByteCount, filePointer );
+
+ // Check the size of loaded data is what we expected.
+ if( bytesRead != imageByteCount )
+ {
+ DALI_LOG_ERROR( "Read of image pixel data failed.\n" );
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Astc
+{
+const unsigned char MAGIC_BYTE_1 = 0x13;
+const unsigned char MAGIC_BYTE_2 = 0xAB;
+} // namespace Astc
+
+
+/**
+ * Loads a compressed bitmap image from a ASTC file without decoding it.
+ * This function checks the header first
+ * and if it is not a ASTC file, or the header contents are invalid, it will return a failure.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return True if file loaded successfully, false otherwise
+ */
+bool LoadBitmapFromAstc( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a ASTC file and fills in the width and height appropriately.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] width Is set with the width of the image
+ * @param[out] height Is set with the height of the image
+ * @return True if the header was read successfully, false otherwise
+ */
+bool LoadAstcHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/imaging/common/loader-bmp.h>
+
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+const unsigned int FileHeaderOffsetOfBF32V4 = 0x7A;
+const unsigned int MaskForBFRGB565 = 0x80;
+const unsigned int FileHeaderOffsetOfRGB24V5 = 0x8A;
+
+enum BmpFormat
+{
+ BMP_RGB1 = 14, //BI_RGB & bpp =1
+ BMP_RGB4, //BI_RGB & bpp = 4
+ BMP_RGB8, //BI_RGB & bpp = 8
+ BMP_RGB555, //BI_RGB & bpp = 16
+ BMP_BITFIELDS555, //BI_BITFIELDS & 16bit & R:G:B = 5:5:5
+ BMP_BITFIELDS32, //BI_BITFIELDS & 32bit & R:G:B:A = 8:8:8:8
+ BMP_RLE8, //BI_RLE8
+ BMP_RLE4, //BI_RLE4
+ BMP_BITFIELDS32V4,//BI_BITFIELDS & 32bit
+ BMP_RGB24V5, //BI_RGB & bpp = 24 & bmp version5
+ BMP_NOTEXIST
+};
+
+struct BmpFileHeader
+{
+ unsigned short signature; // Bitmap file signature
+ unsigned int fileSize; // Bitmap file size in bytes
+ unsigned short reserved1; // Reserved bits
+ unsigned short reserved2; // Reserved bits
+ unsigned int offset; // Offset from BMP file header to BMP bits
+} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes
+
+struct BmpInfoHeader
+{
+ unsigned int infoHeaderSize; // Specifies the number of bytes required by the info header
+ unsigned int width; // The Image Width
+ int height; // The Image Height (negative value represents image data is flipped)
+ unsigned short planes; // The number of color planes, must be 1
+ unsigned short bitsPerPixel; // The bits per pixel
+ unsigned int compression; // The type of compression used by the image
+ unsigned int imageSize; // The size of the image in bytes
+ unsigned int xPixelsPerMeter; // The number of pixels per meter in x axis
+ unsigned int yPixelsPerMeter; // The number of pixels per meter in y axis
+ unsigned int numberOfColors; // The number of colors in the color table
+ unsigned int importantColors; // The important color count
+} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes
+
+/**
+ * Template function to read from the file directly into our structure.
+ * @param[in] fp The file to read from
+ * @param[out] header The structure we want to store our information in
+ * @return true, if read successful, false otherwise
+ */
+template<typename T>
+inline bool ReadHeader(FILE* fp, T& header)
+{
+ const unsigned int readLength = sizeof(T);
+
+ // Load the information directly into our structure
+ if ( fread( &header, 1, readLength, fp ) != readLength )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+bool LoadBmpHeader(FILE *fp, unsigned int &width, unsigned int &height, BmpFileHeader &fileHeader, BmpInfoHeader &infoHeader)
+{
+ if (!ReadHeader(fp, fileHeader))
+ {
+ return false;
+ }
+
+ if (!ReadHeader(fp, infoHeader))
+ {
+ return false;
+ }
+
+ width = infoHeader.width;
+ height = abs(infoHeader.height);
+
+ if( infoHeader.width == 0 )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * function to decode format BI_RGB & bpp = 24 & bmp version5.
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @param[in] padding padded to a u_int32 boundary for each line
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRGB24V5(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown,
+ unsigned int rowStride,
+ unsigned int padding)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RGB24V5 format\n");
+ return false;
+ }
+ if ( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RGB24V5 data\n");
+ return false;
+ }
+
+ for(unsigned int yPos = 0; yPos < height; yPos ++)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if(topDown)
+ {
+ pixelsPtr = pixels + ( yPos * rowStride);
+ }
+ else
+ {
+ pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
+ }
+ if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ for(unsigned int i = 0; i < rowStride; i += 3)
+ {
+ unsigned char temp = pixelsPtr[i];
+ pixelsPtr[i] = pixelsPtr[i + 2];
+ pixelsPtr[i + 2] = temp;
+ }
+
+ if (padding)
+ {
+ // move past the padding.
+ if( fseek(fp, padding, SEEK_CUR) )
+ {
+ DALI_LOG_ERROR("Error moving past BMP_RGB24V5 padding\n");
+ }
+ }
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_BITFIELDS & bpp = 32 & bmp version4.
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @param[in] rowStride bits span for each line
+ * @param[in] padding padded to a u_int32 boundary for each line
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeBF32V4(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown,
+ unsigned int rowStride,
+ unsigned int padding)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32V4 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32V4 data\n");
+ return false;
+ }
+
+ for(unsigned int yPos = 0; yPos < height; yPos ++)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if(topDown)
+ {
+ pixelsPtr = pixels + ( yPos * rowStride);
+ }
+ else
+ {
+ pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
+ }
+ if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ for(unsigned int i = 0; i < rowStride; i += 4)
+ {
+ unsigned char temp = pixelsPtr[i];
+ pixelsPtr[i] = pixelsPtr[i + 2];
+ pixelsPtr[i + 2] = temp;
+ }
+ if (padding)
+ {
+ // move past the padding.
+ if( fseek(fp, padding, SEEK_CUR) )
+ {
+ DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32V4 padding\n");
+ }
+ }
+
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_BITFIELDS & bpp = 32
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @param[in] rowStride bits span for each line
+ * @param[in] padding padded to a u_int32 boundary for each line
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeBF32(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown,
+ unsigned int rowStride,
+ unsigned int padding)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32 data\n");
+ return false;
+ }
+
+ for (unsigned int yPos = 0; yPos < height; yPos++)
+ {
+ unsigned char* pixelsPtr;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( yPos * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
+ }
+
+ if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ for(unsigned int i = 0; i < rowStride; i += 4)
+ {
+ unsigned char temp = pixelsPtr[i];
+ pixelsPtr[i] = pixelsPtr[i + 2];
+ pixelsPtr[i + 2] = temp;
+ }
+
+ if (padding)
+ {
+ // move past the padding.
+ if( fseek(fp, padding, SEEK_CUR) )
+ {
+ DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32 padding\n");
+ }
+ }
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_BITFIELDS & bpp = 16 & R:G:B = 5:6:5
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeBF565(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding RGB565 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking RGB565 data\n");
+ return false;
+ }
+
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ unsigned int rowStride = width * 2;
+
+ for(unsigned int i = 0; i < height; i++)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( i * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height - 1) - i) * rowStride);
+ }
+ if(fread(pixelsPtr, 1, rowStride, fp) != rowStride)
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * function to decode format BI_BITFIELDS & bpp = 16 & R:G:B = 5:5:5
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeBF555(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_BITFIELDS555 format\n");
+ return false;
+ }
+
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_BITFIELDS555 data\n");
+ return false;
+ }
+
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+
+ std::vector<char> raw(width * height * 2);
+ unsigned int rawStride = width * 2;
+ unsigned int rowStride = width * 3;
+
+ char *rawPtr = NULL;
+ for(unsigned int j = 0; j < height; j ++)
+ {
+ rawPtr = &raw[0] + ( j * rawStride);
+ if(fread(rawPtr, 1, rawStride, fp) != rawStride)
+ {
+ return false;
+ }
+ }
+
+ for (unsigned int yPos = 0; yPos < height; yPos++)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( yPos * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
+ }
+
+ for(unsigned int k = 0; k < width; k ++)
+ {
+ int index = yPos * rawStride + 2 * k;
+ pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F;
+ pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F;
+ pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F;
+ }
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_RGB & bpp = 16 & R:G:B = 5:5:5
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp image data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRGB555(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RGB555 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RGB555 data\n");
+ return false;
+ }
+
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ std::vector<char> raw(width * height * 2);
+ unsigned int rawStride = width * 2;
+ unsigned int rowStride = width * 3;
+
+ char *rawPtr = NULL;
+ for(unsigned int j = 0; j < height; j ++)
+ {
+ rawPtr = &raw[0] + ( j * rawStride);
+ if(fread(rawPtr, 1, rawStride, fp) != rawStride)
+ {
+ return false;
+ }
+ }
+ for(unsigned int i = 0; i < height; i++)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( i * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height - 1) - i) * rowStride);
+ }
+ for(unsigned int k = 0; k < width; k ++)
+ {
+ int index = i * rawStride + 2 * k;
+ pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F;
+ pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F;
+ pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F;
+ }
+
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_RGB & bpp = 1
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp palette data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRGB1(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RGB1 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RGB1 data\n");
+ return false;
+ }
+
+ unsigned char colorTable[8] = {0};
+ char cmd;
+ unsigned int fillw = ((width & 63) != 0) ? width + 64 - (width & 63) : width;
+ std::vector<char> colorIndex(fillw * height);
+ unsigned int rowStride = fillw * 3; // RGB
+
+
+ if(fread(colorTable, 1, 8, fp) != 8)
+ {
+ return false;
+ }
+
+ for(unsigned int i = 0; i < fillw * height; i += 8)
+ {
+ if(fread(&cmd, 1, 1, fp) != 1)
+ {
+ return false;
+ }
+
+ colorIndex[i] = (cmd >> 7) & 0x01;
+ colorIndex[i + 1] = (cmd >> 6) & 0x01;
+ colorIndex[i + 2] = (cmd >> 5) & 0x01;
+ colorIndex[i + 3] = (cmd >> 4) & 0x01;
+ colorIndex[i + 4] = (cmd >> 3) & 0x01;
+ colorIndex[i + 5] = (cmd >> 2) & 0x01;
+ colorIndex[i + 6] = (cmd >> 1) & 0x01;
+ colorIndex[i + 7] = (cmd & 0x01);
+ }
+
+ for(unsigned int index = 0; index < height; index = index + 1)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( index * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height - 1) - index) * rowStride);
+ }
+ for(unsigned int j = 0; j < fillw; j ++)
+ {
+ unsigned int ctIndex = 0;
+ if((fillw * index + j ) < (fillw * height))
+ {
+ ctIndex = colorIndex[ fillw * index + j ];
+ }
+ else
+ {
+ break;
+ }
+ // temp solution for PLM bug P130411-5268, there is one mono bmp that cause DecodeRGB1 API crash.
+ if( ((3 * j + 2) < height * fillw * 3) && (ctIndex < 2))
+ {
+ pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
+ pixelsPtr[3 * j + 1] = colorTable[4 * ctIndex + 1];
+ pixelsPtr[3 * j + 2] = colorTable[4 * ctIndex ];
+ }
+ }
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_RGB & bpp = 4
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp palette data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRGB4(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RGB4 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RGB4 data\n");
+ return false;
+ }
+
+ char colorTable[64];
+ char cmd;
+ unsigned int fillw = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ std::vector<char> colorIndex(fillw * height);
+ unsigned int rowStride = fillw * 3;
+
+ if(fread(colorTable, 1, 64, fp) != 64)
+ {
+ return false;
+ }
+
+ for(unsigned int i = 0; i < fillw * height; i += 2)
+ {
+ if (fread(&cmd, 1, 1, fp) != 1)
+ {
+ return false;
+ }
+
+ colorIndex[i] = cmd >> 4;
+ colorIndex[i + 1] = cmd & (0x0F);
+ }
+ unsigned int ctIndex = 0;
+
+ for(unsigned int index = 0; index < height; index = index + 1)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( index * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height - 1) - index) * rowStride);
+ }
+ for(unsigned int j = 0; j < fillw; j ++)
+ {
+ ctIndex = colorIndex[ fillw * index + j ];
+ pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
+ pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1];
+ pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ];
+ }
+ }
+
+ return true;
+}
+
+/**
+ * function to decode format BI_RGB & bpp = 8
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp palette data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRGB8(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RGB8 format\n");
+ return false;
+ }
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RGB8 data\n");
+ return false;
+ }
+
+ std::vector<char> colorTable(1024);
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ char cmd;
+ std::vector<char> colorIndex(width * height);
+ unsigned int rowStride = width * 3;//RGB8->RGB24
+
+ if(fread(&colorTable[0], 1, 1024, fp) != 1024)
+ {
+ return false;
+ }
+ for(unsigned int i = 0; i < width * height; i ++)
+ {
+ if (fread(&cmd, 1, 1, fp) != 1)
+ {
+ return false;
+ }
+
+ colorIndex[i] = cmd;
+ }
+ unsigned int ctIndex = 0;
+ for(unsigned int index = 0; index < height; index = index + 1)
+ {
+ unsigned char* pixelsPtr = NULL;
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsPtr = pixels + ( index * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsPtr = pixels + (((height - 1) - index) * rowStride);
+ }
+ for(unsigned int j = 0; j < width; j ++)
+ {
+ ctIndex = colorIndex[ width * index + j ];
+ pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
+ pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1];
+ pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ];
+ }
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_RLE4 & bpp = 4
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp palette data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRLE4(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RLE4 format\n");
+ return false;
+ }
+ unsigned char* pixelsPtr = pixels;
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ char cmd[2];
+ unsigned int cmdStride = 2;
+ char colorTable[64];
+ std::vector<char> colorIndex(width * height >> 1);
+ std::vector<char> run;
+ unsigned int x = 0;
+ unsigned int y = 0;
+ unsigned int dx = 0;
+ unsigned int dy = 0;
+ width += (width & 1);
+ width = width >> 1;
+
+ bool finish = false;
+
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RLE4 data\n");
+ return false;
+ }
+
+ if (fread(colorTable, 1, 64, fp) != 64)
+ {
+ return false;
+ }
+
+ while((x >> 1) + y * width < width * height)
+ {
+ if (finish)
+ {
+ break;
+ }
+ if (fread(cmd, 1, cmdStride, fp) != cmdStride)
+ {
+ return false;
+ }
+ if(cmd[0] == 0) // ESCAPE
+ {
+ switch(cmd[1])
+ {
+ case 1: //end of bitmap
+ finish = true;
+ break;
+ case 0: // end of line
+ x = 0;
+ y ++;
+ break;
+ case 2: // delta
+ if (fread(cmd, 1, cmdStride, fp) != cmdStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ dx = cmd[0] & (0xFF);
+ dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+ default:
+ // decode a literal run
+ unsigned int length = cmd[1] & (0xFF);
+ //size of run, which is word aligned
+ unsigned int bytesize = length;
+ bytesize += (bytesize & 1);
+ bytesize >>= 1;
+ bytesize += (bytesize & 1);
+ run.resize(bytesize);
+ if(fread(&run[0], 1, bytesize, fp) != bytesize)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ if((x & 1) == 0)
+ {
+ length += (length & 1);
+ length >>= 1;
+ for(unsigned int i = 0; i < length; i += 1)
+ {
+ colorIndex[(x >> 1) + width * (height - y - 1) + i] = run[i];
+ }
+ }
+ else
+ {
+ for(unsigned int i = 0; i < length; i ++)
+ {
+ if((i & 1) == 0)//copy high to low
+ {
+ colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((run[i >> 1] & 0xF0) >> 4);
+ }
+ else //copy low to high
+ {
+ colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((run[i >> 1] & 0x0F) << 4);
+ }
+ }
+ }
+ x += cmd[1] & (0xFF);
+ break;
+ }
+ }
+ else
+ {
+ unsigned int length = cmd[0] & (0xFF);
+ if((x & 1) == 0)
+ {
+ length += (length & 1);
+ length >>= 1;
+ for(unsigned int i = 0; i < length; i ++)
+ {
+ colorIndex[(height-y-1)*width + i + (x >> 1)] = cmd[1];
+ }
+ }
+ else
+ {
+ for(unsigned int i = 0; i < length; i ++)
+ {
+ if((i & 1) == 0)
+ {
+ colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((cmd[1] & 0xF0) >> 4);
+ }
+ else
+ {
+ colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((cmd[1] & 0x0F) << 4);
+ }
+ }
+ }
+ x += cmd[0] & (0xFF);
+ }
+ }
+
+ int ctIndexHigh = 0;
+ int ctIndexLow = 0;
+ for(unsigned int index = 0; index < (width * height ); index = index + 1)
+ {
+ ctIndexHigh = colorIndex[ index] >> 4;
+ ctIndexLow = colorIndex[index] & (0x0F);
+ pixelsPtr[6 * index ] = colorTable[4 * ctIndexHigh + 2];
+ pixelsPtr[6 * index + 1] = colorTable[4 * ctIndexHigh + 1];
+ pixelsPtr[6 * index + 2] = colorTable[4 * ctIndexHigh ];
+ pixelsPtr[6 * index + 3] = colorTable[4 * ctIndexLow + 2];
+ pixelsPtr[6 * index + 4] = colorTable[4 * ctIndexLow + 1];
+ pixelsPtr[6 * index + 5] = colorTable[4 * ctIndexLow ];
+ }
+ return true;
+}
+
+/**
+ * function to decode format BI_RLE8 & bpp = 8
+ * @param[in] fp The file to read from
+ * @param[out] pixels The pointer that we want to store bmp data in
+ * @param[in] width bmp width
+ * @param[in] height bmp height
+ * @param[in] offset offset from bmp header to bmp palette data
+ * @param[in] topDown indicate image data is read from bottom or from top
+ * @return true, if decode successful, false otherwise
+ */
+bool DecodeRLE8(FILE *fp,
+ unsigned char* pixels,
+ unsigned int width,
+ unsigned int height,
+ unsigned int offset,
+ bool topDown)
+{
+ if(fp == NULL || pixels == NULL)
+ {
+ DALI_LOG_ERROR("Error decoding BMP_RLE8 format\n");
+ return false;
+ }
+ unsigned char* pixelsPtr = pixels;
+ unsigned int x = 0;
+ unsigned int y = 0;
+ unsigned int cmdStride = 2;
+
+ width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
+ std::vector<char> colorTable(1024);
+ char cmd[2];
+ std::vector<char> colorIndex(width * height);
+
+ if( fseek(fp, offset, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking BMP_RLE8 data\n");
+ return false;
+ }
+
+ if (fread(&colorTable[0], 1, 1024, fp) != 1024)
+ {
+ return false;
+ }
+
+ unsigned int dx = 0;
+ unsigned int dy = 0;
+ bool finish = false;
+ unsigned int length = 0;
+ unsigned int copylength = 0;
+ std::vector<char> run;
+ while((x + y * width) < width * height )
+ {
+ if (finish)
+ {
+ break;
+ }
+ if (fread(cmd, 1, cmdStride, fp) != cmdStride)
+ {
+ return false;
+ }
+
+ if(cmd[0] == 0)//ESCAPE
+ {
+ switch(cmd[1])
+ {
+ case 1: // end of bitmap
+ finish = true;
+ break;
+ case 0: // end of line
+ x = 0;
+ y ++;
+ break;
+ case 2: // delta
+ if (fread(cmd, 1, cmdStride, fp) != cmdStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+ dx = cmd[0] & (0xFF);
+ dy = cmd[1] & (0xFF);
+ x += dx;
+ y += dy;
+ break;
+ default:
+ //decode a literal run
+ length = cmd[1] & (0xFF);
+ copylength = length;
+ //absolute mode must be word-aligned
+ length += (length & 1);
+ run.resize(length);
+ if(fread(&run[0], 1, length, fp) != length)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ return false;
+ }
+
+ for(unsigned int i = 0; i < length; i += 1)
+ {
+ colorIndex[x + width * (height - y - 1) + i] = run[i];
+ }
+ x += copylength;
+ break;
+ }
+ }// end if cmd[0] ==
+ else
+ {
+ length = cmd[0] & (0xFF);
+ for(unsigned int i = 0; i < length; i ++)
+ {
+ colorIndex[(height - y - 1) * width + x] = cmd[1];
+ x++;
+ }
+ }
+ }
+ int ctIndex = 0;
+ for(unsigned int index = 0; index < width * height; index = index + 1)
+ {
+ ctIndex = colorIndex[ index];
+ pixelsPtr[3 * index ] = colorTable[4 * ctIndex + 2];
+ pixelsPtr[3 * index + 1] = colorTable[4 * ctIndex + 1];
+ pixelsPtr[3 * index + 2] = colorTable[4 * ctIndex ];
+ }
+ return true;
+}
+
+} // unnamed namespace
+
+bool LoadBmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ BmpFileHeader fileHeader;
+ BmpInfoHeader infoHeader;
+
+ bool ret = LoadBmpHeader( input.file, width, height, fileHeader, infoHeader );
+
+ return ret;
+}
+
+bool LoadBitmapFromBmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ //DALI_ASSERT_DEBUG( bitmap.GetPackedPixelsProfile() != 0 && "Need a packed pixel bitmap to load into." );
+ FILE* const fp = input.file;
+ if(fp == NULL)
+ {
+ DALI_LOG_ERROR("Error loading bitmap\n");
+ return false;
+ }
+ BmpFormat customizedFormat = BMP_NOTEXIST;
+ BmpFileHeader fileHeader;
+ BmpInfoHeader infoHeader;
+
+ // Load the header info
+ unsigned int width, height;
+
+ if (!LoadBmpHeader(fp, width, height, fileHeader, infoHeader))
+ {
+ return false;
+ }
+
+ Pixel::Format pixelFormat = Pixel::RGB888;
+ switch(infoHeader.compression)
+ {
+ case 0:
+ switch (infoHeader.bitsPerPixel)
+ {
+ case 32:
+ pixelFormat = Pixel::BGR8888;
+ break;
+
+ case 24:
+ if(fileHeader.offset == FileHeaderOffsetOfRGB24V5)//0x8A
+ {
+ customizedFormat = BMP_RGB24V5;
+ }
+ else
+ {
+ pixelFormat = Pixel::RGB888;
+ }
+ break;
+
+ case 16:
+ customizedFormat = BMP_RGB555;
+ break;
+
+ case 8:
+ customizedFormat = BMP_RGB8;
+ break;
+
+ case 4: // RGB4
+ customizedFormat = BMP_RGB4;
+ break;
+
+ case 1: //RGB1
+ customizedFormat = BMP_RGB1;
+ break;
+ default:
+ DALI_LOG_WARNING("%d bits per pixel not supported for BMP files\n", infoHeader.bitsPerPixel);
+ return false;
+ }
+ break;
+ case 1: //// RLE8
+ {
+ if(infoHeader.bitsPerPixel == 8)
+ {
+ customizedFormat = BMP_RLE8;
+ }
+ break;
+ }
+ case 2: // RLE4
+ {
+ if(infoHeader.bitsPerPixel == 4)
+ {
+ customizedFormat = BMP_RLE4;
+ }
+ break;
+ }
+ case 3: // // BI_BITFIELDS
+ {
+ if(infoHeader.bitsPerPixel == 16)
+ {
+ if( fseek(fp, 14 + infoHeader.infoHeaderSize + 1, SEEK_SET) )
+ {
+ return false;
+ }
+
+ char mask;
+ if(fread(&mask, 1, 1, fp) != 1)
+ {
+ return false;
+ }
+
+ if((mask & 0x80) == MaskForBFRGB565) // mask is 0xF8
+ {
+ pixelFormat = Pixel::RGB565;
+ }
+ else if((mask & 0x80) == 0)// mask is 0x 7C
+ {
+ customizedFormat = BMP_BITFIELDS555;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(infoHeader.bitsPerPixel == 32)
+ {
+ if(fileHeader.offset == FileHeaderOffsetOfBF32V4)// 0x7A
+ {
+ customizedFormat = BMP_BITFIELDS32V4;
+ }
+ else
+ {
+ customizedFormat = BMP_BITFIELDS32;
+ }
+ }
+ break;
+ }
+ default:
+ DALI_LOG_WARNING("Compression not supported for BMP files\n");
+ return false;
+ }
+
+ bool topDown = false;
+
+ // if height is negative, bitmap data is top down
+ if (infoHeader.height<0)
+ {
+ infoHeader.height = abs(infoHeader.height);
+ height = infoHeader.height;
+ topDown = true;
+ }
+
+ unsigned int rowStride = infoHeader.width * (infoHeader.bitsPerPixel >>3);
+
+ // bitmaps row stride is padded to 4 bytes
+ unsigned int padding = (rowStride % 4);
+ if (padding)
+ {
+ padding = 4 - padding;
+ }
+
+ int imageW = infoHeader.width;
+ int pixelBufferW = infoHeader.width;
+ int pixelBufferH = infoHeader.height;
+ auto newPixelFormat = Pixel::Format::INVALID;
+
+ switch(customizedFormat)
+ {
+ case BMP_RLE8:
+ case BMP_RGB8:
+ case BMP_RGB4:
+ case BMP_RLE4:
+ case BMP_RGB555:
+ case BMP_BITFIELDS555:
+ {
+ pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW;
+ pixelBufferH = abs(infoHeader.height);
+ newPixelFormat = Pixel::RGB888;
+ break;
+ }
+ case BMP_RGB1:
+ {
+ pixelBufferW = ((imageW & 63) != 0) ? imageW + 64 - (imageW & 63) : imageW;
+ pixelBufferH = abs(infoHeader.height);
+ newPixelFormat = Pixel::RGB888;
+ break;
+ }
+ case BMP_BITFIELDS32:
+ case BMP_BITFIELDS32V4:
+ {
+ pixelBufferH = abs(infoHeader.height);
+ newPixelFormat = Pixel::RGB8888;
+ break;
+ }
+ case BMP_RGB24V5:
+ {
+ newPixelFormat = Pixel::RGB888;
+ break;
+ }
+ default:
+ if(pixelFormat == Pixel::RGB565 )
+ {
+ pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW;
+ pixelBufferH = abs(infoHeader.height);
+ newPixelFormat = Pixel::RGB565;
+ }
+ else
+ {
+ pixelBufferW = infoHeader.width;
+ pixelBufferH = infoHeader.height;
+ newPixelFormat = pixelFormat;
+ }
+ break;
+ }
+
+ bitmap = Dali::Devel::PixelBuffer::New(pixelBufferW, pixelBufferH, newPixelFormat);
+ auto pixels = bitmap.GetBuffer();
+
+ // Read the raw bitmap data
+ decltype(pixels) pixelsIterator = nullptr;
+
+ bool decodeResult(false);
+ switch(customizedFormat)
+ {
+ case BMP_RGB1:
+ {
+ decodeResult = DecodeRGB1( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
+ break;
+ }
+ case BMP_RGB4:
+ {
+ decodeResult = DecodeRGB4(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
+ break;
+ }
+ case BMP_RLE4:
+ {
+ decodeResult = DecodeRLE4( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
+ break;
+ }
+ case BMP_BITFIELDS32:
+ {
+ decodeResult = DecodeBF32(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
+ break;
+ }
+ case BMP_BITFIELDS555:
+ {
+ decodeResult = DecodeBF555(fp, pixels,infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
+ break;
+ }
+ case BMP_RGB555:
+ {
+ decodeResult = DecodeRGB555(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
+ break;
+ }
+ case BMP_RGB8:
+ {
+ decodeResult = DecodeRGB8(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
+ break;
+ }
+ case BMP_RLE8:
+ {
+ decodeResult = DecodeRLE8(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
+ break;
+ }
+ case BMP_RGB24V5:
+ {
+ decodeResult = DecodeRGB24V5(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
+ break;
+ }
+ case BMP_BITFIELDS32V4:
+ {
+ decodeResult = DecodeBF32V4(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
+ break;
+ }
+ default:
+ {
+ if(pixelFormat == Pixel::RGB565)
+ {
+ decodeResult = DecodeBF565(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
+ }
+ else
+ {
+ for (unsigned int yPos = 0; yPos < height; yPos++)
+ {
+ if (topDown)
+ {
+ // the data in the file is top down, and we store the data top down
+ pixelsIterator = pixels + ( yPos * rowStride);
+ }
+ else
+ {
+ // the data in the file is bottom up, and we store the data top down
+ pixelsIterator = pixels + (((height-1)-yPos) * rowStride);
+ }
+
+ if (fread(pixelsIterator, 1, rowStride, fp) != rowStride)
+ {
+ DALI_LOG_ERROR("Error reading the BMP image\n");
+ break;
+ }
+
+ // If 24 bit mode then swap Blue and Red pixels
+ // BGR888 doesn't seem to be supported by dali-core
+ if (infoHeader.bitsPerPixel == 24 )
+ {
+ for(unsigned int i = 0; i < rowStride; i += 3)
+ {
+ unsigned char temp = pixelsIterator[i];
+ pixelsIterator[i] = pixelsIterator[i+2];
+ pixelsIterator[i+2] = temp;
+ }
+ }
+
+ if (padding)
+ {
+ if( fseek(fp, padding, SEEK_CUR) ) // move past the padding.
+ {
+ DALI_LOG_ERROR("Error moving past BMP padding\n");
+ }
+ }
+ }
+ decodeResult = true;
+ }
+ break;
+ }
+ } // switch
+
+ if( !decodeResult )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Bmp
+{
+const unsigned char MAGIC_BYTE_1 = 0x42;
+const unsigned char MAGIC_BYTE_2 = 0x4D;
+} // namespace Bmp
+
+/**
+ * Loads the bitmap from an BMP file. This function checks the header first
+ * and if it is not a BMP file, then it returns straight away.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromBmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a BMP file and fills in the width and height appropriately.
+ * @param[in] fp Pointer to the Image file
+ * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
+ * @param[out] width Is set with the width of the image
+ * @param[out] height Is set with the height of the image
+ * @return true if the file's header was read successully, false otherwise
+ */
+bool LoadBmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/imaging/common/loader-gif.h>
+
+#include <gif_lib.h>
+
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <memory>
+
+// We need to check if giflib has the new open and close API (including error parameter).
+#ifdef GIFLIB_MAJOR
+#define LIBGIF_VERSION_5_1_OR_ABOVE
+#endif
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+
+// simple class to enforce clean-up of GIF structures
+struct AutoCleanupGif
+{
+ AutoCleanupGif(GifFileType*& _gifInfo)
+ : gifInfo(_gifInfo)
+ {
+ }
+
+ ~AutoCleanupGif()
+ {
+ if(NULL != gifInfo)
+ {
+ // clean up GIF resources
+#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
+ int errorCode = 0; //D_GIF_SUCCEEDED is 0
+ DGifCloseFile( gifInfo, &errorCode );
+
+ if( errorCode )
+ {
+ DALI_LOG_ERROR( "GIF Loader: DGifCloseFile Error. Code: %d\n", errorCode );
+ }
+#else
+ DGifCloseFile( gifInfo );
+#endif
+ }
+ }
+
+ GifFileType*& gifInfo;
+};
+
+// Used in the GIF interlace algorithm to determine the starting byte and the increment required
+// for each pass.
+struct InterlacePair
+{
+ unsigned int startingByte;
+ unsigned int incrementalByte;
+};
+
+// Used in the GIF interlace algorithm to determine the order and which location to read data from
+// the file.
+const InterlacePair INTERLACE_PAIR_TABLE [] = {
+ { 0, 8 }, // Starting at 0, read every 8 bytes.
+ { 4, 8 }, // Starting at 4, read every 8 bytes.
+ { 2, 4 }, // Starting at 2, read every 4 bytes.
+ { 1, 2 }, // Starting at 1, read every 2 bytes.
+};
+const unsigned int INTERLACE_PAIR_TABLE_SIZE( sizeof( INTERLACE_PAIR_TABLE ) / sizeof( InterlacePair ) );
+
+/// Function used by Gif_Lib to read from the image file.
+int ReadDataFromGif(GifFileType *gifInfo, GifByteType *data, int length)
+{
+ FILE *fp = reinterpret_cast<FILE*>(gifInfo->UserData);
+ return fread( data, sizeof( GifByteType ), length, fp);
+}
+
+/// Loads the GIF Header.
+bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileType** gifInfo)
+{
+ int errorCode = 0; //D_GIF_SUCCEEDED is 0
+
+#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
+ *gifInfo = DGifOpen( reinterpret_cast<void*>(fp), ReadDataFromGif, &errorCode );
+#else
+ *gifInfo = DGifOpen( reinterpret_cast<void*>(fp), ReadDataFromGif );
+#endif
+
+ if ( !(*gifInfo) || errorCode )
+ {
+ DALI_LOG_ERROR( "GIF Loader: DGifOpen Error. Code: %d\n", errorCode );
+ return false;
+ }
+
+ width = (*gifInfo)->SWidth;
+ height = (*gifInfo)->SHeight;
+
+ // No proper size in GIF.
+ if ( width <= 0 || height <= 0 )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+/// Decode the GIF image.
+bool DecodeImage( GifFileType* gifInfo, unsigned char* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow )
+{
+ if ( gifInfo->Image.Interlace )
+ {
+ // If the image is interlaced, then use the GIF interlace algorithm to read the file appropriately.
+
+ const InterlacePair* interlacePairPtr( INTERLACE_PAIR_TABLE );
+ for ( unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr )
+ {
+ for( unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte )
+ {
+ unsigned char* row = decodedData + currentByte * bytesPerRow;
+ if ( DGifGetLine( gifInfo, row, width ) == GIF_ERROR )
+ {
+ DALI_LOG_ERROR( "GIF Loader: Error reading Interlaced GIF\n" );
+ return false;
+ }
+ }
+ }
+ }
+ else
+ {
+ // Non-interlace does not require any erratic reading / jumping.
+ unsigned char* decodedDataPtr( decodedData );
+
+ for ( unsigned int row = 0; row < height; ++row )
+ {
+ if ( DGifGetLine( gifInfo, decodedDataPtr, width ) == GIF_ERROR)
+ {
+ DALI_LOG_ERROR( "GIF Loader: Error reading non-interlaced GIF\n" );
+ return false;
+ }
+ decodedDataPtr += bytesPerRow;
+ }
+ }
+ return true;
+}
+
+// Retrieves the colors used in the GIF image.
+GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo )
+{
+ GifColorType* color( NULL );
+ if ( image->ImageDesc.ColorMap )
+ {
+ color = image->ImageDesc.ColorMap->Colors;
+ }
+ else
+ {
+ // if there is no color map for this image use the default one
+ color = gifInfo->SColorMap->Colors;
+ }
+ return color;
+}
+
+/// Called when we want to handle IMAGE_DESC_RECORD_TYPE
+bool HandleImageDescriptionRecordType( Dali::Devel::PixelBuffer& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished )
+{
+ if ( DGifGetImageDesc( gifInfo ) == GIF_ERROR )
+ {
+ DALI_LOG_ERROR( "GIF Loader: Error getting Image Description\n" );
+ return false;
+ }
+
+ // Ensure there is at least 1 image in the GIF.
+ if ( gifInfo->ImageCount < 1 )
+ {
+ DALI_LOG_ERROR( "GIF Loader: No Images\n" );
+ return false;
+ }
+
+ Pixel::Format pixelFormat( Pixel::RGB888 );
+
+ SavedImage* image( &gifInfo->SavedImages[ gifInfo->ImageCount - 1 ] );
+ const GifImageDesc& desc( image->ImageDesc );
+
+ auto decodedData = new unsigned char[ width * height * sizeof( GifPixelType ) ];
+
+ std::unique_ptr<unsigned char[]> ptr{ decodedData };
+
+ const unsigned int bytesPerRow( width * sizeof( GifPixelType ) );
+ const unsigned int actualWidth( desc.Width );
+ const unsigned int actualHeight( desc.Height );
+
+ // Create a buffer to store the decoded data.
+ bitmap = Dali::Devel::PixelBuffer::New( actualWidth, actualHeight, pixelFormat );
+
+ // Decode the GIF Image
+ if ( !DecodeImage( gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow ) )
+ {
+ return false;
+ }
+
+ // Get the colormap for the GIF
+ GifColorType* color( GetImageColors( image, gifInfo ) );
+
+ // If it's an animated GIF, we still only read the first image
+
+ // Create and populate pixel buffer.
+ auto pixels = bitmap.GetBuffer();
+ for (unsigned int row = 0; row < actualHeight; ++row)
+ {
+ for (unsigned int column = 0; column < actualWidth; ++column)
+ {
+ unsigned char index = decodedData[row * width + column];
+
+ pixels[0] = color[index].Red;
+ pixels[1] = color[index].Green;
+ pixels[2] = color[index].Blue;
+ pixels += 3;
+ }
+ }
+ finished = true;
+ return true;
+}
+
+/// Called when we want to handle EXTENSION_RECORD_TYPE
+bool HandleExtensionRecordType( GifFileType* gifInfo )
+{
+ SavedImage image;
+ GifByteType *extensionByte( NULL );
+
+#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
+ ExtensionBlock extensionBlocks;
+ image.ExtensionBlocks = &extensionBlocks;
+ image.ExtensionBlockCount = 1;
+ int *extensionBlockTypePointer = &image.ExtensionBlocks->Function;
+#else
+ image.ExtensionBlocks = NULL;
+ image.ExtensionBlockCount = 0;
+ int *extensionBlockTypePointer = &image.Function;
+#endif
+
+ // Not really interested in the extensions so just skip them unless there is an error.
+ for ( int extRetCode = DGifGetExtension( gifInfo, extensionBlockTypePointer, &extensionByte );
+ extensionByte != NULL;
+ extRetCode = DGifGetExtensionNext( gifInfo, &extensionByte ) )
+ {
+ if ( extRetCode == GIF_ERROR )
+ {
+ DALI_LOG_ERROR( "GIF Loader: Error reading GIF Extension record.\n" );
+ return false;
+ }
+ }
+
+ return true;
+}
+
+} // unnamed namespace
+
+bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ GifFileType* gifInfo = NULL;
+ AutoCleanupGif autoCleanupGif(gifInfo);
+ FILE* const fp = input.file;
+
+ return LoadGifHeader(fp, width, height, &gifInfo);
+}
+
+bool LoadBitmapFromGif( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ FILE* const fp = input.file;
+ // Load the GIF Header file.
+
+ GifFileType* gifInfo( NULL );
+ unsigned int width( 0 );
+ unsigned int height( 0 );
+ if ( !LoadGifHeader( fp, width, height, &gifInfo ) )
+ {
+ return false;
+ }
+ AutoCleanupGif autoGif( gifInfo );
+
+ // Check each record in the GIF file.
+
+ bool finished( false );
+ GifRecordType recordType( UNDEFINED_RECORD_TYPE );
+ for ( int returnCode = DGifGetRecordType( gifInfo, &recordType );
+ !finished && recordType != TERMINATE_RECORD_TYPE;
+ returnCode = DGifGetRecordType( gifInfo, &recordType ) )
+ {
+ if ( returnCode == GIF_ERROR )
+ {
+ DALI_LOG_ERROR( "GIF Loader: Error getting Record Type\n" );
+ return false;
+ }
+
+ if( IMAGE_DESC_RECORD_TYPE == recordType )
+ {
+ if ( !HandleImageDescriptionRecordType( bitmap, gifInfo, width, height, finished ) )
+ {
+ return false;
+ }
+ }
+ else if ( EXTENSION_RECORD_TYPE == recordType )
+ {
+ if ( !HandleExtensionRecordType( gifInfo ))
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Gif
+{
+const unsigned char MAGIC_BYTE_1 = 0x47;
+const unsigned char MAGIC_BYTE_2 = 0x49;
+} // namespace Gif
+
+/**
+ * Loads the bitmap from a GIF file. This function checks the header first
+ * and if it is not a GIF file, then it returns straight away.
+ * @note For animated GIFs, only the first image is displayed
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromGif( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a GIF file and fills in the width and height appropriately.
+ * @param[in] fp Pointer to the Image file
+ * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
+ * @param[in/out] width Is set with the width of the image
+ * @param[in/out] height Is set with the height of the image
+ * @return true if the file's header was read successully, false otherwise
+ */
+bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Derived from Enlightenment file evas_image_load_ico.c[1] which is licensed
+ * under the BSD 2-clause license[2] reproduced below.
+ *
+ * [1][http://web.archive.org/web/20141201151111/http://git.enlightenment.org/core/efl.git/tree/src/modules/evas/loaders/ico/evas_image_load_ico.c]
+ * [2][http://web.archive.org/web/20140717012400/https://git.enlightenment.org/core/efl.git/about/]
+ *
+ * Copyright (C) 2002-2012 Carsten Haitzler, Dan Sinclair, Mike Blumenkrantz,
+ * Samsung Electronics and various contributors (see AUTHORS)
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// HEADER
+#include <dali/internal/imaging/common/loader-ico.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+// Reserved 2 bytes + type 2 bytes + count 2 bytes + count * 16 bytes
+const unsigned char ICO_FILE_HEADER = 22;
+// Info header 40 bytes = size 4 bytes + width 4 bytes + height 4 bytes + planes 2 bytes + bitcount 2 bytes
+// + compression 4 bytes + imagesize 4 bytes + xpixelsPerM 4 bytes + ypixelsPerM 4 bytes + colorsUsed 4 bytes + colorImportant 4 bytes
+// besides, there are rgba color data = numberOfColors * 4 bytes
+const unsigned char ICO_IMAGE_INFO_HEADER = 40;
+
+typedef unsigned char DATA8;
+#define A_VAL(p) (reinterpret_cast< DATA8 * >( p )[3])
+
+#define RGB_JOIN(r,g,b) \
+ (((r) << 16) + ((g) << 8) + (b))
+
+#define ARGB_JOIN(a,r,g,b) \
+ (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
+
+bool read_ushort(unsigned char *map, size_t length, size_t *position, unsigned short *ret)
+{
+ unsigned char b[2];
+
+ if (*position + 2 > length)
+ {
+ return false;
+ }
+ b[0] = map[(*position)++];
+ b[1] = map[(*position)++];
+ *ret = (b[1] << 8) | b[0];
+ return true;
+}
+
+bool read_uint(unsigned char *map, size_t length, size_t *position, unsigned int *ret)
+{
+ unsigned char b[4];
+ unsigned int i;
+
+ if (*position + 4 > length)
+ {
+ return false;
+ }
+ for (i = 0; i < 4; i++)
+ {
+ b[i] = map[(*position)++];
+ }
+ *ret = ARGB_JOIN(b[3], b[2], b[1], b[0]);
+ return true;
+}
+
+bool read_uchar(unsigned char *map, size_t length, size_t *position, unsigned char *ret)
+{
+ if (*position + 1 > length)
+ {
+ return false;
+ }
+ *ret = map[(*position)++];
+ return true;
+}
+
+bool read_mem(unsigned char *map, size_t length, size_t *position, void *buffer, int size)
+{
+ if (*position + size > length)
+ {
+ return false;
+ }
+ memcpy(buffer, map + *position, size);
+ *position += size;
+ return true;
+}
+
+enum
+{
+ SMALLEST,
+ BIGGEST,
+ SMALLER,
+ BIGGER
+};
+
+enum
+{
+ ICON = 1,
+ CURSOR = 2
+};
+
+struct IcoData
+{
+ int pdelta;
+ int w, h;
+ int cols;
+ int bpp, planes;
+ int hot_x, hot_y;
+ unsigned int bmoffset, bmsize;
+};
+
+bool LoadIcoHeaderHelper( FILE* fp,
+ IcoData& chosen,
+ Dali::Vector<unsigned char>& map,
+ unsigned int& fsize )
+{
+ memset( &chosen, 0, sizeof(chosen) );
+
+ if(fp == NULL)
+ {
+ DALI_LOG_ERROR("Error loading bitmap\n");
+ return false;
+ }
+ size_t position = 0;
+ unsigned short word;
+ unsigned char byte;
+
+ if( fseek(fp,0,SEEK_END) )
+ {
+ DALI_LOG_ERROR("Error seeking ICO data\n");
+ return false;
+ }
+
+ long positionIndicator = ftell(fp);
+ fsize = 0u;
+
+ if( positionIndicator > -1L )
+ {
+ fsize = static_cast<unsigned int>(positionIndicator);
+ }
+
+ if( 0u == fsize )
+ {
+ return false;
+ }
+
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking ICO data\n");
+ return false;
+ }
+
+ if (fsize < (ICO_FILE_HEADER + ICO_IMAGE_INFO_HEADER)) //6 + 16 + 40
+ {
+ return false;
+ }
+ map.Resize(fsize);
+
+ if(fread(&map[0], 1, fsize, fp) != fsize)
+ {
+ DALI_LOG_WARNING("image file read opeation error!\n");
+ return false;
+ }
+
+ int search = BIGGEST;
+ unsigned short reserved, type, count;
+ if (!read_ushort(&map[0], fsize, &position, &reserved))
+ {
+ return false;
+ }
+ if (!read_ushort(&map[0], fsize, &position, &type))
+ {
+ return false;
+ }
+ if (!read_ushort(&map[0], fsize, &position, &count))
+ {
+ return false;
+ }
+ if (!((reserved == 0) &&
+ ((type == ICON) || (type == CURSOR)) && (count != 0)))
+ {
+ return false;
+ }
+ search = BIGGEST;
+ chosen.pdelta = 0;
+ bool have_choice = false;
+
+ for (unsigned short i = 0; i < count; i++)
+ {
+ unsigned char tw = 0, th = 0, tcols = 0;
+ if (!read_uchar(&map[0], fsize, &position, &tw))
+ {
+ return false;
+ }
+ int w = tw;
+ if (w <= 0)
+ {
+ w = 256;
+ }
+ if (!read_uchar(&map[0], fsize, &position, &th))
+ {
+ return false;
+
+ }
+ int h = th;
+ if (h <= 0)
+ {
+ h = 256;
+ }
+ if (!read_uchar(&map[0], fsize, &position, &tcols))
+ {
+ return false;
+ }
+ int cols = tcols;
+ if (!read_uchar(&map[0], fsize, &position, &byte))
+ {
+ return false;
+ }
+ if (!read_ushort(&map[0], fsize, &position, &word))
+ {
+ return false;
+ }
+ int planes=0;
+ if (type == 1)
+ {
+ planes = word;
+ }
+ //else hot_x = word;
+ if (!read_ushort(&map[0], fsize, &position, &word))
+ {
+ return false;
+ }
+ int bpp=0;
+ if (type == 1)
+ {
+ bpp = word;
+ }
+
+ // 0 colors means 256 for paletized modes.
+ // Note: We must not do this conversion for bpp greater than 8, as there is no palette.
+ if( bpp <= 8 && cols == 0 )
+ {
+ cols = 256;
+ }
+
+ //else hot_y = word;
+ unsigned int bmoffset, bmsize;
+ if (!read_uint(&map[0], fsize, &position, &bmsize))
+ {
+ return false;
+ }
+ if (!read_uint(&map[0], fsize, &position, &bmoffset))
+ {
+ return false;
+ }
+ if ((bmsize <= 0) || (bmoffset <= 0) || (bmoffset >= fsize))
+ {
+ return false;
+ }
+ if (search == BIGGEST)
+ {
+ int pdelta = w * h;
+ if ((!have_choice) ||
+ ((pdelta >= chosen.pdelta) &&
+ (((bpp >= 3) && (bpp >= chosen.bpp)) ||
+ ((bpp < 3) && (cols >= chosen.cols)))))
+ {
+ have_choice = true;
+ chosen.pdelta = pdelta;
+ chosen.w = w;
+ chosen.h = h;
+ chosen.cols = cols;
+ chosen.bpp = bpp;
+ chosen.planes = planes;
+ chosen.bmsize = bmsize;
+ chosen.bmoffset = bmoffset;
+ }
+ }
+ }
+
+ if (chosen.bmoffset == 0)
+ {
+ return false;
+ }
+
+ return true;
+}
+
+}//unnamed namespace
+
+bool LoadIcoHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ IcoData chosen;
+ Dali::Vector<unsigned char> map;
+ unsigned int fsize;
+ FILE* const fp = input.file;
+
+ if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) )
+ {
+ return false;
+ }
+
+ width = chosen.w;
+ height = chosen.h;
+
+ return true;
+}
+
+bool LoadBitmapFromIco( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ IcoData chosen;
+ Dali::Vector<unsigned char> map;
+ unsigned int fsize;
+ FILE* const fp = input.file;
+
+ if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) )
+ {
+ return false;
+ }
+
+ Dali::Vector<unsigned int> pal;
+ Dali::Vector<unsigned int> surface;
+ Dali::Vector<unsigned char> maskbuf;
+ Dali::Vector<unsigned char> pixbuf;
+ pal.Resize(256 * 4);
+
+ unsigned int dword;
+ unsigned short word;
+
+ int diff_size = 0;
+ unsigned int* pix;
+
+ size_t position = chosen.bmoffset;//22 == position
+
+ unsigned int w = chosen.w;
+ unsigned int h = chosen.h;
+ unsigned int cols = chosen.cols;
+
+ // read bmp header time... let's do some checking
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // headersize - dont care
+ }
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // width
+ }
+ if (dword > 0)
+ {
+ if (dword != w)
+ {
+ w = dword;
+ diff_size = 1;
+ }
+ }
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // height
+ }
+ if (dword > 0)
+ {
+ if (dword != (h * 2))
+ {
+ h = dword / 2;
+ diff_size = 1;
+ }
+ }
+ if (diff_size)
+ {
+ DALI_LOG_WARNING("Broken ICO file!\n");
+ }
+
+ // Set up the surface as soon as we have the width and height, so we have a black image if there are any further errors.
+ surface.Resize( w * h * 4 );
+ memset( &surface[0], 0, w * h * 4 );
+
+ if (!read_ushort(&map[0], fsize, &position, &word))
+ {
+ return false; // planes
+ }
+ //planes2 = word;
+ if (!read_ushort(&map[0], fsize, &position, &word))
+ {
+ return false; // bitcount
+ }
+ unsigned int bitcount = word;
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // compression
+ }
+ //compression = dword;
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // imagesize
+ }
+ //imagesize = dword;
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // z pixels per m
+ }
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // y pizels per m
+ }
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // colors used
+ }
+ //colorsused = dword;
+ if (!read_uint(&map[0], fsize, &position, &dword))
+ {
+ return false; // colors important
+ }
+
+ for( unsigned int i = 0; i < cols ; i ++ )
+ {
+ unsigned char a, r, g, b;
+
+ if (!read_uchar(&map[0], fsize, &position, &b))
+ {
+ return false;
+ }
+ if (!read_uchar(&map[0], fsize, &position, &g))
+ {
+ return false;
+ }
+ if (!read_uchar(&map[0], fsize, &position, &r))
+ {
+ return false;
+ }
+ if (!read_uchar(&map[0], fsize, &position, &a))
+ {
+ return false;
+ }
+ pal[i] = ARGB_JOIN( 0xff, b, g, r );
+ }
+
+ // This is the reference way of calculating the total number of bytes necessary to store one row of pixels.
+ unsigned int stride = ( ( ( bitcount * w ) + 31 ) / 32 ) * 4;
+ unsigned int bitStride = ( ( w + 31 ) / 32 ) * 4;
+
+ // Pixbuf only ever contains one scanline worth of data.
+ pixbuf.Resize( stride );
+ maskbuf.Resize( bitStride * h );
+
+ // Handle different bits-per-pixel.
+ // Note: Switch is in order of most common format first.
+ switch( bitcount )
+ {
+ case 32:
+ {
+ unsigned char* p = &map[position];
+ pix = &surface[0] + ( ( h - 1 ) * w );
+
+ for( unsigned int i = 0; i < h; i++ )
+ {
+ for( unsigned int j = 0; j < w; j++ )
+ {
+ *pix++ = ARGB_JOIN( p[3], p[0], p[1], p[2] );
+ p += 4;
+ }
+ // Move the output up 1 line (we subtract 2 lines because we moved forward one line while copying).
+ pix -= ( w * 2 );
+ }
+ break;
+ }
+
+ case 24:
+ {
+ for( unsigned int i = 0; i < h; i++ )
+ {
+ pix = &surface[0] + ( ( h - 1 - i ) * w );
+ if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
+ {
+ return false;
+ }
+ unsigned char* p = &pixbuf[0];
+ for( unsigned int j = 0; j < w; j++ )
+ {
+ *pix++ = ARGB_JOIN( 0xff, p[0], p[1], p[2] );
+ p += 3;
+ }
+ }
+ break;
+ }
+
+ case 8:
+ {
+ for( unsigned int i = 0; i < h; i++ )
+ {
+ pix = &surface[0] + ( ( h - 1 - i ) * w );
+ if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
+ {
+ return false;
+ }
+ unsigned char* p = &pixbuf[0];
+ for( unsigned int j = 0; j < w; j++ )
+ {
+ *pix++ = pal[*p++];
+ }
+ }
+ break;
+ }
+
+ case 4:
+ {
+ for( unsigned int i = 0; i < h; i++ )
+ {
+ pix = &surface[0] + ( ( h - 1 - i ) * w );
+ if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
+ {
+ return false;
+ }
+ unsigned char* p = &pixbuf[0];
+ for( unsigned int j = 0; j < w; j++ )
+ {
+ if( j & 0x1 )
+ {
+ *pix = pal[*p & 0x0f];
+ p++;
+ }
+ else
+ {
+ *pix = pal[*p >> 4];
+ }
+ pix++;
+ }
+ }
+ break;
+ }
+
+ case 1:
+ {
+ for( unsigned int i = 0; i < h; i++ )
+ {
+ pix = &surface[0] + ( ( h - 1 - i ) * w );
+ if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
+ {
+ return false;
+ }
+ unsigned char* p = &pixbuf[0];
+
+ for( unsigned int j = 0; j < w; j += 8 )
+ {
+ *pix++ = pal[ *p >> 7 ];
+ *pix++ = pal[ *p >> 6 & 0x01 ];
+ *pix++ = pal[ *p >> 5 & 0x01 ];
+ *pix++ = pal[ *p >> 4 & 0x01 ];
+ *pix++ = pal[ *p >> 3 & 0x01 ];
+ *pix++ = pal[ *p >> 2 & 0x01 ];
+ *pix++ = pal[ *p >> 1 & 0x01 ];
+ *pix++ = pal[ *p >> 0 & 0x01 ];
+
+ p++;
+ }
+ }
+ break;
+ }
+
+ default:
+ {
+ DALI_LOG_WARNING( "Image file contains unsupported bits-per-pixel %d\n", bitcount );
+ return false;
+ }
+ }
+
+ // From the spec: If bpp is less than 32, there will be a 1bpp mask bitmap also.
+ if( bitcount < 32 )
+ {
+ if( !read_mem( &map[0], fsize, &position, &maskbuf[0], bitStride * h ) )
+ {
+ return false;
+ }
+
+ // Apply mask.
+ // Precalc to save time in the loops.
+ unsigned int bytesPerWidth = w / 8;
+ unsigned int bytesRemainingPerWidth = w - ( bytesPerWidth << 3 );
+
+ // Loop for each line of the image.
+ for( unsigned int i = 0; i < h; ++i )
+ {
+ unsigned char *m = &maskbuf[0] + ( bitStride * i );
+ pix = &surface[0] + ( ( h - 1 - i ) * w );
+
+ // Do chunks of 8 pixels first so mask operations can be unrolled.
+ for( unsigned int j = 0; j < bytesPerWidth; ++j )
+ {
+ // Unrolled 8 bits of the mask to avoid many conditions and branches.
+ A_VAL( pix++ ) = ( *m & ( 1 << 7 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 6 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 5 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 4 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 3 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 2 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 1 ) ) ? 0x00 : 0xff;
+ A_VAL( pix++ ) = ( *m & ( 1 << 0 ) ) ? 0x00 : 0xff;
+ m++;
+ }
+
+ // Handle any remaining width ( < 8 ) or images that are < 8 wide.
+ if( bytesRemainingPerWidth > 0 )
+ {
+ for( unsigned int j = 0; j < bytesRemainingPerWidth; ++j )
+ {
+ // Note: Although we are doing less that a bytes worth of mask, we still always start on the first bit.
+ // If the image is smaller than 8 pixels wide, each mask will still start on a new byte.
+ A_VAL( pix++ ) = ( *m & ( 1 << ( 7 - j ) ) ) ? 0x00 : 0xff;
+ }
+ m++;
+ }
+ }
+ }
+
+ bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::Format::RGBA8888);
+ auto pixels = bitmap.GetBuffer();
+ memcpy( pixels, &surface[0], w * h * 4 );
+
+ return true;
+}
+
+}
+
+}
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_ICO_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_ICO_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Ico
+{
+//00 00 01 00 01 00 20 20
+const unsigned char MAGIC_BYTE_1 = 0x00;
+const unsigned char MAGIC_BYTE_2 = 0x00;
+}
+/**
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromIco( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] width of image
+ * @param[out] height of image
+ * @return true if header loaded successfully, false otherwise
+ */
+bool LoadIcoHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+}
+
+}
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+ // CLASS HEADER
+#include <dali/internal/imaging/common/loader-jpeg.h>
+
+// EXTERNAL HEADERS
+#include <functional>
+#include <array>
+#include <utility>
+#include <memory>
+#include <libexif/exif-data.h>
+#include <libexif/exif-loader.h>
+#include <libexif/exif-tag.h>
+#include <turbojpeg.h>
+#include <jpeglib.h>
+#include <cstring>
+#include <setjmp.h>
+
+#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/object/property-array.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+
+// INTERNAL HEADERS
+#include <dali/internal/legacy/tizen/platform-capabilities.h>
+#include <dali/internal/imaging/common/image-operations.h>
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace
+{
+using Dali::Vector;
+namespace Pixel = Dali::Pixel;
+using PixelArray = unsigned char*;
+const unsigned int DECODED_L8 = 1;
+const unsigned int DECODED_RGB888 = 3;
+const unsigned int DECODED_RGBA8888 = 4;
+
+/** Transformations that can be applied to decoded pixels to respect exif orientation
+ * codes in image headers */
+enum class JpegTransform
+{
+ NONE, //< no transformation 0th-Row = top & 0th-Column = left
+ FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right
+ FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right
+ TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left
+ TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top
+ ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top
+ ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom
+ ROTATE_270, //< 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom
+};
+
+/**
+ * @brief Error handling bookeeping for the JPEG Turbo library's
+ * setjmp/longjmp simulated exceptions.
+ */
+struct JpegErrorState
+{
+ struct jpeg_error_mgr errorManager;
+ jmp_buf jumpBuffer;
+};
+
+/**
+ * @brief Called by the JPEG library when it hits an error.
+ * We jump out of the library so our loader code can return an error.
+ */
+void JpegErrorHandler ( j_common_ptr cinfo )
+{
+ DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
+ /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
+ JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
+
+ /* Return control to the setjmp point */
+ longjmp( myerr->jumpBuffer, 1 );
+}
+
+void JpegOutputMessageHandler( j_common_ptr cinfo )
+{
+ /* Stop libjpeg from printing to stderr - Do Nothing */
+}
+
+/**
+ * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
+ * the JPEG to be displayed and fatal errors.
+ */
+bool IsJpegErrorFatal( const std::string& errorMessage )
+{
+ if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) ||
+ ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) ||
+ ( errorMessage.find("Invalid JPEG file structure") != std::string::npos ) ||
+ ( errorMessage.find("Unsupported JPEG process") != std::string::npos ) ||
+ ( errorMessage.find("Unsupported marker type") != std::string::npos ) ||
+ ( errorMessage.find("Bogus marker length") != std::string::npos ) ||
+ ( errorMessage.find("Bogus DQT index") != std::string::npos ) ||
+ ( errorMessage.find("Bogus Huffman table definition") != std::string::npos ))
+ {
+ return false;
+ }
+ return true;
+}
+
+// helpers for safe exif memory handling
+using ExifHandle = std::unique_ptr<ExifData, decltype(exif_data_free)*>;
+
+ExifHandle MakeNullExifData()
+{
+ return ExifHandle{nullptr, exif_data_free};
+}
+
+ExifHandle MakeExifDataFromData(unsigned char* data, unsigned int size)
+{
+ return ExifHandle{exif_data_new_from_data(data, size), exif_data_free};
+}
+
+// Helpers for safe Jpeg memory handling
+using JpegHandle = std::unique_ptr<void /*tjhandle*/, decltype(tjDestroy)*>;
+
+JpegHandle MakeJpegCompressor()
+{
+ return JpegHandle{tjInitCompress(), tjDestroy};
+}
+
+JpegHandle MakeJpegDecompressor()
+{
+ return JpegHandle{tjInitDecompress(), tjDestroy};
+}
+
+using JpegMemoryHandle = std::unique_ptr<unsigned char, decltype(tjFree)*>;
+
+JpegMemoryHandle MakeJpegMemory()
+{
+ return JpegMemoryHandle{nullptr, tjFree};
+}
+
+template<class T, class Deleter>
+class UniquePointerSetter final
+{
+public:
+ UniquePointerSetter(std::unique_ptr<T, Deleter>& uniquePointer)
+ : mUniquePointer(uniquePointer),
+ mRawPointer(nullptr)
+ {}
+
+ /// @brief Pointer to Pointer cast operator
+ operator T** () { return &mRawPointer; }
+
+ /// @brief Destructor, reset the unique_ptr
+ ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); }
+
+private:
+ std::unique_ptr<T, Deleter>& mUniquePointer;
+ T* mRawPointer;
+};
+
+template<typename T, typename Deleter>
+UniquePointerSetter<T, Deleter> SetPointer(std::unique_ptr<T, Deleter>& uniquePointer)
+{
+ return UniquePointerSetter<T, Deleter>{uniquePointer};
+}
+
+using TransformFunction = std::function<void(PixelArray,unsigned, unsigned)>;
+using TransformFunctionArray = std::array<TransformFunction, 3>; // 1, 3 and 4 bytes per pixel
+
+/// @brief Select the transform function depending on the pixel format
+TransformFunction GetTransformFunction(const TransformFunctionArray& functions,
+ Pixel::Format pixelFormat)
+{
+ auto function = TransformFunction{};
+
+ int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat);
+ switch( decodedPixelSize )
+ {
+ case DECODED_L8:
+ {
+ function = functions[0];
+ break;
+ }
+ case DECODED_RGB888:
+ {
+ function = functions[1];
+ break;
+ }
+ case DECODED_RGBA8888:
+ {
+ function = functions[2];
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR("Transform operation not supported on this Pixel::Format!");
+ function = functions[1];
+ break;
+ }
+ }
+ return function;
+}
+
+// Storing Exif fields as properties
+template<class R, class V>
+R ConvertExifNumeric( const ExifEntry& entry )
+{
+ return static_cast<R>((*reinterpret_cast<V*>(entry.data)));
+}
+
+void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd )
+{
+ auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd ));
+ switch( entry.format )
+ {
+ case EXIF_FORMAT_ASCII:
+ {
+ out.Insert( shortName, std::string(reinterpret_cast<char *>(entry.data)) );
+ break;
+ }
+ case EXIF_FORMAT_SHORT:
+ {
+ out.Insert( shortName, ConvertExifNumeric<int, unsigned int>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_LONG:
+ {
+ out.Insert( shortName, ConvertExifNumeric<int, unsigned long>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_SSHORT:
+ {
+ out.Insert( shortName, ConvertExifNumeric<int, int>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_SLONG:
+ {
+ out.Insert( shortName, ConvertExifNumeric<int, long>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_FLOAT:
+ {
+ out.Insert (shortName, ConvertExifNumeric<float, float>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_DOUBLE:
+ {
+ out.Insert( shortName, ConvertExifNumeric<float, double>(entry) );
+ break;
+ }
+ case EXIF_FORMAT_RATIONAL:
+ {
+ auto values = reinterpret_cast<unsigned int*>( entry.data );
+ Dali::Property::Array array;
+ array.Add( static_cast<int>(values[0]) );
+ array.Add( static_cast<int>(values[1]) );
+ out.Insert(shortName, array);
+ break;
+ }
+ case EXIF_FORMAT_SBYTE:
+ {
+ out.Insert(shortName, "EXIF_FORMAT_SBYTE Unsupported");
+ break;
+ }
+ case EXIF_FORMAT_BYTE:
+ {
+ out.Insert(shortName, "EXIF_FORMAT_BYTE Unsupported");
+ break;
+ }
+ case EXIF_FORMAT_SRATIONAL:
+ {
+ auto values = reinterpret_cast<int*>( entry.data );
+ Dali::Property::Array array;
+ array.Add(values[0]);
+ array.Add(values[1]);
+ out.Insert(shortName, array);
+ break;
+ }
+ case EXIF_FORMAT_UNDEFINED:
+ default:
+ {
+ std::stringstream ss;
+ ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components;
+ out.Insert( shortName, ss.str());
+ }
+ }
+}
+
+/// @brief Apply a transform to a buffer
+bool Transform(const TransformFunctionArray& transformFunctions,
+ PixelArray buffer,
+ int width,
+ int height,
+ Pixel::Format pixelFormat )
+{
+ auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat);
+ if(transformFunction)
+ {
+ transformFunction(buffer, width, height);
+ }
+ return bool(transformFunction);
+}
+
+/// @brief Auxiliar type to represent pixel data with different number of bytes
+template<size_t N>
+struct PixelType
+{
+ char _[N];
+};
+
+template<size_t N>
+void FlipVertical(PixelArray buffer, int width, int height)
+{
+ // Destination pixel, set as the first pixel of screen
+ auto to = reinterpret_cast<PixelType<N>*>( buffer );
+
+ // Source pixel, as the image is flipped horizontally and vertically,
+ // the source pixel is the end of the buffer of size width * height
+ auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * height - 1;
+
+ for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from)
+ {
+ std::swap(*from, *to);
+ }
+}
+
+template<size_t N>
+void FlipHorizontal(PixelArray buffer, int width, int height)
+{
+ for(auto iy = 0; iy < height; ++iy)
+ {
+ //Set the destination pixel as the beginning of the row
+ auto to = reinterpret_cast<PixelType<N>*>(buffer) + width * iy;
+ //Set the source pixel as the end of the row to flip in X axis
+ auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * (iy + 1) - 1;
+ for(auto ix = 0; ix < width / 2; ++ix, ++to, --from)
+ {
+ std::swap(*from, *to);
+ }
+ }
+}
+
+template<size_t N>
+void Transpose(PixelArray buffer, int width, int height)
+{
+ //Transform vertically only
+ for(auto iy = 0; iy < height / 2; ++iy)
+ {
+ for(auto ix = 0; ix < width; ++ix)
+ {
+ auto to = reinterpret_cast<PixelType<N>*>(buffer) + iy * width + ix;
+ auto from = reinterpret_cast<PixelType<N>*>(buffer) + (height - 1 - iy) * width + ix;
+ std::swap(*from, *to);
+ }
+ }
+}
+
+template<size_t N>
+void Transverse(PixelArray buffer, int width, int height)
+{
+ using PixelT = PixelType<N>;
+ Vector<PixelT> data;
+ data.Resize( width * height );
+ auto dataPtr = data.Begin();
+
+ auto original = reinterpret_cast<PixelT*>(buffer);
+ std::copy(original, original + width * height, dataPtr);
+
+ auto to = original;
+ for( auto iy = 0; iy < width; ++iy )
+ {
+ for( auto ix = 0; ix < height; ++ix, ++to )
+ {
+ auto from = dataPtr + ix * width + iy;
+ *to = *from;
+ }
+ }
+}
+
+
+template<size_t N>
+void Rotate90(PixelArray buffer, int width, int height)
+{
+ using PixelT = PixelType<N>;
+ Vector<PixelT> data;
+ data.Resize(width * height);
+ auto dataPtr = data.Begin();
+
+ auto original = reinterpret_cast<PixelT*>(buffer);
+ std::copy(original, original + width * height, dataPtr);
+
+ std::swap(width, height);
+ auto hw = width * height;
+ hw = - hw - 1;
+
+ auto to = original + width - 1;
+ auto from = dataPtr;
+
+ for(auto ix = width; --ix >= 0;)
+ {
+ for(auto iy = height; --iy >= 0; ++from)
+ {
+ *to = *from;
+ to += width;
+ }
+ to += hw;
+ }
+}
+
+template<size_t N>
+void Rotate180(PixelArray buffer, int width, int height)
+{
+ using PixelT = PixelType<N>;
+ Vector<PixelT> data;
+ data.Resize(width * height);
+ auto dataPtr = data.Begin();
+
+ auto original = reinterpret_cast<PixelT*>(buffer);
+ std::copy(original, original + width * height, dataPtr);
+
+ auto to = original;
+ for( auto iy = 0; iy < width; iy++ )
+ {
+ for( auto ix = 0; ix < height; ix++ )
+ {
+ auto from = dataPtr + (height - ix) * width - 1 - iy;
+ *to = *from;
+ ++to;
+ }
+ }
+}
+
+
+template<size_t N>
+void Rotate270(PixelArray buffer, int width, int height)
+{
+ using PixelT = PixelType<N>;
+ Vector<PixelT> data;
+ data.Resize(width * height);
+ auto dataPtr = data.Begin();
+
+ auto original = reinterpret_cast<PixelT*>(buffer);
+ std::copy(original, original + width * height, dataPtr);
+
+ auto w = height;
+ std::swap(width, height);
+ auto hw = width * height;
+
+ auto* to = original + hw - width;
+ auto* from = dataPtr;
+
+ w = -w;
+ hw = hw + 1;
+ for(auto ix = width; --ix >= 0;)
+ {
+ for(auto iy = height; --iy >= 0;)
+ {
+ *to = *from;
+ ++from;
+ to += w;
+ }
+ to += hw;
+ }
+}
+
+} // namespace
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+JpegTransform ConvertExifOrientation(ExifData* exifData);
+bool TransformSize( int requiredWidth, int requiredHeight,
+ FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
+ JpegTransform transform,
+ int& preXformImageWidth, int& preXformImageHeight,
+ int& postXformImageWidth, int& postXformImageHeight );
+
+bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
+{
+ // using libjpeg API to avoid having to read the whole file in a buffer
+ struct jpeg_decompress_struct cinfo;
+ struct JpegErrorState jerr;
+ cinfo.err = jpeg_std_error( &jerr.errorManager );
+
+ jerr.errorManager.output_message = JpegOutputMessageHandler;
+ jerr.errorManager.error_exit = JpegErrorHandler;
+
+ // On error exit from the JPEG lib, control will pass via JpegErrorHandler
+ // into this branch body for cleanup and error return:
+ if(setjmp(jerr.jumpBuffer))
+ {
+ jpeg_destroy_decompress(&cinfo);
+ return false;
+ }
+
+// jpeg_create_decompress internally uses C casts
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ jpeg_create_decompress( &cinfo );
+#pragma GCC diagnostic pop
+
+ jpeg_stdio_src( &cinfo, fp );
+
+ // Check header to see if it is JPEG file
+ if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
+ {
+ width = height = 0;
+ jpeg_destroy_decompress( &cinfo );
+ return false;
+ }
+
+ width = cinfo.image_width;
+ height = cinfo.image_height;
+
+ jpeg_destroy_decompress( &cinfo );
+ return true;
+}
+
+bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ const int flags= 0;
+ FILE* const fp = input.file;
+
+ if( fseek(fp,0,SEEK_END) )
+ {
+ DALI_LOG_ERROR("Error seeking to end of file\n");
+ return false;
+ }
+
+ long positionIndicator = ftell(fp);
+ unsigned int jpegBufferSize = 0u;
+ if( positionIndicator > -1L )
+ {
+ jpegBufferSize = static_cast<unsigned int>(positionIndicator);
+ }
+
+ if( 0u == jpegBufferSize )
+ {
+ return false;
+ }
+
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking to start of file\n");
+ return false;
+ }
+
+ Vector<unsigned char> jpegBuffer;
+ try
+ {
+ jpegBuffer.Resize( jpegBufferSize );
+ }
+ catch(...)
+ {
+ DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
+ return false;
+ }
+ unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
+
+ // Pull the compressed JPEG image bytes out of a file and into memory:
+ if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
+ {
+ DALI_LOG_WARNING("Error on image file read.\n");
+ return false;
+ }
+
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking to start of file\n");
+ }
+
+ auto jpeg = MakeJpegDecompressor();
+
+ if(!jpeg)
+ {
+ DALI_LOG_ERROR("%s\n", tjGetErrorStr());
+ return false;
+ }
+
+ auto transform = JpegTransform::NONE;
+
+ // extract exif data
+ auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize);
+
+ if( exifData && input.reorientationRequested )
+ {
+ transform = ConvertExifOrientation(exifData.get());
+ }
+
+ std::unique_ptr<Property::Map> exifMap;
+ exifMap.reset( new Property::Map() );
+
+ for( auto k = 0u; k < EXIF_IFD_COUNT; ++k )
+ {
+ auto content = exifData->ifd[k];
+ for (auto i = 0u; i < content->count; ++i)
+ {
+ auto &&tag = content->entries[i];
+ const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast<ExifIfd>(k));
+ if(shortName)
+ {
+ AddExifFieldPropertyMap(*exifMap, *tag, static_cast<ExifIfd>(k));
+ }
+ }
+ }
+
+ // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
+ int chrominanceSubsampling = -1;
+ int preXformImageWidth = 0, preXformImageHeight = 0;
+
+ // In Ubuntu, the turbojpeg version is not correct. so build error occurs.
+ // Temporarily separate Ubuntu and other profiles.
+#ifndef DALI_PROFILE_UBUNTU
+ int jpegColorspace = -1;
+ if( tjDecompressHeader3( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace ) == -1 )
+ {
+ DALI_LOG_ERROR("%s\n", tjGetErrorStr());
+ // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
+ }
+#else
+ if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
+ {
+ DALI_LOG_ERROR("%s\n", tjGetErrorStr());
+ // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
+ }
+#endif
+
+ if(preXformImageWidth == 0 || preXformImageHeight == 0)
+ {
+ DALI_LOG_WARNING("Invalid Image!\n");
+ return false;
+ }
+
+ int requiredWidth = input.scalingParameters.dimensions.GetWidth();
+ int requiredHeight = input.scalingParameters.dimensions.GetHeight();
+
+ // If transform is a 90 or 270 degree rotation, the logical width and height
+ // request from the client needs to be adjusted to account by effectively
+ // rotating that too, and the final width and height need to be swapped:
+ int postXformImageWidth = preXformImageWidth;
+ int postXformImageHeight = preXformImageHeight;
+
+
+ int scaledPreXformWidth = preXformImageWidth;
+ int scaledPreXformHeight = preXformImageHeight;
+ int scaledPostXformWidth = postXformImageWidth;
+ int scaledPostXformHeight = postXformImageHeight;
+
+ TransformSize( requiredWidth, requiredHeight,
+ input.scalingParameters.scalingMode,
+ input.scalingParameters.samplingMode,
+ transform,
+ scaledPreXformWidth, scaledPreXformHeight,
+ scaledPostXformWidth, scaledPostXformHeight );
+
+
+ // Colorspace conversion options
+ TJPF pixelLibJpegType = TJPF_RGB;
+ Pixel::Format pixelFormat = Pixel::RGB888;
+#ifndef DALI_PROFILE_UBUNTU
+ switch (jpegColorspace)
+ {
+ case TJCS_RGB:
+ // YCbCr is not an absolute colorspace but rather a mathematical transformation of RGB designed solely for storage and transmission.
+ // YCbCr images must be converted to RGB before they can actually be displayed.
+ case TJCS_YCbCr:
+ {
+ pixelLibJpegType = TJPF_RGB;
+ pixelFormat = Pixel::RGB888;
+ break;
+ }
+ case TJCS_GRAY:
+ {
+ pixelLibJpegType = TJPF_GRAY;
+ pixelFormat = Pixel::L8;
+ break;
+ }
+ case TJCS_CMYK:
+ case TJCS_YCCK:
+ {
+ pixelLibJpegType = TJPF_CMYK;
+ pixelFormat = Pixel::RGBA8888;
+ break;
+ }
+ default:
+ {
+ pixelLibJpegType = TJPF_RGB;
+ pixelFormat = Pixel::RGB888;
+ break;
+ }
+ }
+#endif
+ // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
+ bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat);
+
+ // set metadata
+ GetImplementation(bitmap).SetMetadata( std::move(exifMap) );
+
+ auto bitmapPixelBuffer = bitmap.GetBuffer();
+
+ if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast<unsigned char*>( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 )
+ {
+ std::string errorString = tjGetErrorStr();
+
+ if( IsJpegErrorFatal( errorString ) )
+ {
+ DALI_LOG_ERROR("%s\n", errorString.c_str() );
+ return false;
+ }
+ else
+ {
+ DALI_LOG_WARNING("%s\n", errorString.c_str() );
+ }
+ }
+
+ const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth );
+ const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight );
+
+ bool result = false;
+ switch(transform)
+ {
+ case JpegTransform::NONE:
+ {
+ result = true;
+ break;
+ }
+ // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
+ case JpegTransform::ROTATE_180:
+ {
+ static auto rotate180Functions = TransformFunctionArray {
+ &Rotate180<1>,
+ &Rotate180<3>,
+ &Rotate180<4>,
+ };
+ result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ case JpegTransform::ROTATE_270:
+ {
+ static auto rotate270Functions = TransformFunctionArray {
+ &Rotate270<1>,
+ &Rotate270<3>,
+ &Rotate270<4>,
+ };
+ result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ case JpegTransform::ROTATE_90:
+ {
+ static auto rotate90Functions = TransformFunctionArray {
+ &Rotate90<1>,
+ &Rotate90<3>,
+ &Rotate90<4>,
+ };
+ result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ case JpegTransform::FLIP_VERTICAL:
+ {
+ static auto flipVerticalFunctions = TransformFunctionArray {
+ &FlipVertical<1>,
+ &FlipVertical<3>,
+ &FlipVertical<4>,
+ };
+ result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ // Less-common orientation changes, since they don't correspond to a camera's physical orientation:
+ case JpegTransform::FLIP_HORIZONTAL:
+ {
+ static auto flipHorizontalFunctions = TransformFunctionArray {
+ &FlipHorizontal<1>,
+ &FlipHorizontal<3>,
+ &FlipHorizontal<4>,
+ };
+ result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ case JpegTransform::TRANSPOSE:
+ {
+ static auto transposeFunctions = TransformFunctionArray {
+ &Transpose<1>,
+ &Transpose<3>,
+ &Transpose<4>,
+ };
+ result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ case JpegTransform::TRANSVERSE:
+ {
+ static auto transverseFunctions = TransformFunctionArray {
+ &Transverse<1>,
+ &Transverse<3>,
+ &Transverse<4>,
+ };
+ result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform );
+ break;
+ }
+ }
+
+ return result;
+}
+
+bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
+ const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
+{
+
+ if( !pixelBuffer )
+ {
+ DALI_LOG_ERROR("Null input buffer\n");
+ return false;
+ }
+
+ // Translate pixel format enum:
+ int jpegPixelFormat = -1;
+
+ switch( pixelFormat )
+ {
+ case Pixel::RGB888:
+ {
+ jpegPixelFormat = TJPF_RGB;
+ break;
+ }
+ case Pixel::RGBA8888:
+ {
+ // Ignore the alpha:
+ jpegPixelFormat = TJPF_RGBX;
+ break;
+ }
+ case Pixel::BGRA8888:
+ {
+ // Ignore the alpha:
+ jpegPixelFormat = TJPF_BGRX;
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
+ return false;
+ }
+ }
+
+ // Assert quality is in the documented allowable range of the jpeg-turbo lib:
+ DALI_ASSERT_DEBUG( quality >= 1 );
+ DALI_ASSERT_DEBUG( quality <= 100 );
+ if( quality < 1 )
+ {
+ quality = 1;
+ }
+ if( quality > 100 )
+ {
+ quality = 100;
+ }
+
+ // Initialise a JPEG codec:
+ {
+ auto jpeg = MakeJpegCompressor();
+ if( jpeg )
+ {
+ DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
+ return false;
+ }
+
+
+ // Safely wrap the jpeg codec's buffer in case we are about to throw, then
+ // save the pixels to a persistent buffer that we own and let our cleaner
+ // class clean up the buffer as it goes out of scope:
+ auto dstBuffer = MakeJpegMemory();
+
+ // Run the compressor:
+ unsigned long dstBufferSize = 0;
+ const int flags = 0;
+
+ if( tjCompress2( jpeg.get(),
+ const_cast<unsigned char*>(pixelBuffer),
+ width, 0, height,
+ jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize,
+ TJSAMP_444, quality, flags ) )
+ {
+ DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
+ return false;
+ }
+
+ encodedPixels.Resize( dstBufferSize );
+ memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize );
+ }
+ return true;
+}
+
+
+JpegTransform ConvertExifOrientation(ExifData* exifData)
+{
+ auto transform = JpegTransform::NONE;
+ ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
+ int orientation = 0;
+ if( entry )
+ {
+ orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
+ switch( orientation )
+ {
+ case 1:
+ {
+ transform = JpegTransform::NONE;
+ break;
+ }
+ case 2:
+ {
+ transform = JpegTransform::FLIP_HORIZONTAL;
+ break;
+ }
+ case 3:
+ {
+ transform = JpegTransform::FLIP_VERTICAL;
+ break;
+ }
+ case 4:
+ {
+ transform = JpegTransform::TRANSPOSE;
+ break;
+ }
+ case 5:
+ {
+ transform = JpegTransform::TRANSVERSE;
+ break;
+ }
+ case 6:
+ {
+ transform = JpegTransform::ROTATE_90;
+ break;
+ }
+ case 7:
+ {
+ transform = JpegTransform::ROTATE_180;
+ break;
+ }
+ case 8:
+ {
+ transform = JpegTransform::ROTATE_270;
+ break;
+ }
+ default:
+ {
+ // Try to keep loading the file, but let app developer know there was something fishy:
+ DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
+ break;
+ }
+ }
+ }
+ return transform;
+}
+
+bool TransformSize( int requiredWidth, int requiredHeight,
+ FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
+ JpegTransform transform,
+ int& preXformImageWidth, int& preXformImageHeight,
+ int& postXformImageWidth, int& postXformImageHeight )
+{
+ bool success = true;
+
+ if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE)
+ {
+ std::swap( requiredWidth, requiredHeight );
+ std::swap( postXformImageWidth, postXformImageHeight );
+ }
+
+ // Apply the special rules for when there are one or two zeros in requested dimensions:
+ const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
+ requiredWidth = correctedDesired.GetWidth();
+ requiredHeight = correctedDesired.GetHeight();
+
+ // Rescale image during decode using one of the decoder's built-in rescaling
+ // ratios (expected to be powers of 2), keeping the final image at least as
+ // wide and high as was requested:
+
+ int numFactors = 0;
+ tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
+ if( factors == NULL )
+ {
+ DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
+ success = false;
+ }
+ else
+ {
+ // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
+ // apply it if the application requested one of those:
+ // (use a switch case here so this code will fail to compile if other modes are added)
+ bool downscale = true;
+ switch( samplingMode )
+ {
+ case SamplingMode::BOX:
+ case SamplingMode::BOX_THEN_NEAREST:
+ case SamplingMode::BOX_THEN_LINEAR:
+ case SamplingMode::DONT_CARE:
+ {
+ downscale = true;
+ break;
+ }
+ case SamplingMode::NO_FILTER:
+ case SamplingMode::NEAREST:
+ case SamplingMode::LINEAR:
+ {
+ downscale = false;
+ break;
+ }
+ }
+
+ int scaleFactorIndex( 0 );
+ if( downscale )
+ {
+ // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
+ for( int i = 1; i < numFactors; ++i )
+ {
+ bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth;
+ bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
+ // If either scaled dimension is smaller than the desired one, we were done at the last iteration
+ if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
+ {
+ break;
+ }
+ // If both dimensions are smaller than the desired one, we were done at the last iteration:
+ if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
+ {
+ break;
+ }
+ // If the width is smaller than the desired one, we were done at the last iteration:
+ if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
+ {
+ break;
+ }
+ // If the width is smaller than the desired one, we were done at the last iteration:
+ if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
+ {
+ break;
+ }
+ // This factor stays is within our fitting mode constraint so remember it:
+ scaleFactorIndex = i;
+ }
+ }
+
+ // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
+ for( int i = scaleFactorIndex; i < numFactors; ++i )
+ {
+ // Continue downscaling to below maximum texture size (if possible)
+ scaleFactorIndex = i;
+
+ if( TJSCALED(postXformImageWidth, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) &&
+ TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) )
+ {
+ // Current scale-factor downscales to below maximum texture size
+ break;
+ }
+ }
+
+ // We have finally chosen the scale-factor, return width/height values
+ if( scaleFactorIndex > 0 )
+ {
+ preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex]));
+ preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex]));
+ postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex]));
+ postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
+ }
+ }
+
+ return success;
+}
+
+ExifHandle LoadExifData( FILE* fp )
+{
+ auto exifData = MakeNullExifData();
+ unsigned char dataBuffer[1024];
+
+ if( fseek( fp, 0, SEEK_SET ) )
+ {
+ DALI_LOG_ERROR("Error seeking to start of file\n");
+ }
+ else
+ {
+ auto exifLoader = std::unique_ptr<ExifLoader, decltype(exif_loader_unref)*>{
+ exif_loader_new(), exif_loader_unref };
+
+ while( !feof(fp) )
+ {
+ int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
+ if( size <= 0 )
+ {
+ break;
+ }
+ if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) )
+ {
+ break;
+ }
+ }
+
+ exifData.reset( exif_loader_get_data( exifLoader.get() ) );
+ }
+
+ return exifData;
+}
+
+bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth();
+ unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
+ FILE* const fp = input.file;
+
+ bool success = false;
+ if( requiredWidth == 0 && requiredHeight == 0 )
+ {
+ success = LoadJpegHeader( fp, width, height );
+ }
+ else
+ {
+ // Double check we get the same width/height from the header
+ unsigned int headerWidth;
+ unsigned int headerHeight;
+ if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
+ {
+ auto transform = JpegTransform::NONE;
+
+ if( input.reorientationRequested )
+ {
+ auto exifData = LoadExifData( fp );
+ if( exifData )
+ {
+ transform = ConvertExifOrientation(exifData.get());
+ }
+
+ int preXformImageWidth = headerWidth;
+ int preXformImageHeight = headerHeight;
+ int postXformImageWidth = headerWidth;
+ int postXformImageHeight = headerHeight;
+
+ success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
+ if(success)
+ {
+ width = postXformImageWidth;
+ height = postXformImageHeight;
+ }
+ }
+ else
+ {
+ success = true;
+ width = headerWidth;
+ height = headerHeight;
+ }
+ }
+ }
+ return success;
+}
+
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <stdio.h>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/public-api/images/pixel.h>
+#include <dali/internal/legacy/tizen/image-encoder.h>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Jpeg
+{
+const unsigned char MAGIC_BYTE_1 = 0xFF;
+const unsigned char MAGIC_BYTE_2 = 0xD8;
+} // namespace Jpeg
+
+/**
+ * Loads the bitmap from an JPEG file. This function checks the header first
+ * and if it is not a JPEG file, then it returns straight away.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a JPEG file and fills in the width and height appropriately.
+ * If the width and height are set on entry, it will set the width and height
+ * to the closest scaled size (exactly as will be loaded by LoadBitmapFromJpeg with the same
+ * attributes)
+ * @param[in] fp Pointer to the Image file
+ * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
+ * @param[in/out] width Is set with the width of the image
+ * @param[in/out] height Is set with the height of the image
+ * @return true if the file's header was read successully, false otherwise
+ */
+bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+/**
+ * Encode raw pixel data to JPEG format.
+ * @param[in] pixelBuffer Pointer to raw pixel data to be encoded
+ * @param[out] encodedPixels Encoded pixel data. Existing contents will be overwritten
+ * @param[in] width Image width
+ * @param[in] height Image height
+ * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888)
+ * @param[in] quality JPEG quality on usual 1 to 100 scale.
+ */
+bool EncodeToJpeg(const unsigned char* pixelBuffer, Vector< unsigned char >& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat, unsigned quality = 80);
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/loader-ktx.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+#include <dali/public-api/common/compile-time-assert.h>
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+
+/** Max width or height of an image. */
+const unsigned MAX_TEXTURE_DIMENSION = 4096;
+/** Max bytes of image data allowed. Not a precise number, just a sanity check. */
+const unsigned MAX_IMAGE_DATA_SIZE = MAX_TEXTURE_DIMENSION * MAX_TEXTURE_DIMENSION;
+/** We don't read any of this but limit it to a resonable amount in order to be
+ * friendly to files from random tools. */
+const unsigned MAX_BYTES_OF_KEYVALUE_DATA = 65536U;
+
+typedef uint8_t Byte;
+
+const Byte FileIdentifier[] = {
+ 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
+};
+
+
+/** The formats we support inside a KTX file container.
+ * Currently only compressed formats are allowed as we'd rather
+ * use a PNG or JPEG with their own compression for the general
+ * cases. */
+enum KtxInternalFormat
+{
+ KTX_NOTEXIST = 0,
+
+ // GLES 2 Extension formats:
+ KTX_ETC1_RGB8_OES = 0x8D64,
+ KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00,
+
+ // GLES 3 Standard compressed formats (values same as in gl3.h):
+ KTX_COMPRESSED_R11_EAC = 0x9270,
+ KTX_COMPRESSED_SIGNED_R11_EAC = 0x9271,
+ KTX_COMPRESSED_RG11_EAC = 0x9272,
+ KTX_COMPRESSED_SIGNED_RG11_EAC = 0x9273,
+ KTX_COMPRESSED_RGB8_ETC2 = 0x9274,
+ KTX_COMPRESSED_SRGB8_ETC2 = 0x9275,
+ KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
+ KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277,
+ KTX_COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
+
+ // GLES 3.1 compressed formats:
+ KTX_COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0,
+ KTX_COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1,
+ KTX_COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2,
+ KTX_COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3,
+ KTX_COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4,
+ KTX_COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5,
+ KTX_COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6,
+ KTX_COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7,
+ KTX_COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8,
+ KTX_COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9,
+ KTX_COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA,
+ KTX_COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB,
+ KTX_COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC,
+ KTX_COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD,
+
+ // Uncompressed Alpha format
+ KTX_UNCOMPRESSED_ALPHA8 = 0x1906,
+
+ KTX_SENTINEL = ~0u
+};
+
+const unsigned KtxInternalFormats[] =
+{
+ // GLES 2 Extension formats:
+ KTX_ETC1_RGB8_OES,
+ KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
+
+ // GLES 3 Standard compressed formats:
+ KTX_COMPRESSED_R11_EAC,
+ KTX_COMPRESSED_SIGNED_R11_EAC,
+ KTX_COMPRESSED_RG11_EAC,
+ KTX_COMPRESSED_SIGNED_RG11_EAC,
+ KTX_COMPRESSED_RGB8_ETC2,
+ KTX_COMPRESSED_SRGB8_ETC2,
+ KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
+ KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
+ KTX_COMPRESSED_RGBA8_ETC2_EAC,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,
+
+ // GLES 3.1 Compressed formats:
+ KTX_COMPRESSED_RGBA_ASTC_4x4_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_5x4_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_5x5_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_6x5_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_6x6_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_8x5_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_8x6_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_8x8_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_10x5_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_10x6_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_10x8_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_10x10_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_12x10_KHR,
+ KTX_COMPRESSED_RGBA_ASTC_12x12_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,
+ KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR,
+
+ // Uncompressed Alpha format
+ KTX_UNCOMPRESSED_ALPHA8,
+
+ KTX_SENTINEL
+};
+
+struct KtxFileHeader
+{
+ Byte identifier[12];
+ uint32_t endianness;
+ uint32_t glType;
+ uint32_t glTypeSize;
+ uint32_t glFormat;
+ uint32_t glInternalFormat;
+ uint32_t glBaseInternalFormat;
+ uint32_t pixelWidth;
+ uint32_t pixelHeight;
+ uint32_t pixelDepth;
+ uint32_t numberOfArrayElements;
+ uint32_t numberOfFaces;
+ uint32_t numberOfMipmapLevels;
+ uint32_t bytesOfKeyValueData;
+} __attribute__ ( (__packed__));
+// Packed attribute stops the structure from being aligned to compiler defaults
+// so we can be sure of reading the whole thing from file in one call to fread.
+
+/**
+ * Function to read from the file directly into our structure.
+ * @param[in] fp The file to read from
+ * @param[out] header The structure we want to store our information in
+ * @return true, if read successful, false otherwise
+ */
+inline bool ReadHeader( FILE* filePointer, KtxFileHeader& header )
+{
+ const unsigned int readLength = sizeof( KtxFileHeader );
+
+ // Load the information directly into our structure
+ if( fread( &header, 1, readLength, filePointer ) != readLength )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+/** Check whether the array passed in is the right size and matches the magic
+ * values defined to be at the start of a KTX file by the specification.*/
+template<int BYTES_IN_SIGNATURE>
+bool CheckFileIdentifier(const Byte * const signature)
+{
+ const unsigned signatureSize = BYTES_IN_SIGNATURE;
+ const unsigned identifierSize = sizeof(FileIdentifier);
+ DALI_COMPILE_TIME_ASSERT(signatureSize == identifierSize);
+ const bool signatureGood = 0 == memcmp( signature, FileIdentifier, std::min( signatureSize, identifierSize ) );
+ return signatureGood;
+}
+
+/**
+ * @returns True if the argument is a GLES compressed texture format that we support.
+ */
+bool ValidInternalFormat(const unsigned format)
+{
+ unsigned candidateFormat = 0;
+ for(unsigned iFormat = 0; (candidateFormat = KtxInternalFormats[iFormat]) != KTX_SENTINEL; ++iFormat)
+ {
+ if(format == candidateFormat)
+ {
+ return true;
+ }
+ }
+ DALI_LOG_ERROR("Rejecting unsupported compressed format when loading compressed texture from KTX file: 0x%x.\n", format);
+ return false;
+}
+
+/**
+ * @returns The Pixel::Format Dali enum corresponding to the KTX internal format
+ * passed in, or Pixel::INVALID_PIXEL_FORMAT if the format is not valid.
+ **/
+bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
+{
+ using namespace Dali::Pixel;
+ switch(ktxPixelFormat)
+ {
+ // GLES 2 extension compressed formats:
+ case KTX_ETC1_RGB8_OES:
+ {
+ format = COMPRESSED_RGB8_ETC1;
+ break;
+ }
+ case KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
+ {
+ format = COMPRESSED_RGB_PVRTC_4BPPV1;
+ break;
+ }
+
+ // GLES 3 extension compressed formats:
+ case KTX_COMPRESSED_R11_EAC:
+ {
+ format = COMPRESSED_R11_EAC;
+ break;
+ }
+ case KTX_COMPRESSED_SIGNED_R11_EAC:
+ {
+ format = COMPRESSED_SIGNED_R11_EAC;
+ break;
+ }
+ case KTX_COMPRESSED_RG11_EAC:
+ {
+ format = COMPRESSED_RG11_EAC;
+ break;
+ }
+ case KTX_COMPRESSED_SIGNED_RG11_EAC:
+ {
+ format = COMPRESSED_SIGNED_RG11_EAC;
+ break;
+ }
+ case KTX_COMPRESSED_RGB8_ETC2:
+ {
+ format = COMPRESSED_RGB8_ETC2;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ETC2:
+ {
+ format = COMPRESSED_SRGB8_ETC2;
+ break;
+ }
+ case KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
+ {
+ format = COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
+ {
+ format = COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA8_ETC2_EAC:
+ {
+ format = COMPRESSED_RGBA8_ETC2_EAC;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
+ break;
+ }
+
+ // GLES 3.1 extension compressed formats:
+ case KTX_COMPRESSED_RGBA_ASTC_4x4_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_4x4_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_5x4_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_5x4_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_5x5_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_5x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_6x5_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_6x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_6x6_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_6x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_8x5_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_8x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_8x6_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_8x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_8x8_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_8x8_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_10x5_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_10x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_10x6_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_10x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_10x8_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_10x8_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_10x10_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_10x10_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_12x10_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_12x10_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_RGBA_ASTC_12x12_KHR:
+ {
+ format = COMPRESSED_RGBA_ASTC_12x12_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
+ break;
+ }
+ case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
+ {
+ format = COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
+ break;
+ }
+
+ // Uncompressed Alpha format
+ case KTX_UNCOMPRESSED_ALPHA8:
+ {
+ format = A8;
+ break;
+ }
+
+ default:
+ {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool LoadKtxHeader( FILE * const fp, unsigned int& width, unsigned int& height, KtxFileHeader& fileHeader )
+{
+ // Pull the bytes of the file header in as a block:
+ if ( !ReadHeader( fp, fileHeader ) )
+ {
+ return false;
+ }
+ width = fileHeader.pixelWidth;
+ height = fileHeader.pixelHeight;
+
+ if ( width > MAX_TEXTURE_DIMENSION || height > MAX_TEXTURE_DIMENSION )
+ {
+ return false;
+ }
+
+ // Validate file header contents meet our minimal subset:
+ const bool signatureGood = CheckFileIdentifier<sizeof(fileHeader.identifier)>(fileHeader.identifier);
+ const bool fileEndiannessMatchesSystemEndianness = fileHeader.endianness == 0x04030201; // Magic number from KTX spec.
+ const bool glTypeIsCompressed = fileHeader.glType == 0;
+ const bool glTypeSizeCompatibleWithCompressedTex = fileHeader.glTypeSize == 1;
+ const bool glFormatCompatibleWithCompressedTex = fileHeader.glFormat == 0;
+ const bool glInternalFormatIsSupportedCompressedTex = ValidInternalFormat(fileHeader.glInternalFormat);
+ // Ignore glBaseInternalFormat
+ const bool textureIsNot3D = fileHeader.pixelDepth == 0 || fileHeader.pixelDepth == 1;
+ const bool textureIsNotAnArray = fileHeader.numberOfArrayElements == 0 || fileHeader.numberOfArrayElements == 1;
+ const bool textureIsNotACubemap = fileHeader.numberOfFaces == 0 || fileHeader.numberOfFaces == 1;
+ const bool textureHasNoMipmapLevels = fileHeader.numberOfMipmapLevels == 0 || fileHeader.numberOfMipmapLevels == 1;
+ const bool keyValueDataNotTooLarge = fileHeader.bytesOfKeyValueData <= MAX_BYTES_OF_KEYVALUE_DATA;
+
+ bool headerIsValid = signatureGood && fileEndiannessMatchesSystemEndianness &&
+ glTypeSizeCompatibleWithCompressedTex && textureIsNot3D && textureIsNotAnArray &&
+ textureIsNotACubemap && textureHasNoMipmapLevels && keyValueDataNotTooLarge;
+
+ if( !glTypeIsCompressed ) // check for uncompressed Alpha
+ {
+ const bool isAlpha = ( ( fileHeader.glBaseInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) && ( fileHeader.glFormat == KTX_UNCOMPRESSED_ALPHA8 ) &&
+ ( fileHeader.glInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) );
+ headerIsValid = headerIsValid && isAlpha;
+ }
+ else
+ {
+ headerIsValid = headerIsValid && glFormatCompatibleWithCompressedTex && glInternalFormatIsSupportedCompressedTex;
+ }
+
+ if( !headerIsValid )
+ {
+ DALI_LOG_ERROR( "KTX file invalid or using unsupported features. Header tests: sig: %d, endian: %d, gl_type: %d, gl_type_size: %d, gl_format: %d, internal_format: %d, depth: %d, array: %d, faces: %d, mipmap: %d, vey-vals: %d.\n", 0+signatureGood, 0+fileEndiannessMatchesSystemEndianness, 0+glTypeIsCompressed, 0+glTypeSizeCompatibleWithCompressedTex, 0+glFormatCompatibleWithCompressedTex, 0+glInternalFormatIsSupportedCompressedTex, 0+textureIsNot3D, 0+textureIsNotAnArray, 0+textureIsNotACubemap, 0+textureHasNoMipmapLevels, 0+keyValueDataNotTooLarge);
+ }
+
+ // Warn if there is space wasted in the file:
+ if( fileHeader.bytesOfKeyValueData > 0U )
+ {
+ DALI_LOG_WARNING("Loading of KTX file with key/value header data requested. This should be stripped in application asset/resource build.\n");
+ }
+
+ return headerIsValid;
+}
+
+
+} // unnamed namespace
+
+// File loading API entry-point:
+bool LoadKtxHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ KtxFileHeader fileHeader;
+ FILE* const fp = input.file;
+
+ bool ret = LoadKtxHeader(fp, width, height, fileHeader);
+ return ret;
+}
+
+// File loading API entry-point:
+bool LoadBitmapFromKtx( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ DALI_COMPILE_TIME_ASSERT( sizeof(Byte) == 1);
+ DALI_COMPILE_TIME_ASSERT( sizeof(uint32_t) == 4);
+
+ FILE* const fp = input.file;
+ if( fp == NULL )
+ {
+ DALI_LOG_ERROR( "Null file handle passed to KTX compressed bitmap file loader.\n" );
+ return false;
+ }
+ KtxFileHeader fileHeader;
+
+ // Load the header info
+ unsigned int width, height;
+
+ if (!LoadKtxHeader(fp, width, height, fileHeader))
+ {
+ return false;
+ }
+
+ // Skip the key-values:
+ const long int imageSizeOffset = sizeof(KtxFileHeader) + fileHeader.bytesOfKeyValueData;
+ if(fseek(fp, imageSizeOffset, SEEK_SET))
+ {
+ DALI_LOG_ERROR( "Seek past key/vals in KTX compressed bitmap file failed.\n" );
+ return false;
+ }
+
+ // Load the size of the image data:
+ uint32_t imageByteCount = 0;
+ if ( fread( &imageByteCount, 1, 4, fp ) != 4 )
+ {
+ DALI_LOG_ERROR( "Read of image size failed.\n" );
+ return false;
+ }
+ // Sanity-check the image size:
+ if( imageByteCount > MAX_IMAGE_DATA_SIZE ||
+ // A compressed texture should certainly be less than 2 bytes per texel:
+ imageByteCount > width * height * 2)
+ {
+ DALI_LOG_ERROR( "KTX file with too-large image-data field.\n" );
+ return false;
+ }
+
+ Pixel::Format pixelFormat;
+ const bool pixelFormatKnown = ConvertPixelFormat(fileHeader.glInternalFormat, pixelFormat);
+ if(!pixelFormatKnown)
+ {
+ DALI_LOG_ERROR( "No internal pixel format supported for KTX file pixel format.\n" );
+ return false;
+ }
+
+ // Load up the image bytes:
+ bitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
+
+ // Compressed format won't allocate the buffer
+ auto pixels = bitmap.GetBuffer();
+ if( !pixels )
+ {
+ // allocate buffer manually
+ auto &impl = GetImplementation(bitmap);
+ impl.AllocateFixedSize(imageByteCount);
+ pixels = bitmap.GetBuffer();
+ }
+
+ if(!pixels)
+ {
+ DALI_LOG_ERROR( "Unable to reserve a pixel buffer to load the requested bitmap into.\n" );
+ return false;
+ }
+
+ const size_t bytesRead = fread(pixels, 1, imageByteCount, fp);
+ if(bytesRead != imageByteCount)
+ {
+ DALI_LOG_ERROR( "Read of image pixel data failed.\n" );
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Ktx
+{
+const unsigned char MAGIC_BYTE_1 = 0xAB;
+const unsigned char MAGIC_BYTE_2 = 0x4B;
+} // namespace Ktx
+
+/**
+ * Loads a compressed bitmap from a KTX file without decoding it.
+ * This function checks the header first
+ * and if it is not a KTX file, then it returns straight away.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file loaded successfully, false otherwise
+ */
+bool LoadBitmapFromKtx( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a KTX file and fills in the width and height appropriately.
+ * @param[in] fp Pointer to the Image file
+ * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
+ * @param[out] width Is set with the width of the image
+ * @param[out] height Is set with the height of the image
+ * @return true if the file's header was read successully, false otherwise
+ */
+bool LoadKtxHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/imaging/common/loader-png.h>
+
+#include <cstring>
+
+#include <zlib.h>
+#include <png.h>
+
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/images/image.h>
+#include <dali/internal/legacy/tizen/platform-capabilities.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+namespace TizenPlatform
+{
+
+namespace
+{
+
+// simple class to enforce clean-up of PNG structures
+struct auto_png
+{
+ auto_png(png_structp& _png, png_infop& _info)
+ : png(_png),
+ info(_info)
+ {
+ }
+
+ ~auto_png()
+ {
+ if(NULL != png)
+ {
+ png_destroy_read_struct(&png, &info, NULL);
+ }
+ }
+
+ png_structp& png;
+ png_infop& info;
+}; // struct auto_png;
+
+bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
+{
+ png_byte header[8] = { 0 };
+
+ // Check header to see if it is a PNG file
+ size_t size = fread(header, 1, 8, fp);
+ if(size != 8)
+ {
+ return false;
+ }
+
+ if(png_sig_cmp(header, 0, 8))
+ {
+ return false;
+ }
+
+ png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+
+ if(!png)
+ {
+ DALI_LOG_WARNING("Can't create PNG read structure\n");
+ return false;
+ }
+
+ info = png_create_info_struct(png);
+ if(!info)
+ {
+ DALI_LOG_WARNING("png_create_info_struct failed\n");
+ return false;
+ }
+
+ png_set_expand(png);
+
+ if(setjmp(png_jmpbuf(png)))
+ {
+ DALI_LOG_WARNING("error during png_init_io\n");
+ return false;
+ }
+
+ png_init_io(png, fp);
+ png_set_sig_bytes(png, 8);
+
+ // read image info
+ png_read_info(png, info);
+
+ // dimensions
+ width = png_get_image_width(png, info);
+ height = png_get_image_height(png, info);
+
+ return true;
+}
+
+} // namespace - anonymous
+
+bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ png_structp png = NULL;
+ png_infop info = NULL;
+ auto_png autoPng(png, info);
+
+ bool success = LoadPngHeader( input.file, width, height, png, info );
+
+ return success;
+}
+
+bool LoadBitmapFromPng( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ png_structp png = NULL;
+ png_infop info = NULL;
+ auto_png autoPng(png, info);
+
+ /// @todo: consider parameters
+ unsigned int y;
+ unsigned int width, height;
+ png_bytep *rows;
+ unsigned int bpp = 0; // bytes per pixel
+ bool valid = false;
+
+ // Load info from the header
+ if( !LoadPngHeader( input.file, width, height, png, info ) )
+ {
+ return false;
+ }
+
+ Pixel::Format pixelFormat = Pixel::RGBA8888;
+
+ // decide pixel format
+ unsigned int colordepth = png_get_bit_depth(png, info);
+
+ // Ask PNGLib to convert high precision images into something we can use:
+ if (colordepth == 16)
+ {
+ png_set_strip_16(png);
+ colordepth = 8;
+ }
+
+ png_byte colortype = png_get_color_type(png, info);
+
+ if( colortype == PNG_COLOR_TYPE_GRAY ||
+ colortype == PNG_COLOR_TYPE_GRAY_ALPHA )
+ {
+ if( colortype == PNG_COLOR_TYPE_GRAY )
+ {
+ pixelFormat = Pixel::L8;
+ if( png_get_valid(png, info, PNG_INFO_tRNS) )
+ {
+ colortype = PNG_COLOR_TYPE_GRAY_ALPHA;
+ /* expand transparency entry -> alpha channel if present */
+ png_set_tRNS_to_alpha(png);
+ pixelFormat = Pixel::LA88;
+ }
+ }
+ else
+ {
+ pixelFormat = Pixel::LA88;
+ }
+
+ if( colordepth < 8 )
+ {
+ /* expand gray (w/reduced bits) -> 8-bit RGB if necessary */
+ png_set_expand_gray_1_2_4_to_8(png);
+ /* pack all pixels to byte boundaries */
+ png_set_packing(png);
+ }
+ valid = true;
+ }
+ else if(colortype == PNG_COLOR_TYPE_RGB )
+ {
+ switch(colordepth)
+ {
+ case 8:
+ {
+ pixelFormat = Pixel::RGB888;
+ valid = true;
+ break;
+ }
+ case 5: /// @todo is this correct for RGB16 5-6-5 ?
+ {
+ pixelFormat = Pixel::RGB565;
+ valid = true;
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+ else if(colortype == PNG_COLOR_TYPE_RGBA)
+ {
+ switch(colordepth)
+ {
+ case 8:
+ {
+ pixelFormat = Pixel::RGBA8888;
+ valid = true;
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+ else if(colortype == PNG_COLOR_TYPE_PALETTE)
+ {
+ switch(colordepth)
+ {
+ case 1:
+ {
+ pixelFormat = Pixel::LA88;
+ valid = true;
+ break;
+ }
+
+ case 2:
+ case 4:
+ case 8:
+ {
+ /* Expand paletted or RGB images with transparency to full alpha channels
+ * so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
+ */
+ if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
+ {
+ pixelFormat = Pixel::RGBA8888;
+ valid = true;
+ }
+ else
+ {
+ pixelFormat = Pixel::RGB888;
+ png_set_packing(png);
+ png_set_packswap(png);
+ png_set_palette_to_rgb(png);
+ valid = true;
+ }
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+ }
+
+ if( !valid )
+ {
+ DALI_LOG_WARNING( "Unsupported png format\n" );
+ return false;
+ }
+
+ // bytes per pixel
+ bpp = Pixel::GetBytesPerPixel(pixelFormat);
+
+ png_read_update_info(png, info);
+
+ if(setjmp(png_jmpbuf(png)))
+ {
+ DALI_LOG_WARNING("error during png_read_image\n");
+ return false;
+ }
+
+ unsigned int rowBytes = png_get_rowbytes(png, info);
+
+ unsigned int bufferWidth = GetTextureDimension(width);
+ unsigned int bufferHeight = GetTextureDimension(height);
+ unsigned int stride = bufferWidth*bpp;
+
+ // not sure if this ever happens
+ if( rowBytes > stride )
+ {
+ stride = GetTextureDimension(rowBytes);
+
+ bpp = stride / bufferWidth;
+ switch(bpp)
+ {
+ case 3:
+ pixelFormat = Pixel::RGB888;
+ break;
+ case 4:
+ pixelFormat = Pixel::RGBA8888;
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ // decode the whole image into bitmap buffer
+ auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat)).GetBuffer();
+
+ DALI_ASSERT_DEBUG(pixels);
+ rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
+ for(y=0; y<height; y++)
+ {
+ rows[y] = pixels + y * stride;
+ }
+
+ // decode image
+ png_read_image(png, rows);
+
+ free(rows);
+
+ return true;
+}
+
+// simple class to enforce clean-up of PNG structures
+struct AutoPngWrite
+{
+ AutoPngWrite(png_structp& _png, png_infop& _info)
+ : png(_png),
+ info(_info)
+ {
+ }
+
+ ~AutoPngWrite()
+ {
+ if(NULL != png)
+ {
+ png_destroy_write_struct(&png, &info);
+ }
+ }
+
+ png_structp& png;
+ png_infop& info;
+}; // struct AutoPngWrite;
+
+namespace
+{
+ // Custom libpng write callbacks that buffer to a vector instead of a file:
+
+ /**
+ * extern "C" linkage is used because this is a callback that we pass to a C
+ * library which is part of the underlying platform and so potentially compiled
+ * as C rather than C++.
+ * @see http://stackoverflow.com/a/2594222
+ * */
+ extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
+ {
+ DALI_ASSERT_DEBUG(png_ptr && data);
+ if(!png_ptr || !data)
+ {
+ return;
+ }
+ // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
+ try
+ {
+ // Recover our buffer for writing into:
+ Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
+ if(encoded_img)
+ {
+ const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
+ encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
+ unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
+ memcpy(bufferBack, data, length);
+ }
+ else
+ {
+ DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
+ }
+ }
+ catch(...)
+ {
+ DALI_LOG_ERROR("C++ Exception caught\n");
+ }
+ }
+
+ /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
+ extern "C" void FlushData(png_structp png_ptr)
+ {
+#ifdef DEBUG_ENABLED
+ Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
+#endif // DEBUG_ENABLED
+ }
+}
+
+/**
+ * Potential improvements:
+ * 1. Detect <= 256 colours and write in palette mode.
+ * 2. Detect grayscale (will early-out quickly for colour images).
+ * 3. Store colour space / gamma correction info related to the device screen?
+ * http://www.libpng.org/pub/png/book/chapter10.html
+ * 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
+ * 5. Prealloc buffer (reserve) to input size / <A number greater than 2 (expexcted few realloc but without using lots of memory) | 1 (expected zero reallocs but using a lot of memory)>.
+ * 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
+ * 7. If caller asks for no compression, bypass libpng and blat raw data to
+ * disk, topped and tailed with header/tail blocks.
+ */
+bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
+{
+ // Translate pixel format enum:
+ int pngPixelFormat = -1;
+ unsigned pixelBytes = 0;
+ bool rgbaOrder = true;
+
+ // Account for RGB versus BGR and presence of alpha in input pixels:
+ switch( pixelFormat )
+ {
+ case Pixel::RGB888:
+ {
+ pngPixelFormat = PNG_COLOR_TYPE_RGB;
+ pixelBytes = 3;
+ break;
+ }
+ case Pixel::BGRA8888:
+ {
+ rgbaOrder = false;
+ ///! No break: fall through:
+ }
+ case Pixel::RGBA8888:
+ {
+ pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
+ pixelBytes = 4;
+ break;
+ }
+ default:
+ {
+ DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
+ return false;
+ }
+ }
+
+ const int interlace = PNG_INTERLACE_NONE;
+
+ png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+ if(!png_ptr)
+ {
+ return false;
+ }
+ /* Allocate/initialize the image information data. REQUIRED */
+ png_infop info_ptr = png_create_info_struct( png_ptr );
+ if(!info_ptr)
+ {
+ png_destroy_write_struct(&png_ptr, NULL);
+ return false;
+ }
+
+ /* Set error handling. REQUIRED if you aren't supplying your own
+ * error handling functions in the png_create_write_struct() call.
+ */
+ if(setjmp(png_jmpbuf(png_ptr)))
+ {
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ return false;
+ }
+
+ // Since we are going to write to memory instead of a file, lets provide
+ // libpng with a custom write function and ask it to pass back our
+ // Vector buffer each time it calls back to flush data to "file":
+ png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
+
+ // png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
+ png_set_compression_level(png_ptr, Z_BEST_SPEED);
+ // png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
+
+ // Explicitly limit the number of filters used per scanline to speed us up:
+ // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
+ // PNG_FILTER_SUB |
+ // PNG_FILTER_UP |
+ // PNG_FILTER_AVE |
+ // PNG_FILTER_PAETH |
+ // PNG_ALL_FILTERS);
+ // Play with Zlib parameters in optimisation phase:
+ // png_set_compression_mem_level(png_ptr, 8);
+ // png_set_compression_strategy(png_ptr,
+ // Z_DEFAULT_STRATEGY);
+ // png_set_compression_window_bits(png_ptr, 15);
+ // png_set_compression_method(png_ptr, 8);
+ // png_set_compression_buffer_size(png_ptr, 8192)
+
+ // Let lib_png know if the pixel bytes are in BGR(A) order:
+ if(!rgbaOrder)
+ {
+ png_set_bgr( png_ptr );
+ }
+
+ // Set the image information:
+ png_set_IHDR(png_ptr, info_ptr, width, height, 8,
+ pngPixelFormat, interlace,
+ PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+
+ // Start to output the PNG data to our buffer:
+ png_write_info(png_ptr, info_ptr);
+
+ // Walk the rows:
+ const unsigned row_step = width * pixelBytes;
+ png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
+ const png_bytep row_end = row_ptr + height * row_step;
+ for(; row_ptr < row_end; row_ptr += row_step)
+ {
+ png_write_row(png_ptr, row_ptr);
+ }
+
+ /* It is REQUIRED to call this to finish writing the rest of the file */
+ png_write_end(png_ptr, info_ptr);
+ /* Clean up after the write, and free any memory allocated */
+ png_destroy_write_struct(&png_ptr, &info_ptr);
+ return true;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/public-api/images/pixel.h>
+#include <dali/internal/legacy/tizen/image-encoder.h>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+namespace Devel
+{
+class PixelBuffer;
+}
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+namespace Png
+{
+const unsigned char MAGIC_BYTE_1 = 0x89;
+const unsigned char MAGIC_BYTE_2 = 0x50;
+} // namespace Png
+
+/**
+ * Loads the bitmap from an PNG file. This function checks the header first
+ * and if it is not a PNG file, then it returns straight away.
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromPng( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * Loads the header of a PNG file and fills in the width and height appropriately.
+ * @param[in] fp Pointer to the Image file
+ * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
+ * @param[out] width Is set with the width of the image
+ * @param[out] height Is set with the height of the image
+ * @return true if the file's header was read successully, false otherwise
+ */
+bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+/**
+ * Encode raw pixel data to PNG format.
+ * @param[in] pixelBuffer Pointer to raw pixel data to be encoded
+ * @param[out] encodedPixels Encoded pixel data. Existing contents will be overwritten
+ * @param[in] width Image width
+ * @param[in] height Image height
+ * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888)
+ */
+bool EncodeToPng( const unsigned char* pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat );
+
+} // namespace TizenPlatform
+
+} // namespace Dali
+
+#endif // __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// HEADER
+#include <dali/internal/imaging/common/loader-wbmp.h>
+
+// EXTERNAL INCLUDES
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_LOADER_WBMP");
+#endif
+
+#define IMG_MAX_SIZE 65536
+
+#define IMG_TOO_BIG(w, h) \
+ ((((unsigned long long)w) * ((unsigned long long)h)) >= \
+ ((1ULL << (29)) - 2048))
+
+
+//extract multiple bytes integer , and saved in *data
+int extractMultiByteInteger(unsigned int *data, void *map, size_t length, size_t *position)
+{
+ // the header field contains an image type indentifier of multi-byte length(TypeField), an octet of general header info(FixHeaderField)
+ //, a multi-byte width field(Width) and a multi-byte height field(Height) and so on.
+ // The actual organisation of the image data depends on the image type
+ // for Ext Headers flag (7th bit), 1 = More will follow, 0 = Last octet
+ // so in the for loop, if(buf & 0x80 == 0), loop will be exited
+ int targetMultiByteInteger = 0, readBufCount;
+ unsigned char buf;
+
+ for (readBufCount = 0;;)
+ {
+ // readBufCount means the count that fetched data from map
+ // extractMultiByteInteger() is to fetch wbmp type , width, and height
+ // for wbmp type, when readBufCount == 1, buf = 0x00, it will exit the loop
+ // for width, it have 4 bytes, so when readBufCount == 4, it must exit the loop
+ // for general width and height, if(buf & 0x80) == 0, then the next byte does not need to fetch again
+ // first step, readBufCount = 1 , read int(4 bytes) to buf, if buf & 0x80 !=0, the buf need to continue to fetch
+ // second step, readBufCount = 2, read next( 4 bytes) to buf, if buf & 0x80 == 0, then assigned the buf to target
+ if ((readBufCount ++) == 4)
+ {
+ return -1;
+ }
+ if (*position > length)
+ {
+ return -1;
+ }
+ buf = reinterpret_cast< unsigned char * >( map )[(*position)++];
+ targetMultiByteInteger = (targetMultiByteInteger << 7) | (buf & 0x7f);
+
+ if ((buf & 0x80) == 0)
+ {
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "position: %d, readBufCount: %d\n", *position, readBufCount);
+ break;
+ }
+ }
+ *data = targetMultiByteInteger;
+ return 0;
+}
+
+}// end unnamed namespace
+
+bool LoadBitmapFromWbmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
+{
+ FILE* const fp = input.file;
+ if(fp == NULL)
+ {
+ DALI_LOG_ERROR("Error loading bitmap\n");
+ return false;
+ }
+ Dali::Vector<unsigned char> map;
+ Dali::Vector<unsigned char> surface;//unsigned int
+ size_t position = 0;
+
+ unsigned int w, h;
+ unsigned int type;
+ unsigned int line_length;
+ unsigned char *line = NULL;
+ unsigned int cur = 0, x, y;
+
+ if( fseek(fp,0,SEEK_END) )
+ {
+ DALI_LOG_ERROR("Error seeking WBMP data\n");
+ return false;
+ }
+ long positionIndicator = ftell(fp);
+
+ unsigned int fsize( 0u );
+ if( positionIndicator > -1L )
+ {
+ fsize = static_cast<unsigned int>(positionIndicator);
+ }
+
+ if( 0u == fsize )
+ {
+ DALI_LOG_ERROR("Error: filesize is 0!\n");
+ return false;
+ }
+
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking WBMP data\n");
+ return false;
+ }
+ if(fsize <= 4)
+ {
+ DALI_LOG_ERROR("Error: WBMP Raw Data Not Found!\n");
+ return false;
+ }
+ if(fsize > 4096 * 4096 * 4)
+ {
+ DALI_LOG_ERROR("Error: WBMP size is too large!\n");
+ return false;
+ }
+ map.Resize(fsize);
+
+ if(fread(&map[0], 1, fsize, fp) != fsize)
+ {
+ DALI_LOG_WARNING("image file read opeation error!\n");
+ return false;
+ }
+
+ if (extractMultiByteInteger(&type, &map[0], fsize, &position) < 0)
+ {
+ return false;
+ }
+
+ position++; /* skipping one byte */
+
+ if (extractMultiByteInteger(&w, &map[0], fsize, &position) < 0)
+ {
+ return false;
+ }
+ if (extractMultiByteInteger(&h, &map[0], fsize, &position) < 0)
+ {
+ return false;
+ }
+ if(type != 0)
+ {
+ DALI_LOG_ERROR("Unknown Format!\n");
+ return false;
+ }
+
+ if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE))
+ {
+ return false;
+ }
+
+ surface.Resize(w* h );//(w * h * 4);
+ memset(&surface[0], 0, w * h ); // w * h * 4
+
+ line_length = (w + 7) >> 3;
+ for (y = 0; y < h; y ++)
+ {
+ if (position + line_length > fsize)
+ {
+ return false;
+ }
+ line = &map[0] + position;
+ position += line_length;
+ for (x = 0; x < w; x++)
+ {
+ int idx = x >> 3;
+ int offset = 1 << (0x07 - (x & 0x07));
+ if (line[idx] & offset)
+ {
+ surface[cur] = 0xff;//0xffffffff;
+ }
+ else
+ {
+ surface[cur] = 0x00;//0xff000000;
+ }
+ cur++;
+ }
+ }
+ auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::L8)).GetBuffer();
+
+ memcpy( pixels, &surface[0], w * h ); //w * h * 4
+
+ return true;
+}
+
+
+bool LoadWbmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
+{
+ FILE* const fp = input.file;
+ if(fp == NULL)
+ {
+ DALI_LOG_ERROR("Error loading bitmap\n");
+ return false;
+ }
+ Dali::Vector<unsigned char> map;
+ size_t position = 0;
+
+ unsigned int w, h;
+ unsigned int type;
+ if( fseek(fp,0,SEEK_END) )
+ {
+ DALI_LOG_ERROR("Error seeking WBMP data\n");
+ return false;
+ }
+ long positionIndicator = ftell(fp);
+
+ unsigned int fsize( 0u );
+ if( positionIndicator > -1L )
+ {
+ fsize = static_cast<unsigned int>(positionIndicator);
+ }
+
+ if( 0u == fsize )
+ {
+ return false;
+ }
+
+ if( fseek(fp, 0, SEEK_SET) )
+ {
+ DALI_LOG_ERROR("Error seeking WBMP data\n");
+ return false;
+ }
+ if(fsize <= 4)
+ {
+ DALI_LOG_ERROR("Error: WBMP Raw Data Not Found!\n");
+ return false;
+ }
+
+ // type(1 byte) + fixedheader(1 byte) + width(uint) + height(uint)
+ unsigned int headerSize = 1 + 1 + 4 + 4;// 8 + 8 + 32 + 32;
+ headerSize = std::min(headerSize, fsize);
+
+ map.Resize(headerSize);
+ if(fread(&map[0], 1, headerSize, fp) != headerSize)
+ {
+ DALI_LOG_WARNING("image file read opeation error!\n");
+ return false;
+ }
+
+ if (extractMultiByteInteger(&type, &map[0], headerSize, &position) < 0)
+ {
+ DALI_LOG_ERROR("Error: unable to read type!\n");
+ return false;
+ }
+ position++; /* skipping one byte */
+ if(type != 0)
+ {
+ DALI_LOG_ERROR("Error: unknown format!\n");
+ return false;
+ }
+ if (extractMultiByteInteger(&w, &map[0], headerSize, &position) < 0)
+ {
+ DALI_LOG_ERROR("Error: can not read width!\n");
+ return false;
+ }
+ if (extractMultiByteInteger(&h, &map[0], headerSize, &position) < 0)
+ {
+ DALI_LOG_ERROR("Error: can not read height!\n");
+ return false;
+ }
+
+ if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE) )
+ {
+ DALI_LOG_ERROR("Error: file size is not supported!\n");
+ return false;
+ }
+
+ width = w;
+ height = h;
+ return true;
+}
+
+}
+}
--- /dev/null
+#ifndef __DALI_TIZEN_PLATFORM_LOADER_WBMP_H__
+#define __DALI_TIZEN_PLATFORM_LOADER_WBMP_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cstdio>
+#include <dali/internal/imaging/common/image-loader-input.h>
+
+namespace Dali
+{
+
+namespace Devel
+{
+class PixelBuffer;
+}
+
+namespace TizenPlatform
+{
+
+class ResourceLoadingClient;
+
+/**
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] bitmap The bitmap class where the decoded image will be stored
+ * @return true if file decoded successfully, false otherwise
+ */
+bool LoadBitmapFromWbmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
+
+/**
+ * @param[in] input Information about the input image (including file pointer)
+ * @param[out] width of image
+ * @param[out] height of image
+ * @return true if header loaded successfully, false otherwise
+ */
+bool LoadWbmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
+
+}
+
+}
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/native-bitmap-buffer-impl.h>
+
+// EXTERNAL HEADERS
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/bitmap.h>
+
+// INTERNAL HEADERS
+#include <dali/internal/graphics/gles20/gl-implementation.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+NativeBitmapBuffer::NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pFormat )
+: mWidth(width),
+ mHeight(height),
+ mPixelFormat(pFormat),
+ mLastReadBuffer(NULL)
+{
+ DALI_ASSERT_ALWAYS( adaptor );
+ mBuffer = new Integration::LocklessBuffer( width * height * Pixel::GetBytesPerPixel(pFormat) );
+ mGlAbstraction = &(adaptor->GetGlAbstraction());
+}
+
+NativeBitmapBuffer::~NativeBitmapBuffer()
+{
+ delete mBuffer;
+}
+
+void NativeBitmapBuffer::PrepareTexture()
+{
+ DALI_ASSERT_ALWAYS( mBuffer );
+ GLenum pixelFormat = GL_RGBA;
+ GLenum pixelDataType = GL_UNSIGNED_BYTE;
+
+ Integration::ConvertToGlFormat( mPixelFormat, pixelDataType, pixelFormat );
+
+ const unsigned char* buf = mBuffer->Read();
+
+ if( buf && buf != mLastReadBuffer ) // Prevent same buffer being uploaded multiple times
+ {
+ mLastReadBuffer = buf;
+
+ // The active texture has already been set to a sampler and bound.
+ mGlAbstraction->TexImage2D( GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, buf );
+ }
+}
+
+void NativeBitmapBuffer::Write( const unsigned char *src, size_t size )
+{
+ mBuffer->Write( src, size ); // Write will cause LocklessBuffer to switch to the other buffer
+}
+
+bool NativeBitmapBuffer::GlExtensionCreate()
+{
+ return true;
+}
+
+void NativeBitmapBuffer::GlExtensionDestroy()
+{
+}
+
+unsigned int NativeBitmapBuffer::TargetTexture()
+{
+ return 0;
+}
+
+unsigned int NativeBitmapBuffer::GetWidth() const
+{
+ return mWidth;
+}
+
+unsigned int NativeBitmapBuffer::GetHeight() const
+{
+ return mHeight;
+}
+
+bool NativeBitmapBuffer::RequiresBlending() const
+{
+ return Pixel::HasAlpha( mPixelFormat );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_NATIVE_BITMAP_BUFFER_H__
+#define __DALI_NATIVE_BITMAP_BUFFER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL HEADERS
+#include <dali/public-api/images/native-image-interface.h>
+#include <dali/public-api/images/pixel.h>
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/lockless-buffer.h>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL HEADERS
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class NativeBitmapBuffer;
+typedef IntrusivePtr<NativeBitmapBuffer> NativeBitmapBufferPtr;
+
+/**
+ * A Bitmap-based implementation of the NativeImage interface.
+ */
+class NativeBitmapBuffer : public NativeImageInterface
+{
+
+public:
+ /**
+ * Constructor.
+ * @param adaptor Adaptor used
+ * @param width width of image
+ * @param height height of image
+ * @param pixelFormat pixel format for image
+ */
+ NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat );
+
+ /**
+ * virtual destructor
+ */
+ virtual ~NativeBitmapBuffer();
+
+ /**
+ * Write to buffer. Does not block.
+ * @param[in] src data source
+ * @param[in] size size of data in bytes
+ * @return true if successful, false if currently reading from buffer in render thread
+ */
+ void Write( const unsigned char* src, size_t size );
+
+public:
+ /**
+ * @copydoc Dali::NativeImageInterface::GlExtensionCreate()
+ */
+ virtual bool GlExtensionCreate();
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GlExtensionDestroy()
+ */
+ virtual void GlExtensionDestroy();
+
+ /**
+ * @copydoc Dali::NativeImageInterface::TargetTexture()
+ */
+ virtual unsigned int TargetTexture();
+
+ /**
+ * @copydoc Dali::NativeImageInterface::PrepareTexture()
+ */
+ virtual void PrepareTexture();
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetWidth()
+ */
+ virtual unsigned int GetWidth() const;
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetHeight()
+ */
+ virtual unsigned int GetHeight() const;
+
+ /**
+ * @copydoc Dali::NativeImageInterface::RequiresBlending()
+ */
+ virtual bool RequiresBlending() const;
+
+private:
+ NativeBitmapBuffer( const NativeBitmapBuffer& ); ///< not defined
+ NativeBitmapBuffer& operator =( const NativeBitmapBuffer& ); ///< not defined
+ NativeBitmapBuffer(); ///< not defined
+
+private:
+ Integration::GlAbstraction* mGlAbstraction; ///< GlAbstraction used
+
+ Integration::LocklessBuffer* mBuffer; ///< bitmap data double buffered
+ unsigned int mWidth; ///< Image width
+ unsigned int mHeight; ///< Image height
+ Pixel::Format mPixelFormat; ///< Image pixelformat
+ const unsigned char* mLastReadBuffer; ///< last buffer that was read
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_NATIVE_BITMAP_BUFFER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/internal/imaging/common/native-image-source-impl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+namespace NativeImageSourceFactory
+{
+
+/**
+ * Dummy implementation
+ * @param width
+ * @param height
+ * @param depth
+ * @param nativeImageSource
+ * @return
+ */
+__attribute__((weak))
+std::unique_ptr<Dali::Internal::Adaptor::NativeImageSource> New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource)
+{
+ return std::unique_ptr<NativeImageSource>(nullptr);
+}
+
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+#ifndef TIZEN_ORG_NATIVE_IMAGE_SOURCE_FACTORY_H
+#define TIZEN_ORG_NATIVE_IMAGE_SOURCE_FACTORY_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+class NativeImageSource;
+namespace NativeImageSourceFactory
+{
+
+__attribute__((weak))
+std::unique_ptr<Internal::Adaptor::NativeImageSource> New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#endif //TIZEN_ORG_NATIVE_IMAGE_SOURCE_FACTORY_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/native-image-source-impl.h>
+#include <dali/internal/imaging/common/native-image-source-factory.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+NativeImageSource::~NativeImageSource() = default;
+
+NativeImageSource* NativeImageSource::New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource)
+{
+ return Internal::Adaptor::NativeImageSourceFactory::New( width, height, depth, nativeImageSource ).release();
+}
+
+
+Any NativeImageSource::GetNativeImageSource() const
+{
+ return nullptr;
+}
+
+
+bool NativeImageSource::GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const
+{
+ return false;
+}
+
+bool NativeImageSource::EncodeToFile(const std::string& filename) const
+{
+ return false;
+}
+
+void NativeImageSource::SetSource( Any source )
+{
+
+}
+
+bool NativeImageSource::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
+{
+ return false;
+}
+
+bool NativeImageSource::GlExtensionCreate()
+{
+ return false;
+}
+
+void NativeImageSource::GlExtensionDestroy()
+{
+
+}
+
+unsigned int NativeImageSource::TargetTexture()
+{
+ return 0u;
+}
+
+void NativeImageSource::PrepareTexture()
+{
+
+}
+
+unsigned int NativeImageSource::GetWidth() const
+{
+ return 0u;
+}
+
+unsigned int NativeImageSource::GetHeight() const
+{
+ return 0u;
+}
+
+bool NativeImageSource::RequiresBlending() const
+{
+ return false;
+}
+
+
+NativeImageInterface::Extension* NativeImageSource::GetNativeImageInterfaceExtension()
+{
+ return nullptr;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
--- /dev/null
+#ifndef DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_H
+#define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Dali internal NativeImageSource.
+ */
+class NativeImageSource
+{
+public:
+
+ /**
+ * Create a new NativeImageSource internally.
+ * Depending on hardware the width and height may have to be a power of two.
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] depth color depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return A smart-pointer to a newly allocated image.
+ */
+ static NativeImageSource* New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+ /**
+ * @copydoc Dali::NativeImageSource::GetNativeImageSource()
+ */
+ virtual Any GetNativeImageSource() const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetPixels()
+ */
+ virtual bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
+ */
+ virtual bool EncodeToFile(const std::string& filename) const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::SetSource( Any source )
+ */
+ virtual void SetSource( Any source );
+
+ /**
+ * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
+ */
+ virtual bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth );
+
+ /**
+ * destructor
+ */
+ virtual ~NativeImageSource();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionCreate()
+ */
+ virtual bool GlExtensionCreate();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
+ */
+ virtual void GlExtensionDestroy();
+
+ /**
+ * @copydoc Dali::NativeImageSource::TargetTexture()
+ */
+ virtual unsigned int TargetTexture();
+
+ /**
+ * @copydoc Dali::NativeImageSource::PrepareTexture()
+ */
+ virtual void PrepareTexture();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetWidth()
+ */
+ virtual unsigned int GetWidth() const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetHeight()
+ */
+ virtual unsigned int GetHeight() const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::RequiresBlending()
+ */
+ virtual bool RequiresBlending() const;
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetExtension()
+ */
+ virtual NativeImageInterface::Extension* GetNativeImageInterfaceExtension();
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_H
--- /dev/null
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+// EXTERNAL INCLUDES
+#include <stdlib.h>
+#include <cstring>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/pixel-manipulation.h>
+#include <dali/internal/imaging/common/alpha-mask.h>
+#include <dali/internal/imaging/common/gaussian-blur.h>
+#include <dali/internal/imaging/common/image-operations.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+PixelBuffer::PixelBuffer( unsigned char* buffer,
+ unsigned int bufferSize,
+ unsigned int width,
+ unsigned int height,
+ Dali::Pixel::Format pixelFormat )
+: mMetadata(),
+ mBuffer( buffer ),
+ mBufferSize( bufferSize ),
+ mWidth( width ),
+ mHeight( height ),
+ mPixelFormat( pixelFormat )
+{
+}
+
+PixelBuffer::~PixelBuffer()
+{
+ ReleaseBuffer();
+}
+
+PixelBufferPtr PixelBuffer::New( unsigned int width,
+ unsigned int height,
+ Dali::Pixel::Format pixelFormat )
+{
+ unsigned int bufferSize = width * height * Dali::Pixel::GetBytesPerPixel( pixelFormat );
+ unsigned char* buffer = NULL;
+ if( bufferSize > 0 )
+ {
+ buffer = static_cast<unsigned char*>( malloc ( bufferSize ) );
+ }
+ return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
+}
+
+PixelBufferPtr PixelBuffer::New( unsigned char* buffer,
+ unsigned int bufferSize,
+ unsigned int width,
+ unsigned int height,
+ Dali::Pixel::Format pixelFormat )
+{
+ return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat );
+}
+
+Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer )
+{
+ Dali::PixelData pixelData = Dali::PixelData::New( pixelBuffer.mBuffer,
+ pixelBuffer.mBufferSize,
+ pixelBuffer.mWidth,
+ pixelBuffer.mHeight,
+ pixelBuffer.mPixelFormat,
+ Dali::PixelData::FREE );
+ pixelBuffer.mBuffer = NULL;
+ pixelBuffer.mWidth = 0;
+ pixelBuffer.mHeight = 0;
+ pixelBuffer.mBufferSize = 0;
+
+ return pixelData;
+}
+
+unsigned int PixelBuffer::GetWidth() const
+{
+ return mWidth;
+}
+
+unsigned int PixelBuffer::GetHeight() const
+{
+ return mHeight;
+}
+
+Dali::Pixel::Format PixelBuffer::GetPixelFormat() const
+{
+ return mPixelFormat;
+}
+
+unsigned char* PixelBuffer::GetBuffer() const
+{
+ return mBuffer;
+}
+
+unsigned int PixelBuffer::GetBufferSize() const
+{
+ return mBufferSize;
+}
+
+Dali::PixelData PixelBuffer::CreatePixelData() const
+{
+ unsigned char* destBuffer = NULL;
+
+ if( mBufferSize > 0 )
+ {
+ destBuffer = static_cast<unsigned char*>( malloc( mBufferSize ) );
+ memcpy( destBuffer, mBuffer, mBufferSize );
+ }
+
+ Dali::PixelData pixelData = Dali::PixelData::New( destBuffer, mBufferSize,
+ mWidth, mHeight,
+ mPixelFormat,
+ Dali::PixelData::FREE );
+ return pixelData;
+}
+
+void PixelBuffer::ApplyMask( const PixelBuffer& inMask, float contentScale, bool cropToMask )
+{
+ if( cropToMask )
+ {
+ // First scale this buffer by the contentScale, and crop to the mask size
+ // If it's too small, then scale the mask to match the image size
+ // Then apply the mask
+ ScaleAndCrop( contentScale, ImageDimensions( inMask.GetWidth(), inMask.GetHeight() ) );
+
+ if( inMask.mWidth > mWidth || inMask.mHeight > mHeight )
+ {
+ PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
+ ApplyMaskInternal( *mask );
+ }
+ else
+ {
+ ApplyMaskInternal( inMask );
+ }
+ }
+ else
+ {
+ // First, scale the mask to match the image size,
+ // then apply the mask.
+ PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) );
+ ApplyMaskInternal( *mask );
+ }
+}
+
+void PixelBuffer::ApplyMaskInternal( const PixelBuffer& mask )
+{
+ int byteOffset=0;
+ int bitMask=0;
+
+ Dali::Pixel::GetAlphaOffsetAndMask(mPixelFormat, byteOffset, bitMask);
+ if( Dali::Pixel::HasAlpha( mPixelFormat ) && bitMask == 255 )
+ {
+ ApplyMaskToAlphaChannel( *this, mask );
+ }
+ else
+ {
+ PixelBufferPtr newPixelBuffer = CreateNewMaskedBuffer( *this, mask );
+ TakeOwnershipOfBuffer( *newPixelBuffer );
+ // On leaving scope, newPixelBuffer will get destroyed.
+ }
+}
+
+void PixelBuffer::TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer )
+{
+ ReleaseBuffer();
+
+ // Take ownership of new buffer
+ mBuffer = pixelBuffer.mBuffer;
+ pixelBuffer.mBuffer = NULL;
+ mBufferSize = pixelBuffer.mBufferSize;
+ mWidth = pixelBuffer.mWidth;
+ mHeight = pixelBuffer.mHeight;
+ mPixelFormat = pixelBuffer.mPixelFormat;
+}
+
+void PixelBuffer::ReleaseBuffer()
+{
+ if( mBuffer )
+ {
+ free( mBuffer );
+ }
+}
+
+void PixelBuffer::AllocateFixedSize( uint32_t size )
+{
+ ReleaseBuffer();
+ mBuffer = reinterpret_cast<unsigned char*>(malloc( size ));
+ mBufferSize = size;
+}
+
+void PixelBuffer::ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions )
+{
+ ImageDimensions outDimensions( float(mWidth) * scaleFactor,
+ float(mHeight) * scaleFactor );
+
+ if( outDimensions.GetWidth() != mWidth || outDimensions.GetHeight() != mHeight )
+ {
+ Resize( outDimensions );
+ }
+
+ ImageDimensions postCropDimensions(
+ std::min(cropDimensions.GetWidth(), outDimensions.GetWidth()),
+ std::min(cropDimensions.GetHeight(), outDimensions.GetHeight()));
+
+ if( postCropDimensions.GetWidth() < outDimensions.GetWidth() ||
+ postCropDimensions.GetHeight() < outDimensions.GetHeight() )
+ {
+ uint16_t x = ( outDimensions.GetWidth() - postCropDimensions.GetWidth() ) / 2;
+ uint16_t y = ( outDimensions.GetHeight() - postCropDimensions.GetHeight() ) / 2;
+ Crop( x, y, postCropDimensions );
+ }
+}
+
+void PixelBuffer::Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions )
+{
+ PixelBufferPtr outBuffer = NewCrop( *this, x, y, cropDimensions );
+ TakeOwnershipOfBuffer( *outBuffer );
+}
+
+PixelBufferPtr PixelBuffer::NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions )
+{
+ PixelBufferPtr outBuffer = PixelBuffer::New( cropDimensions.GetWidth(), cropDimensions.GetHeight(), inBuffer.GetPixelFormat() );
+ int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
+ int srcStride = inBuffer.mWidth * bytesPerPixel;
+ int destStride = cropDimensions.GetWidth() * bytesPerPixel;
+
+ // Clamp crop to right edge
+ if( x + cropDimensions.GetWidth() > inBuffer.mWidth )
+ {
+ destStride = ( inBuffer.mWidth - x ) * bytesPerPixel;
+ }
+
+ int srcOffset = x * bytesPerPixel + y * srcStride;
+ int destOffset = 0;
+ unsigned char* destBuffer = outBuffer->mBuffer;
+
+ // Clamp crop to last row
+ unsigned int endRow = y + cropDimensions.GetHeight();
+ if( endRow > inBuffer.mHeight )
+ {
+ endRow = inBuffer.mHeight - 1 ;
+ }
+ for( uint16_t row = y; row < endRow; ++row )
+ {
+ memcpy(destBuffer + destOffset, inBuffer.mBuffer + srcOffset, destStride );
+ srcOffset += srcStride;
+ destOffset += destStride;
+ }
+ return outBuffer;
+
+}
+
+void PixelBuffer::SetMetadata( const Property::Map& map )
+{
+ mMetadata.reset(new Property::Map(map));
+}
+
+bool PixelBuffer::GetMetadata(Property::Map& outMetadata) const
+{
+ if( !mMetadata )
+ {
+ return false;
+ }
+ outMetadata = *mMetadata;
+ return true;
+}
+
+void PixelBuffer::SetMetadata(std::unique_ptr<Property::Map> metadata)
+{
+ mMetadata = std::move(metadata);
+}
+
+void PixelBuffer::Resize( ImageDimensions outDimensions )
+{
+ if( mWidth != outDimensions.GetWidth() || mHeight != outDimensions.GetHeight() )
+ {
+ PixelBufferPtr outBuffer = NewResize( *this, outDimensions );
+ TakeOwnershipOfBuffer( *outBuffer );
+ }
+}
+
+PixelBufferPtr PixelBuffer::NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions )
+{
+ PixelBufferPtr outBuffer = PixelBuffer::New( outDimensions.GetWidth(), outDimensions.GetHeight(), inBuffer.GetPixelFormat() );
+ ImageDimensions inDimensions( inBuffer.mWidth, inBuffer.mHeight );
+
+ bool hasAlpha = Pixel::HasAlpha( inBuffer.mPixelFormat );
+ int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat );
+
+ Resampler::Filter filterType = Resampler::LANCZOS4;
+ if( inDimensions.GetWidth() < outDimensions.GetWidth() && inDimensions.GetHeight() < outDimensions.GetHeight() )
+ {
+ filterType = Resampler::MITCHELL;
+ }
+
+ // This method only really works for 8 bit wide channels.
+ // (But could be expanded to work)
+ if( inBuffer.mPixelFormat == Pixel::A8 ||
+ inBuffer.mPixelFormat == Pixel::L8 ||
+ inBuffer.mPixelFormat == Pixel::LA88 ||
+ inBuffer.mPixelFormat == Pixel::RGB888 ||
+ inBuffer.mPixelFormat == Pixel::RGB8888 ||
+ inBuffer.mPixelFormat == Pixel::BGR8888 ||
+ inBuffer.mPixelFormat == Pixel::RGBA8888 ||
+ inBuffer.mPixelFormat == Pixel::BGRA8888 )
+ {
+ Dali::Internal::Platform::Resample( inBuffer.mBuffer, inDimensions,
+ outBuffer->GetBuffer(), outDimensions,
+ filterType, bytesPerPixel, hasAlpha );
+ }
+ else
+ {
+ DALI_LOG_ERROR( "Trying to resize an image with too narrow a channel width" );
+ }
+
+ return outBuffer;
+}
+
+void PixelBuffer::ApplyGaussianBlur( const float blurRadius )
+{
+ // This method only works for pixel buffer in RGBA format.
+ if( mWidth > 0 && mHeight > 0 && mPixelFormat == Pixel::RGBA8888 )
+ {
+ if ( blurRadius > Math::MACHINE_EPSILON_1 )
+ {
+ PerformGaussianBlurRGBA( *this, blurRadius );
+ }
+ }
+ else
+ {
+ DALI_LOG_ERROR( "Trying to apply gaussian blur to an empty pixel buffer or a pixel buffer not in RGBA format" );
+ }
+}
+
+void PixelBuffer::MultiplyColorByAlpha()
+{
+ auto bytesPerPixel = Pixel::GetBytesPerPixel( mPixelFormat );
+
+ // Compressed textures have unknown size of the pixel. Alpha premultiplication
+ // must be skipped in such case
+ if( Pixel::GetBytesPerPixel(mPixelFormat) && Pixel::HasAlpha(mPixelFormat) )
+ {
+ unsigned char* pixel = mBuffer;
+ const unsigned int bufferSize = mWidth * mHeight;
+
+ for( unsigned int i=0; i<bufferSize; ++i )
+ {
+ unsigned int alpha = ReadChannel( pixel, mPixelFormat, Adaptor::ALPHA );
+ {
+ auto red = ReadChannel( pixel, mPixelFormat, Adaptor::RED);
+ auto green = ReadChannel( pixel, mPixelFormat, Adaptor::GREEN);
+ auto blue = ReadChannel( pixel, mPixelFormat, Adaptor::BLUE);
+ auto luminance = ReadChannel( pixel, mPixelFormat, Adaptor::LUMINANCE);
+ WriteChannel( pixel, mPixelFormat, Adaptor::RED, red*alpha / 255 );
+ WriteChannel( pixel, mPixelFormat, Adaptor::GREEN, green*alpha/255 );
+ WriteChannel( pixel, mPixelFormat, Adaptor::BLUE, blue*alpha/255 );
+ WriteChannel( pixel, mPixelFormat, Adaptor::LUMINANCE, luminance*alpha/255 );
+ }
+ pixel += bytesPerPixel;
+ }
+ }
+}
+
+
+
+
+}// namespace Adaptor
+}// namespace Internal
+}// namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H
+#define DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H
+
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <dali/public-api/images/image-operations.h> // For ImageDimensions
+#include <dali/public-api/images/pixel-data.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/object/property-map.h>
+
+// EXTERNAL INCLUDES
+#include <memory>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class PixelBuffer;
+typedef IntrusivePtr<PixelBuffer> PixelBufferPtr;
+
+class PixelBuffer : public BaseObject
+{
+public:
+
+ /**
+ * @brief Create a PixelBuffer object with a pre-allocated buffer.
+ * The PixelBuffer object owns this buffer, which may be retrieved
+ * and modified using GetBuffer().
+ *
+ * @param [in] width Buffer width in pixels
+ * @param [in] height Buffer height in pixels
+ * @param [in] pixelFormat The pixel format
+ */
+ static PixelBufferPtr New( unsigned int width,
+ unsigned int height,
+ Pixel::Format pixelFormat );
+
+ /**
+ * @brief Create a PixelBuffer object. For internal use only.
+ *
+ * @param [in] buffer The raw pixel data.
+ * @param [in] bufferSize The size of the buffer in bytes
+ * @param [in] width Buffer width in pixels
+ * @param [in] height Buffer height in pixels
+ * @param [in] pixelFormat The pixel format
+ * @param [in] releaseFunction The function used to release the memory.
+ */
+ static PixelBufferPtr New( unsigned char* buffer,
+ unsigned int bufferSize,
+ unsigned int width,
+ unsigned int height,
+ Pixel::Format pixelFormat );
+
+ /**
+ * Convert a pixelBuffer object into a PixelData object.
+ * The new object takes ownership of the buffer data, and the
+ * mBuffer pointer is reset to NULL.
+ * @param[in] pixelBuffer The buffer to convert
+ * @return the pixelData
+ */
+ static Dali::PixelData Convert( PixelBuffer& pixelBuffer );
+
+ /**
+ * @brief Constructor.
+ *
+ * @param [in] buffer The raw pixel data.
+ * @param [in] bufferSize The size of the buffer in bytes
+ * @param [in] width Buffer width in pixels
+ * @param [in] height Buffer height in pixels
+ * @param [in] pixelFormat The pixel format
+ */
+ PixelBuffer( unsigned char* buffer,
+ unsigned int bufferSize,
+ unsigned int width,
+ unsigned int height,
+ Pixel::Format pixelFormat );
+
+protected:
+
+ /**
+ * @brief Destructor.
+ *
+ * Release the pixel buffer if exists.
+ */
+ ~PixelBuffer();
+
+public:
+
+ /**
+ * Get the width of the buffer in pixels.
+ * @return The width of the buffer in pixels
+ */
+ unsigned int GetWidth() const;
+
+ /**
+ * Get the height of the buffer in pixels
+ * @return The height of the buffer in pixels
+ */
+ unsigned int GetHeight() const;
+
+ /**
+ * Get the pixel format
+ * @return The pixel format
+ */
+ Pixel::Format GetPixelFormat() const;
+
+ /**
+ * Get the pixel buffer if it's present.
+ * @return The buffer if exists, or NULL if there is no pixel buffer.
+ */
+ unsigned char* GetBuffer() const;
+
+ /**
+ * Get the size of the buffer in bytes
+ * @return The size of the buffer
+ */
+ unsigned int GetBufferSize() const;
+
+ /**
+ * Copy the buffer into a new PixelData
+ */
+ Dali::PixelData CreatePixelData() const;
+
+ /**
+ * @brief Apply the mask to the current buffer.
+ *
+ * This method may update the internal object - e.g. the new buffer
+ * may have a different pixel format - as an alpha channel may be
+ * added.
+ * @param[in] mask The mask to apply to this pixel buffer
+ * @param[in] contentScale The scaling factor to apply to the content
+ * @param[in] cropToMask Whether to crop the output to the mask size (true) or scale the
+ * mask to the content size (false)
+ */
+ void ApplyMask( const PixelBuffer& mask, float contentScale, bool cropToMask );
+
+ /**
+ * @brief Apply a Gaussian blur to the current buffer with the given radius.
+ *
+ * @param[in] blurRadius The radius for Gaussian blur
+ */
+ void ApplyGaussianBlur( const float blurRadius );
+
+ /**
+ * Crops this buffer to the given crop rectangle. Assumes the crop rectangle
+ * is within the bounds of this size.
+ * @param[in] x The top left corner's X
+ * @param[in] y The top left corner's y
+ * @param[in] cropDimensions The dimensions of the crop
+ */
+ void Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions );
+
+ /**
+ * Resizes the buffer to the given dimensions. Uses either Lanczos4 for downscaling
+ * or Mitchell for upscaling
+ * @param[in] outDimensions The new dimensions
+ */
+ void Resize( ImageDimensions outDimensions );
+
+ /**
+ * Multiplies the image's color values by the alpha value. This provides better
+ * blending capability.
+ */
+ void MultiplyColorByAlpha();
+
+ /**
+ * @brief Sets image metadata
+ *
+ * @param map Property map containing Exif fields
+ */
+ void SetMetadata( const Property::Map& map );
+
+ /**
+ * @brief Returns image metadata as a property map
+ * @param[out] outMetadata Property map to copy the data into
+ * @return True on success
+ */
+ bool GetMetadata(Property::Map& outMetadata) const;
+
+ /**
+ * @brief Sets metadata property map for the pixel buffer
+ * @note The function takes over the ownership of the property map
+ * @param[in] metadata Property map to copy the data into
+ */
+ void SetMetadata(std::unique_ptr<Property::Map> metadata);
+
+ /**
+ * Allocates fixed amount of memory for the pixel data. Used by compressed formats.
+ * @param[in] size Size of memory to be allocated
+ */
+ void AllocateFixedSize( uint32_t size );
+
+private:
+ /*
+ * Undefined copy constructor.
+ */
+ PixelBuffer(const PixelBuffer& other);
+
+ /*
+ * Undefined assignment operator.
+ */
+ PixelBuffer& operator= (const PixelBuffer& other);
+
+ /**
+ * Internal method to apply the mask to this buffer. Expects that they are the same size.
+ */
+ void ApplyMaskInternal( const PixelBuffer& mask );
+
+ /**
+ * Takes ownership of the other object's pixel buffer.
+ */
+ void TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer );
+
+ /**
+ * Release the buffer
+ */
+ void ReleaseBuffer();
+
+ /**
+ * Scales this buffer buffer by the given factor, and crops at the center to the
+ * given dimensions.
+ */
+ void ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions );
+
+ /**
+ * Creates a new buffer which is a crop of the passed in buffer,
+ * using the given crop rectangle. Assumes the crop rectangle is
+ * within the bounds of this size.
+ * @param[in] inBuffer The source buffer
+ * @param[in] x The top left corner's X
+ * @param[in] y The top left corner's y
+ * @param[in] cropDimensions The dimensions of the crop
+ * @return the new pixel buffer
+ */
+ static PixelBufferPtr NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions );
+
+ /**
+ * Creates a new buffer which is a resized version of the passed in buffer.
+ * Uses either Lanczos4 for downscaling, or Mitchell for upscaling.
+ * @param[in] inBuffer The source buffer
+ * @param[in] outDimensions The new dimensions
+ * @return a new buffer of the given size.
+ */
+ static PixelBufferPtr NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions );
+
+
+private:
+
+ std::unique_ptr<Property::Map> mMetadata; ///< Metadata fields
+ unsigned char* mBuffer; ///< The raw pixel data
+ unsigned int mBufferSize; ///< Buffer sized in bytes
+ unsigned int mWidth; ///< Buffer width in pixels
+ unsigned int mHeight; ///< Buffer height in pixels
+ Pixel::Format mPixelFormat; ///< Pixel format
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+/**
+ * Helper methods for public API
+ */
+inline Internal::Adaptor::PixelBuffer& GetImplementation( Devel::PixelBuffer& handle )
+{
+ DALI_ASSERT_ALWAYS( handle && "handle is empty" );
+
+ BaseObject& object = handle.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::PixelBuffer&>( object );
+}
+
+inline const Internal::Adaptor::PixelBuffer& GetImplementation( const Devel::PixelBuffer& handle )
+{
+ DALI_ASSERT_ALWAYS( handle && "handle is empty" );
+
+ const BaseObject& object = handle.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::PixelBuffer&>( object );
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_PIXEL_BUFFER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/common/pixel-manipulation.h>
+
+// INTERNAL HEADERS
+#include <dali/public-api/images/pixel.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+struct Location
+{
+ unsigned int bitShift;
+ unsigned int bitMask;
+ bool available;
+};
+
+struct Locations
+{
+ Location luminance;
+ Location alpha;
+ Location red;
+ Location green;
+ Location blue;
+};
+
+
+bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel )
+{
+ switch (pixelFormat)
+ {
+ case Dali::Pixel::A8:
+ {
+ return (channel == ALPHA);
+ }
+ case Dali::Pixel::L8:
+ {
+ return (channel == LUMINANCE);
+ }
+ case Dali::Pixel::LA88:
+ {
+ return ( channel == LUMINANCE || channel == ALPHA );
+ }
+ case Dali::Pixel::RGB565:
+ case Dali::Pixel::BGR565:
+ case Dali::Pixel::RGB888:
+ case Dali::Pixel::RGB8888:
+ case Dali::Pixel::BGR8888:
+ case Dali::Pixel::RGB16F:
+ case Dali::Pixel::RGB32F:
+ {
+ return ( channel == RED || channel == GREEN || channel == BLUE );
+ }
+
+ case Dali::Pixel::RGBA8888:
+ case Dali::Pixel::BGRA8888:
+ case Dali::Pixel::RGBA4444:
+ case Dali::Pixel::BGRA4444:
+ case Dali::Pixel::RGBA5551:
+ case Dali::Pixel::BGRA5551:
+ {
+ return ( channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA );
+ }
+
+ case Dali::Pixel::INVALID:
+ case Dali::Pixel::COMPRESSED_R11_EAC:
+ case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:
+ case Dali::Pixel::COMPRESSED_RG11_EAC:
+ case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:
+ case Dali::Pixel::COMPRESSED_RGB8_ETC2:
+ case Dali::Pixel::COMPRESSED_SRGB8_ETC2:
+ case Dali::Pixel::COMPRESSED_RGB8_ETC1:
+ case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:
+ case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
+ case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
+ case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:
+ case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
+ case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
+ {
+ DALI_LOG_ERROR("Pixel formats for compressed images are not compatible with simple channels.\n");
+ break;
+ }
+ }
+
+ return false;
+}
+
+unsigned int ReadChannel( unsigned char* pixelData,
+ Dali::Pixel::Format pixelFormat,
+ Channel channel )
+{
+ switch (pixelFormat)
+ {
+ case Dali::Pixel::A8:
+ {
+ if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else return 0u;
+ }
+ case Dali::Pixel::L8:
+ {
+ if( channel == LUMINANCE )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else return 0u;
+ }
+ case Dali::Pixel::LA88:
+ {
+ if( channel == LUMINANCE )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*(pixelData+1));
+ }
+ else return 0u;
+ }
+ case Dali::Pixel::RGB565:
+ {
+ if( channel == RED )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
+ }
+ else if( channel == GREEN )
+ {
+ return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
+ ((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
+ }
+ else if( channel == BLUE )
+ {
+ return static_cast<unsigned int>(*(pixelData+1)) & 0x1F;
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::BGR565:
+ {
+ if( channel == BLUE )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
+ }
+ else if( channel == GREEN )
+ {
+ return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
+ ((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
+ }
+ else if( channel == RED )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1) & 0x1F) );
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::RGB888:
+ case Dali::Pixel::RGB8888:
+ {
+ if( channel == RED )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else if( channel == GREEN )
+ {
+ return static_cast<unsigned int>(*(pixelData+1));
+ }
+ else if( channel == BLUE )
+ {
+ return static_cast<unsigned int>(*(pixelData+2));
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::BGR8888:
+ {
+ if( channel == BLUE )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else if( channel == GREEN )
+ {
+ return static_cast<unsigned int>(*(pixelData+1));
+ }
+ else if( channel == RED )
+ {
+ return static_cast<unsigned int>(*(pixelData+2));
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::RGBA8888:
+ {
+ if( channel == RED )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else if( channel == GREEN )
+ {
+ return static_cast<unsigned int>(*(pixelData+1));
+ }
+ else if( channel == BLUE )
+ {
+ return static_cast<unsigned int>(*(pixelData+2));
+ }
+ else if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*(pixelData+3));
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::BGRA8888:
+ {
+ if( channel == BLUE )
+ {
+ return static_cast<unsigned int>(*pixelData);
+ }
+ else if( channel == GREEN )
+ {
+ return static_cast<unsigned int>(*(pixelData+1));
+ }
+ else if( channel == RED )
+ {
+ return static_cast<unsigned int>(*(pixelData+2));
+ }
+ else if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*(pixelData+3));
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::RGBA4444:
+ {
+ if( channel == RED )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
+ }
+ else if( channel == GREEN )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0x0F);
+ }
+ else if( channel == BLUE )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
+ }
+ else if( channel == ALPHA )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::BGRA4444:
+ {
+ if( channel == BLUE )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
+ }
+ else if( channel == GREEN )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0x0F);
+ }
+ else if( channel == RED )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
+ }
+ else if( channel == ALPHA )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
+ }
+ else return 0u;
+ }
+
+ case Dali::Pixel::RGBA5551:
+ {
+ if( channel == RED )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
+ }
+ else if( channel == GREEN )
+ {
+ return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
+ ((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
+ }
+ else if( channel == BLUE )
+ {
+ return (static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
+ }
+ else if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
+ }
+
+ else return 0u;
+ }
+
+ case Dali::Pixel::BGRA5551:
+ {
+ if( channel == BLUE )
+ {
+ return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
+ }
+ else if( channel == GREEN )
+ {
+ return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
+ ((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
+ }
+ else if( channel == RED )
+ {
+ return ( static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
+ }
+ else if( channel == ALPHA )
+ {
+ return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
+ }
+
+ else return 0u;
+ }
+
+ default:
+ {
+ return 0u;
+ }
+ }
+}
+
+void WriteChannel( unsigned char* pixelData,
+ Dali::Pixel::Format pixelFormat,
+ Channel channel,
+ unsigned int channelValue )
+{
+ switch (pixelFormat)
+ {
+ case Dali::Pixel::A8:
+ {
+ if( channel == ALPHA )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+ case Dali::Pixel::L8:
+ {
+ if( channel == LUMINANCE )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+ case Dali::Pixel::LA88:
+ {
+ if( channel == LUMINANCE )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+ case Dali::Pixel::RGB565:
+ {
+ if( channel == RED )
+ {
+ *pixelData &= ~0xF8;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x07;
+ *pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
+
+ *(pixelData+1) &= ~0xE0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
+ }
+ else if( channel == BLUE )
+ {
+ *(pixelData+1) &= ~0x1F;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
+ }
+ break;
+ }
+
+ case Dali::Pixel::BGR565:
+ {
+ if( channel == BLUE )
+ {
+ *pixelData &= ~0xF8;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x07;
+ *pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
+
+ *(pixelData+1) &= ~0xE0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
+ }
+ else if( channel == RED )
+ {
+ *(pixelData+1) &= ~0x1F;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
+ }
+ break;
+ }
+
+ case Dali::Pixel::RGB888:
+ case Dali::Pixel::RGB8888:
+ {
+ if( channel == RED )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == GREEN )
+ {
+ *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == BLUE )
+ {
+ *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+
+ case Dali::Pixel::BGR8888:
+ {
+ if( channel == BLUE )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == GREEN )
+ {
+ *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == RED )
+ {
+ *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+
+ case Dali::Pixel::RGBA8888:
+ {
+ if( channel == RED )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == GREEN )
+ {
+ *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == BLUE )
+ {
+ *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+
+ case Dali::Pixel::BGRA8888:
+ {
+ if( channel == BLUE )
+ {
+ *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == GREEN )
+ {
+ *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == RED )
+ {
+ *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
+ }
+ break;
+ }
+
+ case Dali::Pixel::RGBA4444:
+ {
+ if( channel == RED )
+ {
+ *pixelData &= ~0xF0;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x0F;
+ *pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
+ }
+ else if( channel == BLUE )
+ {
+ *(pixelData+1) &= ~0xF0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+1) &= ~0x0F;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
+ }
+ break;
+ }
+
+ case Dali::Pixel::BGRA4444:
+ {
+ if( channel == BLUE )
+ {
+ *pixelData &= ~0xF0;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x0F;
+ *pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
+ }
+ else if( channel == RED )
+ {
+ *(pixelData+1) &= ~0xF0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+1) &= ~0x0F;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
+ }
+ break;
+ }
+
+ case Dali::Pixel::RGBA5551:
+ {
+ // rrrrrggg ggbbbbba
+ // F8 7 C0 3E 1
+ if( channel == RED )
+ {
+ *pixelData &= ~0xF8;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x07;
+ *pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
+
+ *(pixelData+1) &= ~0xC0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
+ }
+ else if( channel == BLUE )
+ {
+ *(pixelData+1) &= ~0x3E;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1) & 0x3E );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+1) &= ~0x01;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
+ }
+ break;
+ }
+
+ case Dali::Pixel::BGRA5551:
+ {
+ if( channel == BLUE )
+ {
+ *pixelData &= ~0xF8;
+ *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
+ }
+ else if( channel == GREEN )
+ {
+ *pixelData &= ~0x07;
+ *pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
+
+ *(pixelData+1) &= ~0xC0;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
+ }
+ else if( channel == RED )
+ {
+ *(pixelData+1) &= ~0x3E;
+ *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1 ) & 0x3E );
+ }
+ else if( channel == ALPHA )
+ {
+ *(pixelData+1) &= ~0x01;
+ *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+}
+
+void ConvertColorChannelsToRGBA8888(
+ unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat,
+ unsigned char* destPixel, int destOffset )
+{
+ int red = ReadChannel(srcPixel+srcOffset, srcFormat, RED );
+ int green = ReadChannel(srcPixel+srcOffset, srcFormat, GREEN );
+ int blue = ReadChannel(srcPixel+srcOffset, srcFormat, BLUE );
+ switch( srcFormat )
+ {
+ case Dali::Pixel::RGB565:
+ case Dali::Pixel::BGR565:
+ {
+ red = (red<<3) | (red & 0x07);
+ green = (green << 2) | (green & 0x03);
+ blue = (blue<<3) | (blue & 0x07);
+ break;
+ }
+ case Dali::Pixel::RGBA4444:
+ case Dali::Pixel::BGRA4444:
+ {
+ red = (red<<4) | (red&0x0F);
+ green = (green<<4) | (green&0x0F);
+ blue = (blue<<4) | (blue&0x0F);
+ break;
+ }
+ case Dali::Pixel::RGBA5551:
+ case Dali::Pixel::BGRA5551:
+ {
+ red = (red<<3) | (red&0x07);
+ green = (green<<3) | (green&0x07);
+ blue = (blue<<3) | (blue&0x07);
+ break;
+ }
+ default:
+ break;
+ }
+ WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, RED, red);
+ WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, GREEN, green);
+ WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, BLUE, blue);
+}
+
+
+int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat )
+{
+ int alpha = ReadChannel(srcPixel+srcOffset, srcFormat, ALPHA );
+ int destAlpha = alpha;
+ switch( srcFormat )
+ {
+ case Pixel::RGBA5551:
+ case Pixel::BGRA5551:
+ {
+ destAlpha = (alpha==0)?0:255;
+ break;
+ }
+ case Pixel::RGBA4444:
+ case Pixel::BGRA4444:
+ {
+ destAlpha = (alpha<<4) | (alpha&0x0F);
+ break;
+ }
+ default:
+ break;
+ }
+ return destAlpha;
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+
+
+# module: imaging, backend: common
+adaptor_imaging_common_src_files=\
+ ${adaptor_imaging_dir}/common/native-bitmap-buffer-impl.cpp \
+ ${adaptor_imaging_dir}/common/native-image-source-factory.cpp \
+ ${adaptor_imaging_dir}/common/native-image-source-impl.cpp \
+ ${adaptor_imaging_dir}/common/pixel-buffer-impl.cpp \
+ ${adaptor_imaging_dir}/common/alpha-mask.cpp \
+ ${adaptor_imaging_dir}/common/file-download.cpp \
+ ${adaptor_imaging_dir}/common/gaussian-blur.cpp \
+ ${adaptor_imaging_dir}/common/http-utils.cpp \
+ ${adaptor_imaging_dir}/common/image-loader.cpp \
+ ${adaptor_imaging_dir}/common/image-operations.cpp \
+ ${adaptor_imaging_dir}/common/loader-astc.cpp \
+ ${adaptor_imaging_dir}/common/loader-bmp.cpp \
+ ${adaptor_imaging_dir}/common/loader-gif.cpp \
+ ${adaptor_imaging_dir}/common/loader-ico.cpp \
+ ${adaptor_imaging_dir}/common/loader-jpeg-turbo.cpp \
+ ${adaptor_imaging_dir}/common/loader-ktx.cpp \
+ ${adaptor_imaging_dir}/common/loader-png.cpp \
+ ${adaptor_imaging_dir}/common/loader-wbmp.cpp \
+ ${adaptor_imaging_dir}/common/pixel-manipulation.cpp
+
+# module: imaging, backend: tizen
+adaptor_imaging_tizen_src_files=\
+ ${adaptor_imaging_dir}/tizen/native-image-source-factory-tizen.cpp \
+ ${adaptor_imaging_dir}/tizen/native-image-source-impl-tizen.cpp
+
+# module: imaging, backend: ubuntu-x11
+adaptor_imaging_ubuntu_x11_src_files=\
+ ${adaptor_imaging_dir}/ubuntu-x11/native-image-source-factory-x.cpp \
+ ${adaptor_imaging_dir}/ubuntu-x11/native-image-source-impl-x.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/internal/imaging/tizen/native-image-source-impl-tizen.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+namespace NativeImageSourceFactory
+{
+
+/**
+ * Dummy implementation
+ * @param width
+ * @param height
+ * @param depth
+ * @param nativeImageSource
+ * @return
+ */
+std::unique_ptr<Dali::Internal::Adaptor::NativeImageSource> New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource)
+{
+ return std::unique_ptr<NativeImageSourceTizen>( NativeImageSourceTizen::New( width, height, depth, nativeImageSource ) );
+}
+
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/tizen/native-image-source-impl-tizen.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/gl-defines.h>
+#include <cstring>
+#include <tbm_surface_internal.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+#include <dali/internal/graphics/gles20/egl-factory.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+
+// Allow this to be encoded and saved:
+#include <dali/devel-api/adaptor-framework/bitmap-saver.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n";
+const char* SAMPLER_TYPE = "samplerExternalOES";
+
+tbm_format FORMATS_BLENDING_REQUIRED[] = {
+ TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444,
+ TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444,
+ TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551,
+ TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555,
+ TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551,
+ TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888,
+ TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888,
+ TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010,
+ TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102
+};
+
+const int NUM_FORMATS_BLENDING_REQUIRED = 18;
+
+}
+
+using Dali::Integration::PixelBuffer;
+
+NativeImageSourceTizen* NativeImageSourceTizen::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
+{
+ NativeImageSourceTizen* image = new NativeImageSourceTizen( width, height, depth, nativeImageSource );
+ DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." );
+
+ if( image )
+ {
+ image->Initialize();
+ }
+
+ return image;
+}
+
+NativeImageSourceTizen::NativeImageSourceTizen( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
+: mWidth( width ),
+ mHeight( height ),
+ mOwnTbmSurface( false ),
+ mTbmSurface( NULL ),
+ mTbmFormat( 0 ),
+ mBlendingRequired( false ),
+ mColorDepth( depth ),
+ mEglImageKHR( NULL ),
+ mEglImageExtensions( NULL ),
+ mSetSource( false )
+{
+ DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );
+ EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();
+ mEglImageExtensions = eglFactory.GetImageExtensions();
+ DALI_ASSERT_DEBUG( mEglImageExtensions );
+
+ mTbmSurface = GetSurfaceFromAny( nativeImageSource );
+
+ if( mTbmSurface != NULL )
+ {
+ tbm_surface_internal_ref( mTbmSurface );
+ mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
+ mWidth = tbm_surface_get_width( mTbmSurface );
+ mHeight = tbm_surface_get_height( mTbmSurface );
+ }
+}
+
+void NativeImageSourceTizen::Initialize()
+{
+ if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 )
+ {
+ return;
+ }
+
+ tbm_format format = TBM_FORMAT_RGB888;
+ int depth = 0;
+
+ switch( mColorDepth )
+ {
+ case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
+ {
+ format = TBM_FORMAT_RGBA8888;
+ depth = 32;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_8:
+ {
+ format = TBM_FORMAT_C8;
+ depth = 8;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_16:
+ {
+ format = TBM_FORMAT_RGB565;
+ depth = 16;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_24:
+ {
+ format = TBM_FORMAT_RGB888;
+ depth = 24;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_32:
+ {
+ format = TBM_FORMAT_RGBA8888;
+ depth = 32;
+ break;
+ }
+ default:
+ {
+ DALI_LOG_WARNING( "Wrong color depth.\n" );
+ return;
+ }
+ }
+
+ // set whether blending is required according to pixel format based on the depth
+ /* default pixel format is RGB888
+ If depth = 8, Pixel::A8;
+ If depth = 16, Pixel::RGB565;
+ If depth = 32, Pixel::RGBA8888 */
+ mBlendingRequired = ( depth == 32 || depth == 8 );
+
+ mTbmSurface = tbm_surface_create( mWidth, mHeight, format );
+ mOwnTbmSurface = true;
+}
+
+tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny( Any source ) const
+{
+ if( source.Empty() )
+ {
+ return NULL;
+ }
+
+ if( source.GetType() == typeid( tbm_surface_h ) )
+ {
+ return AnyCast< tbm_surface_h >( source );
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+NativeImageSourceTizen::~NativeImageSourceTizen()
+{
+ if( mOwnTbmSurface )
+ {
+ if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" );
+ }
+ }
+ else
+ {
+ if( mTbmSurface != NULL )
+ {
+ tbm_surface_internal_unref( mTbmSurface );
+ }
+ }
+}
+
+Any NativeImageSourceTizen::GetNativeImageSource() const
+{
+ return Any( mTbmSurface );
+}
+
+bool NativeImageSourceTizen::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
+{
+ if( mTbmSurface != NULL )
+ {
+ tbm_surface_info_s surface_info;
+
+ if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "Fail to map tbm_surface\n" );
+
+ width = 0;
+ height = 0;
+
+ return false;
+ }
+
+ tbm_format format = surface_info.format;
+ uint32_t stride = surface_info.planes[0].stride;
+ unsigned char* ptr = surface_info.planes[0].ptr;
+
+ width = mWidth;
+ height = mHeight;
+ size_t lineSize;
+ size_t offset;
+ size_t cOffset;
+
+ switch( format )
+ {
+ case TBM_FORMAT_RGB888:
+ {
+ lineSize = width*3;
+ pixelFormat = Pixel::RGB888;
+ pixbuf.resize( lineSize*height );
+ unsigned char* bufptr = &pixbuf[0];
+
+ for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
+ {
+ for( unsigned int c = 0; c < width; ++c )
+ {
+ cOffset = c*3;
+ offset = cOffset + r*stride;
+ *(bufptr+cOffset) = ptr[offset+2];
+ *(bufptr+cOffset+1) = ptr[offset+1];
+ *(bufptr+cOffset+2) = ptr[offset];
+ }
+ }
+ break;
+ }
+ case TBM_FORMAT_RGBA8888:
+ {
+ lineSize = width*4;
+ pixelFormat = Pixel::RGBA8888;
+ pixbuf.resize( lineSize*height );
+ unsigned char* bufptr = &pixbuf[0];
+
+ for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )
+ {
+ for( unsigned int c = 0; c < width; ++c )
+ {
+ cOffset = c*4;
+ offset = cOffset + r*stride;
+ *(bufptr+cOffset) = ptr[offset+3];
+ *(bufptr+cOffset+1) = ptr[offset+2];
+ *(bufptr+cOffset+2) = ptr[offset+1];
+ *(bufptr+cOffset+3) = ptr[offset];
+ }
+ }
+ break;
+ }
+ default:
+ {
+ DALI_ASSERT_ALWAYS( 0 && "Tbm surface has unsupported pixel format.\n" );
+
+ return false;
+ }
+ }
+
+ if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" );
+ }
+
+ return true;
+ }
+
+ DALI_LOG_WARNING( "TBM surface does not exist.\n" );
+
+ width = 0;
+ height = 0;
+
+ return false;
+}
+
+bool NativeImageSourceTizen::EncodeToFile(const std::string& filename) const
+{
+ std::vector< unsigned char > pixbuf;
+ unsigned int width(0), height(0);
+ Pixel::Format pixelFormat;
+
+ if(GetPixels(pixbuf, width, height, pixelFormat))
+ {
+ return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);
+ }
+ return false;
+}
+
+void NativeImageSourceTizen::SetSource( Any source )
+{
+ if( mOwnTbmSurface )
+ {
+ if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" );
+ }
+
+ mTbmSurface = NULL;
+ mOwnTbmSurface = false;
+ }
+ else
+ {
+ if( mTbmSurface != NULL )
+ {
+ tbm_surface_internal_unref( mTbmSurface );
+ mTbmSurface = NULL;
+ }
+ }
+
+ mTbmSurface = GetSurfaceFromAny( source );
+
+ if( mTbmSurface != NULL )
+ {
+ mSetSource = true;
+ tbm_surface_internal_ref( mTbmSurface );
+ mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );
+ mWidth = tbm_surface_get_width( mTbmSurface );
+ mHeight = tbm_surface_get_height( mTbmSurface );
+ }
+}
+
+bool NativeImageSourceTizen::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
+{
+ uint32_t* formats;
+ uint32_t formatNum;
+ tbm_format format = TBM_FORMAT_RGB888;
+
+ switch( colorDepth )
+ {
+ case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
+ {
+ format = TBM_FORMAT_RGBA8888;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_8:
+ {
+ format = TBM_FORMAT_C8;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_16:
+ {
+ format = TBM_FORMAT_RGB565;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_24:
+ {
+ format = TBM_FORMAT_RGB888;
+ break;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_32:
+ {
+ format = TBM_FORMAT_RGBA8888;
+ break;
+ }
+ }
+
+ if( tbm_surface_query_formats( &formats, &formatNum ) )
+ {
+ for( unsigned int i = 0; i < formatNum; i++ )
+ {
+ if( formats[i] == format )
+ {
+ free( formats );
+ return true;
+ }
+ }
+ }
+
+ free( formats );
+ return false;
+}
+
+bool NativeImageSourceTizen::GlExtensionCreate()
+{
+ // casting from an unsigned int to a void *, which should then be cast back
+ // to an unsigned int in the driver.
+ EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface);
+ if( !eglBuffer )
+ {
+ return false;
+ }
+
+ mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );
+
+ return mEglImageKHR != NULL;
+}
+
+void NativeImageSourceTizen::GlExtensionDestroy()
+{
+ if( mEglImageKHR )
+ {
+ mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
+
+ mEglImageKHR = NULL;
+ }
+}
+
+unsigned int NativeImageSourceTizen::TargetTexture()
+{
+ mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
+
+ return 0;
+}
+
+void NativeImageSourceTizen::PrepareTexture()
+{
+ if( mSetSource )
+ {
+ void* eglImage = mEglImageKHR;
+
+ if( GlExtensionCreate() )
+ {
+ TargetTexture();
+ }
+
+ mEglImageExtensions->DestroyImageKHR( eglImage );
+
+ mSetSource = false;
+ }
+}
+
+int NativeImageSourceTizen::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const
+{
+ switch (depth)
+ {
+ case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
+ {
+ // ToDo: Get the default screen depth
+ return 32;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_8:
+ {
+ return 8;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_16:
+ {
+ return 16;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_24:
+ {
+ return 24;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_32:
+ {
+ return 32;
+ }
+ default:
+ {
+ DALI_ASSERT_DEBUG(0 && "unknown color enum");
+ return 0;
+ }
+ }
+}
+
+const char* NativeImageSourceTizen::GetCustomFragmentPreFix()
+{
+ return FRAGMENT_PREFIX;
+}
+
+const char* NativeImageSourceTizen::GetCustomSamplerTypename()
+{
+ return SAMPLER_TYPE;
+}
+
+int NativeImageSourceTizen::GetEglImageTextureTarget()
+{
+ return GL_TEXTURE_EXTERNAL_OES;
+}
+
+bool NativeImageSourceTizen::CheckBlending( tbm_format format )
+{
+ if( mTbmFormat != format )
+ {
+ for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i)
+ {
+ if( format == FORMATS_BLENDING_REQUIRED[i] )
+ {
+ mBlendingRequired = true;
+ break;
+ }
+ }
+ mTbmFormat = format;
+ }
+
+ return mBlendingRequired;
+}
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_TIZEN_H
+#define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_TIZEN_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <tbm_surface.h>
+#include <dali/devel-api/images/native-image-interface-extension.h>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+#include <dali/internal/imaging/common/native-image-source-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class EglImageExtensions;
+
+/**
+ * Dali internal NativeImageSource.
+ */
+class NativeImageSourceTizen: public Internal::Adaptor::NativeImageSource, public NativeImageInterface::Extension
+{
+public:
+
+ /**
+ * Create a new NativeImageSource internally.
+ * Depending on hardware the width and height may have to be a power of two.
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] depth color depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return A smart-pointer to a newly allocated image.
+ */
+ static NativeImageSourceTizen* New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetNativeImageSource()
+ */
+ Any GetNativeImageSource() const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetPixels()
+ */
+ bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
+ */
+ bool EncodeToFile(const std::string& filename) const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::SetSource( Any source )
+ */
+ void SetSource( Any source ) override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
+ */
+ bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override;
+
+ /**
+ * destructor
+ */
+ ~NativeImageSourceTizen() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionCreate()
+ */
+ bool GlExtensionCreate() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
+ */
+ void GlExtensionDestroy() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::TargetTexture()
+ */
+ unsigned int TargetTexture() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::PrepareTexture()
+ */
+ void PrepareTexture() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetWidth()
+ */
+ unsigned int GetWidth() const override
+ {
+ return mWidth;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetHeight()
+ */
+ unsigned int GetHeight() const override
+ {
+ return mHeight;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::RequiresBlending()
+ */
+ bool RequiresBlending() const override
+ {
+ return mBlendingRequired;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetExtension()
+ */
+ NativeImageInterface::Extension* GetNativeImageInterfaceExtension() override
+ {
+ return this;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageInterface::Extension::GetCustomFragmentPreFix()
+ */
+ const char* GetCustomFragmentPreFix() override;
+
+ /**
+ * @copydoc Dali::NativeImageInterface::Extension::GetCustomSamplerTypename()
+ */
+ const char* GetCustomSamplerTypename() override;
+
+ /**
+ * @copydoc Dali::NativeImageInterface::Extension::GetEglImageTextureTarget()
+ */
+ int GetEglImageTextureTarget() override;
+
+private:
+
+ /**
+ * Private constructor; @see NativeImageSource::New()
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] colour depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ */
+ NativeImageSourceTizen(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+
+ void Initialize();
+
+ int GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const;
+
+ tbm_surface_h GetSurfaceFromAny( Any source ) const;
+
+ bool CheckBlending( tbm_format format );
+
+private:
+
+ unsigned int mWidth; ///< image width
+ unsigned int mHeight; ///< image heights
+ bool mOwnTbmSurface; ///< Whether we created pixmap or not
+ tbm_surface_h mTbmSurface;
+ tbm_format mTbmFormat;
+ bool mBlendingRequired; ///< Whether blending is required
+ Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image
+ void* mEglImageKHR; ///< From EGL extension
+ EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions
+ bool mSetSource;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_TIZEN_H
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+namespace NativeImageSourceFactory
+{
+
+/**
+ * Dummy implementation
+ * @param width
+ * @param height
+ * @param depth
+ * @param nativeImageSource
+ * @return
+ */
+std::unique_ptr<Dali::Internal::Adaptor::NativeImageSource> New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource)
+{
+ return std::unique_ptr<NativeImageSourceX>( NativeImageSourceX::New( width, height, depth, nativeImageSource ) );
+}
+
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h>
+
+// EXTERNAL INCLUDES
+#include <Ecore_X.h>
+#include <X11/Xutil.h>
+#include <X11/Xlib.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/graphics/common/egl-image-extensions.h>
+#include <dali/internal/graphics/gles20/egl-factory.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/devel-api/adaptor-framework/bitmap-saver.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+using Dali::Integration::PixelBuffer;
+
+// Pieces needed to save compressed images (temporary location while plumbing):
+namespace
+{
+
+ /**
+ * Free an allocated XImage on destruction.
+ */
+ struct XImageJanitor
+ {
+ XImageJanitor( XImage* const pXImage ) : mXImage( pXImage )
+ {
+ DALI_ASSERT_DEBUG(pXImage != 0 && "Null pointer to XImage.");
+ }
+
+ ~XImageJanitor()
+ {
+ if( mXImage )
+ {
+ if( !XDestroyImage(mXImage) )
+ {
+ DALI_LOG_ERROR("XImage deallocation failure");
+ }
+ }
+ }
+ XImage* const mXImage;
+ private:
+ XImageJanitor( const XImageJanitor& rhs );
+ XImageJanitor& operator = ( const XImageJanitor& rhs );
+ };
+}
+
+NativeImageSourceX* NativeImageSourceX::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
+{
+ NativeImageSourceX* image = new NativeImageSourceX( width, height, depth, nativeImageSource );
+ DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." );
+
+ // 2nd phase construction
+ if(image) //< Defensive in case we ever compile without exceptions.
+ {
+ image->Initialize();
+ }
+
+ return image;
+}
+
+NativeImageSourceX::NativeImageSourceX( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )
+: mWidth( width ),
+ mHeight( height ),
+ mOwnPixmap( true ),
+ mPixmap( 0 ),
+ mBlendingRequired( false ),
+ mColorDepth( depth ),
+ mEglImageKHR( NULL ),
+ mEglImageExtensions( NULL )
+{
+ DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );
+ EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();
+ mEglImageExtensions = eglFactory.GetImageExtensions();
+ DALI_ASSERT_DEBUG( mEglImageExtensions );
+
+ // assign the pixmap
+ mPixmap = GetPixmapFromAny(nativeImageSource);
+}
+
+void NativeImageSourceX::Initialize()
+{
+ // if pixmap has been created outside of X11 Image we can return
+ if (mPixmap)
+ {
+ // we don't own the pixmap
+ mOwnPixmap = false;
+
+ // find out the pixmap width / height and color depth
+ GetPixmapDetails();
+ return;
+ }
+
+ // get the pixel depth
+ int depth = GetPixelDepth(mColorDepth);
+
+ // set whether blending is required according to pixel format based on the depth
+ /* default pixel format is RGB888
+ If depth = 8, Pixel::A8;
+ If depth = 16, Pixel::RGB565;
+ If depth = 32, Pixel::RGBA8888 */
+ mBlendingRequired = ( depth == 32 || depth == 8 );
+
+ mPixmap = ecore_x_pixmap_new( 0, mWidth, mHeight, depth );
+ ecore_x_sync();
+}
+
+NativeImageSourceX::~NativeImageSourceX()
+{
+ if (mOwnPixmap && mPixmap)
+ {
+ ecore_x_pixmap_free(mPixmap);
+ }
+}
+
+Any NativeImageSourceX::GetNativeImageSource() const
+{
+ // return ecore x11 type
+ return Any(mPixmap);
+}
+
+bool NativeImageSourceX::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const
+{
+ DALI_ASSERT_DEBUG(sizeof(unsigned) == 4);
+ bool success = false;
+ width = mWidth;
+ height = mHeight;
+
+ // Open a display connection
+ Display* displayConnection = XOpenDisplay( 0 );
+
+ XImageJanitor xImageJanitor( XGetImage( displayConnection,
+ mPixmap,
+ 0, 0, // x,y of subregion to extract.
+ width, height, // of suregion to extract.
+ 0xFFFFFFFF,
+ ZPixmap ) );
+ XImage* const pXImage = xImageJanitor.mXImage;
+ DALI_ASSERT_DEBUG(pXImage && "XImage (from pixmap) could not be retrieved from the server");
+ if(!pXImage)
+ {
+ DALI_LOG_ERROR("Could not retrieve Ximage.\n");
+ }
+ else
+ {
+ switch(pXImage->depth)
+ {
+ // Note, depth is a logical value. On target the framebuffer is still 32bpp
+ // (see pXImage->bits_per_pixel) so we go through XGetPixel() and swizzle.
+ // Note, this could be the default, fallback case for all depths if *pXImage
+ // didn't have blank RGB masks (X bug), but we have to hardcode the masks and
+ // shifts instead.
+ case 24:
+ {
+ pixelFormat = Pixel::RGB888;
+ pixbuf.resize(width*height*3);
+ unsigned char* bufPtr = &pixbuf[0];
+
+ for(unsigned y = height-1; y < height; --y)
+ {
+ for(unsigned x = 0; x < width; ++x, bufPtr+=3)
+ {
+ const unsigned pixel = XGetPixel(pXImage,x,y);
+
+ // store as RGB
+ const unsigned blue = pixel & 0xFFU;
+ const unsigned green = (pixel >> 8) & 0xFFU;
+ const unsigned red = (pixel >> 16) & 0xFFU;
+
+ *bufPtr = red;
+ *(bufPtr+1) = green;
+ *(bufPtr+2) = blue;
+ }
+ }
+ success = true;
+ break;
+ }
+ case 32:
+ {
+ if(pXImage->data)
+ {
+ // Sweep through the image, doing a vertical flip, but handling each scanline as
+ // an inlined intrinsic/builtin memcpy (should be fast):
+ pixbuf.resize(width*height*4);
+ unsigned * bufPtr = reinterpret_cast<unsigned *>(&pixbuf[0]);
+ const unsigned xDataLineSkip = pXImage->bytes_per_line;
+ const size_t copy_count = static_cast< size_t >( width ) * 4;
+ pixelFormat = Pixel::BGRA8888;
+
+ for(unsigned y = height-1; y < height; --y, bufPtr += width)
+ {
+ const char * const in = pXImage->data + xDataLineSkip * y;
+
+ // Copy a whole scanline at a time:
+ DALI_ASSERT_DEBUG( size_t( bufPtr ) >= size_t( &pixbuf[0] ));
+ DALI_ASSERT_DEBUG( reinterpret_cast<size_t>( bufPtr ) + copy_count <= reinterpret_cast<size_t>( &pixbuf[pixbuf.size()] ) );
+ DALI_ASSERT_DEBUG( in >= pXImage->data );
+ DALI_ASSERT_DEBUG( in + copy_count <= pXImage->data + xDataLineSkip * height );
+ __builtin_memcpy( bufPtr, in, copy_count );
+ }
+ success = true;
+ }
+ else
+ {
+ DALI_LOG_ERROR("XImage has null data pointer.\n");
+ }
+ break;
+ }
+ // Make a case for 16 bit modes especially to remember that the only reason we don't support them is a bug in X:
+ case 16:
+ {
+ DALI_ASSERT_DEBUG(pXImage->red_mask && pXImage->green_mask && pXImage->blue_mask && "No image masks mean 16 bit modes are not possible.");
+ ///! If the above assert doesn't fail in a debug build, the X bug may have been fixed, so revisit this function.
+ ///! No break, fall through to the general unsupported format warning below.
+ }
+ default:
+ {
+ DALI_LOG_WARNING("Pixmap has unsupported bit-depth for getting pixels: %u\n", pXImage->depth);
+ }
+ }
+ }
+ if(!success)
+ {
+ DALI_LOG_ERROR("Failed to get pixels from NativeImageSource.\n");
+ pixbuf.resize(0);
+ width = 0;
+ height = 0;
+ }
+
+ // Close the display connection
+ XCloseDisplay( displayConnection );
+
+ return success;
+}
+
+bool NativeImageSourceX::EncodeToFile(const std::string& filename) const
+{
+ std::vector< unsigned char > pixbuf;
+ unsigned int width(0), height(0);
+ Pixel::Format pixelFormat;
+
+ if(GetPixels(pixbuf, width, height, pixelFormat))
+ {
+ return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);
+ }
+ return false;
+}
+
+void NativeImageSourceX::SetSource( Any source )
+{
+ mPixmap = GetPixmapFromAny( source );
+
+ if (mPixmap)
+ {
+ // we don't own the pixmap
+ mOwnPixmap = false;
+
+ // find out the pixmap width / height and color depth
+ GetPixmapDetails();
+ }
+}
+
+bool NativeImageSourceX::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )
+{
+ return true;
+}
+
+bool NativeImageSourceX::GlExtensionCreate()
+{
+ // if the image existed previously delete it.
+ if (mEglImageKHR != NULL)
+ {
+ GlExtensionDestroy();
+ }
+
+ // casting from an unsigned int to a void *, which should then be cast back
+ // to an unsigned int in the driver.
+ EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer > (mPixmap);
+
+ mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );
+
+ return mEglImageKHR != NULL;
+}
+
+void NativeImageSourceX::GlExtensionDestroy()
+{
+ mEglImageExtensions->DestroyImageKHR(mEglImageKHR);
+
+ mEglImageKHR = NULL;
+}
+
+unsigned int NativeImageSourceX::TargetTexture()
+{
+ mEglImageExtensions->TargetTextureKHR(mEglImageKHR);
+
+ return 0;
+}
+
+void NativeImageSourceX::PrepareTexture()
+{
+}
+
+int NativeImageSourceX::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const
+{
+ switch (depth)
+ {
+ case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:
+ {
+ // Get the default screen depth
+ return ecore_x_default_depth_get(ecore_x_display_get(), ecore_x_default_screen_get());
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_8:
+ {
+ return 8;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_16:
+ {
+ return 16;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_24:
+ {
+ return 24;
+ }
+ case Dali::NativeImageSource::COLOR_DEPTH_32:
+ {
+ return 32;
+ }
+ default:
+ {
+ DALI_ASSERT_DEBUG(0 && "unknown color enum");
+ return 0;
+ }
+ }
+}
+
+Ecore_X_Pixmap NativeImageSourceX::GetPixmapFromAny(Any pixmap) const
+{
+ if (pixmap.Empty())
+ {
+ return 0;
+ }
+
+ // see if it is of type x11 pixmap
+ if (pixmap.GetType() == typeid (Pixmap))
+ {
+ // get the x pixmap type
+ Pixmap xpixmap = AnyCast<Pixmap>(pixmap);
+
+ // cast it to a ecore pixmap type
+ return static_cast<Ecore_X_Pixmap>(xpixmap);
+ }
+ else
+ {
+ return AnyCast<Ecore_X_Pixmap>(pixmap);
+ }
+}
+
+void NativeImageSourceX::GetPixmapDetails()
+{
+ int x, y;
+
+ // get the width, height and depth
+ ecore_x_pixmap_geometry_get( mPixmap, &x, &y, reinterpret_cast< int* >( &mWidth ), reinterpret_cast< int* >( &mHeight ) );
+
+ // set whether blending is required according to pixel format based on the depth
+ /* default pixel format is RGB888
+ If depth = 8, Pixel::A8;
+ If depth = 16, Pixel::RGB565;
+ If depth = 32, Pixel::RGBA8888 */
+ int depth = ecore_x_pixmap_depth_get(mPixmap);
+ mBlendingRequired = ( depth == 32 || depth == 8 );
+}
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+#define __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_X.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+#include <dali/internal/imaging/common/native-image-source-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class EglImageExtensions;
+
+/**
+ * Dali internal NativeImageSource.
+ */
+class NativeImageSourceX : public Internal::Adaptor::NativeImageSource
+{
+public:
+
+ /**
+ * Create a new NativeImageSource internally.
+ * Depending on hardware the width and height may have to be a power of two.
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] depth color depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return A smart-pointer to a newly allocated image.
+ */
+ static NativeImageSourceX* New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+ /**
+ * @copydoc Dali::NativeImageSource::GetNativeImageSource()
+ */
+ Any GetNativeImageSource() const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetPixels()
+ */
+ bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
+ */
+ bool EncodeToFile(const std::string& filename) const override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::SetSource( Any source )
+ */
+ void SetSource( Any source ) override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
+ */
+ bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override;
+
+ /**
+ * destructor
+ */
+ ~NativeImageSourceX() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionCreate()
+ */
+ bool GlExtensionCreate() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
+ */
+ void GlExtensionDestroy() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::TargetTexture()
+ */
+ unsigned int TargetTexture() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::PrepareTexture()
+ */
+ void PrepareTexture() override;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetWidth()
+ */
+ unsigned int GetWidth() const override
+ {
+ return mWidth;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetHeight()
+ */
+ unsigned int GetHeight() const override
+ {
+ return mHeight;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::RequiresBlending()
+ */
+ bool RequiresBlending() const override
+ {
+ return mBlendingRequired;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetExtension()
+ */
+ NativeImageInterface::Extension* GetNativeImageInterfaceExtension() override
+ {
+ return nullptr;
+ }
+
+private:
+
+ /**
+ * Private constructor; @see NativeImageSource::New()
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] colour depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ */
+ NativeImageSourceX(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+
+ /**
+ * 2nd phase construction.
+ */
+ void Initialize();
+
+ /**
+ * Uses X11 to get the default depth.
+ * @param depth the PixelImage depth enum
+ * @return default x11 pixel depth
+ */
+ int GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const;
+
+ /**
+ * Gets the pixmap from the Any parameter
+ * @param pixmap contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return pixmap x11 pixmap
+ */
+ Ecore_X_Pixmap GetPixmapFromAny(Any pixmap) const;
+
+ /**
+ * Given an existing pixmap, the function uses X to find out
+ * the width, heigth and depth of that pixmap.
+ */
+ void GetPixmapDetails();
+
+private:
+
+ unsigned int mWidth; ///< image width
+ unsigned int mHeight; ///< image heights
+ bool mOwnPixmap; ///< Whether we created pixmap or not
+ Ecore_X_Pixmap mPixmap; ///< From Xlib
+ bool mBlendingRequired; ///< Whether blending is required
+ Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image
+ void* mEglImageKHR; ///< From EGL extension
+ EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::DragAndDropDetector DragAndDropDetector::New()
+{
+ Dali::DragAndDropDetector detector = Dali::DragAndDropDetector(new DragAndDropDetector());
+
+ return detector;
+}
+
+const std::string& DragAndDropDetector::GetContent() const
+{
+ return mContent;
+}
+
+Vector2 DragAndDropDetector::GetCurrentScreenPosition() const
+{
+ return mScreenPosition;
+}
+
+bool DragAndDropDetector::IsEnabled() const
+{
+ return !mDroppedSignal.Empty() || !mEnteredSignal.Empty() || !mExitedSignal.Empty() || !mMovedSignal.Empty() ;
+}
+
+void DragAndDropDetector::SetContent( const std::string& content )
+{
+ mContent = content;
+}
+
+void DragAndDropDetector::ClearContent()
+{
+ mContent.clear();
+}
+
+void DragAndDropDetector::SetPosition( Vector2 screenPosition )
+{
+ mScreenPosition = screenPosition;
+}
+
+void DragAndDropDetector::EmitEnteredSignal()
+{
+ if ( !mEnteredSignal.Empty() )
+ {
+ Dali::DragAndDropDetector handle( this );
+ mEnteredSignal.Emit( handle );
+ }
+}
+
+void DragAndDropDetector::EmitExitedSignal()
+{
+ if ( !mExitedSignal.Empty() )
+ {
+ Dali::DragAndDropDetector handle( this );
+ mExitedSignal.Emit( handle );
+ }
+}
+
+void DragAndDropDetector::EmitMovedSignal()
+{
+ if ( !mMovedSignal.Empty() )
+ {
+ Dali::DragAndDropDetector handle( this );
+ mMovedSignal.Emit( handle );
+ }
+}
+
+void DragAndDropDetector::EmitDroppedSignal()
+{
+ if ( !mDroppedSignal.Empty() )
+ {
+ Dali::DragAndDropDetector handle( this );
+ mDroppedSignal.Emit( handle );
+ }
+}
+
+DragAndDropDetector::DragAndDropDetector()
+: mContent(),
+ mScreenPosition()
+{
+}
+
+DragAndDropDetector::~DragAndDropDetector()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
+#define __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/math/vector2.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/drag-and-drop-detector.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+typedef IntrusivePtr< DragAndDropDetector > DragAndDropDetectorPtr;
+
+/**
+ * This class listens to Drag & Drop events.
+ */
+class DragAndDropDetector : public Dali::BaseObject
+{
+public:
+
+ typedef Dali::DragAndDropDetector::DragAndDropSignal DragAndDropSignal;
+
+ // Creation
+
+ /**
+ * Create a DragAndDropDetector.
+ * This should only be called once by the Window class.
+ * @return A newly allocated drag-and-drop-detector.
+ */
+ static Dali::DragAndDropDetector New();
+
+ // Public API
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::GetContent() const
+ */
+ const std::string& GetContent() const;
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::GetCurrentScreenPosition() const
+ */
+ Vector2 GetCurrentScreenPosition() const;
+
+ // Called by Drag & Drop Event Handler
+
+ /**
+ * Queries whether drag & drop behaviour is really required.
+ * @return true if drag & drop required, false otherwise.
+ */
+ bool IsEnabled() const;
+
+ /**
+ * Sets the dragged content.
+ * @param[in] content A string that represents the content that has been dropped.
+ */
+ void SetContent( const std::string& content );
+
+ /**
+ * Clears the stored content.
+ */
+ void ClearContent();
+
+ /**
+ * Sets the position the drop occurred.
+ */
+ void SetPosition( Vector2 screenPosition );
+
+ /**
+ * Called when a draggable object enters our window.
+ */
+ void EmitEnteredSignal();
+
+ /**
+ * Called when a draggable object leaves our window.
+ */
+ void EmitExitedSignal();
+
+ /**
+ * Called when a draggable object leaves our window.
+ */
+ void EmitMovedSignal();
+
+ /**
+ * Is called when a drop actually occurs.
+ */
+ void EmitDroppedSignal();
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::EnteredSignal
+ */
+ DragAndDropSignal& EnteredSignal()
+ {
+ return mEnteredSignal;
+ }
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::ExitedSignal
+ */
+ DragAndDropSignal& ExitedSignal()
+ {
+ return mExitedSignal;
+ }
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::MovedSignal
+ */
+ DragAndDropSignal& MovedSignal()
+ {
+ return mMovedSignal;
+ }
+
+ /**
+ * @copydoc Dali::DragAndDropDetector::DroppedSignal
+ */
+ DragAndDropSignal& DroppedSignal()
+ {
+ return mDroppedSignal;
+ }
+
+private:
+
+ // Construction & Destruction
+
+ /**
+ * Constructor.
+ */
+ DragAndDropDetector();
+
+ /**
+ * Destructor.
+ */
+ virtual ~DragAndDropDetector();
+
+ // Undefined
+ DragAndDropDetector( const DragAndDropDetector& );
+ DragAndDropDetector& operator=( DragAndDropDetector& );
+
+private:
+
+ std::string mContent; ///< The current Drag & drop content.
+ Vector2 mScreenPosition; ///< The screen position of the drop location.
+
+ DragAndDropSignal mEnteredSignal;
+ DragAndDropSignal mExitedSignal;
+ DragAndDropSignal mMovedSignal;
+ DragAndDropSignal mDroppedSignal;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::DragAndDropDetector& GetImplementation(Dali::DragAndDropDetector& detector)
+{
+ DALI_ASSERT_ALWAYS( detector && "DragAndDropDetector handle is empty" );
+
+ BaseObject& handle = detector.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::DragAndDropDetector&>(handle);
+}
+
+inline const Internal::Adaptor::DragAndDropDetector& GetImplementation(const Dali::DragAndDropDetector& detector)
+{
+ DALI_ASSERT_ALWAYS( detector && "DragAndDropDetector handle is empty" );
+
+ const BaseObject& handle = detector.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::DragAndDropDetector&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_DRAG_AND_DROP_DETECTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/gesture-manager.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+#include <dali/internal/input/common/long-press-gesture-detector.h>
+#include <dali/internal/input/common/pan-gesture-detector.h>
+#include <dali/internal/input/common/pinch-gesture-detector.h>
+#include <dali/internal/input/common/tap-gesture-detector.h>
+#include <dali/internal/system/common/core-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Integration::Log::Filter* gLogFilter = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_GESTURE_MANAGER" );
+
+/**
+ * Helper method to return the string representation of a gesture type.
+ */
+const char * GetGestureTypeString( Gesture::Type type )
+{
+ static const char * const pinch( "Pinch" );
+ static const char * const pan( "Pan" );
+ static const char * const tap( "tap" );
+ static const char * const longPress( "LongPress" );
+ static const char * const invalid( "Invalid" );
+
+ const char * retVal( NULL );
+
+ switch ( type )
+ {
+ case Gesture::LongPress:
+ {
+ retVal = longPress;
+ break;
+ }
+
+ case Gesture::Pan:
+ {
+ retVal = pan;
+ break;
+ }
+
+ case Gesture::Pinch:
+ {
+ retVal = pinch;
+ break;
+ }
+
+ case Gesture::Tap:
+ {
+ retVal = tap;
+ break;
+ }
+
+ default:
+ retVal = invalid;
+ break;
+ }
+
+ return retVal;
+};
+#endif // DEBUG_ENABLED
+
+const float MINIMUM_DISTANCE_DELTA_DIVISOR = 85.0f;
+} // unnamed namespace
+
+GestureManager::GestureManager(CoreEventInterface& coreEventInterface, Vector2 screenSize,CallbackManager* callbackManager, EnvironmentOptions& environmentOptions)
+: mCoreEventInterface( coreEventInterface ),
+ mScreenSize( screenSize ),
+ mCallbackManager( callbackManager ),
+ mEnvironmentOptions( environmentOptions ),
+ mMinimumDistanceDelta(-1.0f),
+ mRunning( true ) // This allows gestures to be created before Adaptor::Start() is called e.g. by Indicator
+{
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Creating GestureManager\n" );
+}
+
+GestureManager::~GestureManager()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Destroying GestureManager\n" );
+}
+
+void GestureManager::SendEvent(const Integration::TouchEvent& event)
+{
+ if (mRunning)
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SendEvent: START\n" );
+
+ // gestures can be added / deleted during SendEvent so we make a copy of the container.
+ // the gestures are reference counted, so unused gesture detectors will be deleted when
+ // the local variable detectors goes out of scope.
+ GestureDetectorContainer detectors( mGestureDetectors );
+
+ // Send the event to all gesture detectors.
+ for ( GestureDetectorContainer::iterator iter = detectors.begin(), endIter = detectors.end(); iter != endIter; ++iter )
+ {
+ (*iter)->SendEvent(event);
+ }
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SendEvent: END\n" );
+ }
+}
+
+void GestureManager::Stop()
+{
+ if (mRunning)
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Stop\n" );
+
+ mGestureDetectors.clear();
+ mRunning = false;
+ }
+}
+
+void GestureManager::SetMinimumPinchDistance(float distance)
+{
+ mMinimumDistanceDelta = distance;
+ for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
+ {
+ if ( ( *iter )->GetType() == Gesture::Pinch )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "Set Minimum Pinch Distance: %f\n", distance );
+ PinchGestureDetector* gestureDetector = static_cast<PinchGestureDetector*>(iter->Get());
+ gestureDetector->SetMinimumPinchDistance(distance);
+ break;
+ }
+ }
+}
+
+void GestureManager::Register(const Integration::GestureRequest& request)
+{
+ if (mRunning)
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "Creating %s Detector\n", GetGestureTypeString( request.type ) );
+
+ switch (request.type)
+ {
+ case Gesture::LongPress:
+ {
+ GestureDetectorPtr gesture = new LongPressGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::LongPressGestureRequest&>(request));
+ mGestureDetectors.push_back(gesture);
+ break;
+ }
+
+ case Gesture::Pan:
+ {
+ GestureDetectorPtr gesture = new PanGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::PanGestureRequest&>(request), mEnvironmentOptions);
+ mGestureDetectors.push_back(gesture);
+ break;
+ }
+
+ case Gesture::Pinch:
+ {
+ float minPinchDistance = mMinimumDistanceDelta >= 0.0f ? mMinimumDistanceDelta : (mScreenSize.height / MINIMUM_DISTANCE_DELTA_DIVISOR);
+ GestureDetectorPtr gesture = new PinchGestureDetector(mCoreEventInterface, mScreenSize, minPinchDistance);
+ mGestureDetectors.push_back(gesture);
+ break;
+ }
+
+ case Gesture::Tap:
+ {
+ GestureDetectorPtr gesture = new TapGestureDetector(mCoreEventInterface, mScreenSize, static_cast<const Integration::TapGestureRequest&>(request));
+ mGestureDetectors.push_back(gesture);
+ break;
+ }
+
+ default:
+ DALI_ASSERT_DEBUG(false);
+ break;
+ }
+ }
+}
+
+void GestureManager::Unregister(const Integration::GestureRequest& request)
+{
+ if ( mRunning )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "Unregister: %s\n", GetGestureTypeString( request.type ) );
+
+ DeleteGestureDetector( request.type );
+
+ }
+}
+
+void GestureManager::Update(const Integration::GestureRequest& request)
+{
+ for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter < endIter; ++iter )
+ {
+ if ( (*iter)->GetType() == request.type )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "Update: %s\n", GetGestureTypeString( request.type ) );
+ (*iter)->Update( request );
+ break;
+ }
+ }
+}
+
+void GestureManager::DeleteGestureDetector( Gesture::Type type )
+{
+ for( GestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
+ {
+ if ( ( *iter )->GetType() == type )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "DeleteGestureDetector: %s\n", GetGestureTypeString( type ) );
+ mGestureDetectors.erase( iter );
+ break;
+ }
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_GESTURE_MANAGER_H__
+#define __DALI_INTERNAL_GESTURE_MANAGER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/math/vector2.h>
+#include <dali/integration-api/gesture-manager.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+struct TouchEvent;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CallbackManager;
+class CoreEventInterface;
+class EnvironmentOptions;
+
+/**
+ * Implementation of the Integration::GestureManager.
+ *
+ * Contains a list of adaptor gesture detectors. It passes touch events to each required detector which
+ * in turn process them to determine if their corresponding gesture has occurred.
+ */
+class GestureManager : public Integration::GestureManager
+{
+public:
+
+ /**
+ * Constructor.
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] screenSize The size of the screen.
+ * @param[in] callbackManager used to install callbacks
+ * @param[in] environmentOptions Environment Options
+ */
+ GestureManager(CoreEventInterface& coreEventInterface, Vector2 screenSize, CallbackManager* callbackManager, EnvironmentOptions& environmentOptions);
+
+ /**
+ * The destructor
+ */
+ virtual ~GestureManager();
+
+public:
+
+ /**
+ * Used by the event handler to send touch events to the Gesture Manager.
+ * @param[in] event The latest touch event.
+ */
+ void SendEvent(const Integration::TouchEvent& event);
+
+ /**
+ * Used by the event handler to stop the GestureManager detection.
+ */
+ void Stop();
+
+ /**
+ * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
+ * trigger a pinch gesture
+ *
+ * @param[in] distance The minimum pinch distance in pixels
+ */
+ void SetMinimumPinchDistance(float distance);
+
+public: // GestureManager overrides
+
+ /**
+ * copydoc Dali::Integration::GestureManager::Register(const Integration::GestureRequest&)
+ */
+ virtual void Register(const Integration::GestureRequest& request);
+
+ /**
+ * copydoc Dali::Integration::GestureManager::Unregister(const Integration::GestureRequest&)
+ */
+ virtual void Unregister(const Integration::GestureRequest& request);
+
+ /**
+ * copydoc Dali::Integration::GestureManager::Unregister(const Integration::GestureRequest&)
+ */
+ virtual void Update(const Integration::GestureRequest& request);
+
+private:
+
+ /**
+ * Used to delete the gesture detector of the given type.
+ */
+ void DeleteGestureDetector( Gesture::Type type );
+
+private:
+
+ typedef std::vector<GestureDetectorPtr> GestureDetectorContainer;
+
+ CoreEventInterface& mCoreEventInterface;
+ GestureDetectorContainer mGestureDetectors;
+ Vector2 mScreenSize;
+ CallbackManager* mCallbackManager;
+ EnvironmentOptions& mEnvironmentOptions;
+ float mMinimumDistanceDelta; ///< The minimum distance before a pinch is applicable. (-1.0f means pinch detector uses default value)
+ bool mRunning; ///< States whether the GestureManager is running or not.
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_GESTURE_MANAGER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/input/common/imf-manager-factory.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class ImfManager;
+
+namespace ImfManagerFactory
+{
+
+// Factory function creating new IMFManager
+// Symbol exists but may be overriden during linking
+
+__attribute__((weak))
+Dali::ImfManager CreateImfManager()
+{
+ // return empty handle if ImgManager not implemented
+ return Dali::ImfManager();
+}
+
+}
+}
+}
+
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_FACTORY_H
+#define DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_FACTORY_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class ImfManager;
+
+namespace ImfManagerFactory
+{
+
+// Factory function creating new IMFManager
+// Symbol exists but may be overriden during linking
+__attribute__((weak))
+Dali::ImfManager CreateImfManager();
+
+}
+}
+}
+
+}
+
+#endif //DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_FACTORY_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/input/common/imf-manager-impl.h>
+#include <dali/internal/input/common/imf-manager-factory.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+
+bool ImfManager::IsAvailable()
+{
+ bool available(false);
+
+ Dali::SingletonService service(SingletonService::Get());
+ if(service)
+ {
+ available = service.GetSingleton(typeid(Dali::ImfManager));
+ }
+
+ return available;
+}
+
+Dali::ImfManager ImfManager::Get()
+{
+ return Dali::Internal::Adaptor::ImfManagerFactory::CreateImfManager();
+}
+
+ImfManager::~ImfManager()
+{}
+
+void ImfManager::NotifyCursorPosition()
+{}
+
+void ImfManager::ConnectCallbacks()
+{}
+
+void ImfManager::DisconnectCallbacks()
+{}
+
+void ImfManager::Activate()
+{}
+
+void ImfManager::Deactivate()
+{}
+
+void ImfManager::Reset()
+{}
+
+ImfContext *ImfManager::GetContext()
+{
+ return nullptr;
+}
+
+bool ImfManager::RestoreAfterFocusLost() const
+{
+ return false;
+}
+
+void ImfManager::SetRestoreAfterFocusLost(bool toggle)
+{}
+
+void ImfManager::PreEditChanged(void *data, ImfContext *imfContext, void *event_info)
+{}
+
+void ImfManager::CommitReceived(void *data, ImfContext *imfContext, void *event_info)
+{}
+
+bool ImfManager::RetrieveSurrounding(void *data, ImfContext *imfContext, char **text, int *cursorPosition)
+{
+ return false;
+}
+
+void ImfManager::DeleteSurrounding(void *data, ImfContext *imfContext, void *event_info)
+{}
+
+void ImfManager::SendPrivateCommand(void *data, ImfContext *imfContext, void *event_info)
+{}
+
+void ImfManager::SetCursorPosition(unsigned int cursorPosition)
+{}
+
+unsigned int ImfManager::GetCursorPosition() const
+{
+ return 0;
+}
+
+void ImfManager::SetSurroundingText(const std::string &text)
+{}
+
+const std::string &ImfManager::GetSurroundingText() const
+{
+ static std::string str("");
+ return str;
+}
+
+void ImfManager::NotifyTextInputMultiLine(bool multiLine)
+{}
+
+Dali::ImfManager::TextDirection ImfManager::GetTextDirection()
+{
+ return Dali::ImfManager::TextDirection();
+}
+
+Dali::Rect<int> ImfManager::GetInputMethodArea()
+{
+ return Dali::Rect<int>();
+}
+
+void ImfManager::ApplyOptions(const InputMethodOptions &options)
+{}
+
+void ImfManager::SetInputPanelData(const std::string &data)
+{}
+
+void ImfManager::GetInputPanelData(std::string &data)
+{}
+
+Dali::ImfManager::State ImfManager::GetInputPanelState()
+{
+ return Dali::ImfManager::State();
+}
+
+void ImfManager::SetReturnKeyState(bool visible)
+{}
+
+void ImfManager::AutoEnableInputPanel(bool enabled)
+{}
+
+void ImfManager::ShowInputPanel()
+{}
+
+void ImfManager::HideInputPanel()
+{}
+
+Dali::ImfManager::KeyboardType ImfManager::GetKeyboardType()
+{
+ return Dali::ImfManager::KeyboardType();
+}
+
+std::string ImfManager::GetInputPanelLocale()
+{
+ return std::string();
+}
+
+}
+}
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_H
+#define DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/integration-api/events/key-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+
+#include <memory>
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+using ImfContext = void;
+
+class DALI_IMPORT_API ImfManager : public Dali::BaseObject
+{
+
+public:
+
+ using ImfManagerSignalType = Dali::ImfManager::ImfManagerSignalType;
+ using ImfEventSignalType = Dali::ImfManager::ImfEventSignalType;
+ using ImfStatusSignalType = Dali::ImfManager::StatusSignalType;
+ using ImfVoidSignalType = Dali::ImfManager::VoidSignalType;
+ using ImfKeyboardTypeSignalType = Dali::ImfManager::KeyboardTypeSignalType;
+ using ImfLanguageChangedSignalType = Dali::ImfManager::LanguageChangedSignalType;
+ using ImfKeyboardResizedSignalType = Dali::ImfManager::KeyboardResizedSignalType;
+
+public:
+
+ /**
+ * Check whether the ImfManager is available.
+ * @return true if available, false otherwise
+ */
+ static bool IsAvailable();
+
+ /**
+ * Get the IMF manager instance, it creates the instance if it has not already been created.
+ * Internally, a check should be made using IsAvailable() before this is called as we do not want
+ * to create an instance if not needed by applications.
+ * @see IsAvailable()
+ */
+ static Dali::ImfManager Get();
+
+ /**
+ * Connect Callbacks required for IMF.
+ * If you don't connect imf callbacks, you can't get the key events.
+ * The events are PreeditChanged, Commit, DeleteSurrounding and PrivateCommand.
+ */
+ virtual void ConnectCallbacks();
+
+ /**
+ * Disconnect Callbacks attached to imf context.
+ */
+ virtual void DisconnectCallbacks();
+
+ /**
+ * @copydoc Dali::ImfManager::Activate()
+ */
+ virtual void Activate();
+
+ /**
+ * @copydoc Dali::ImfManager::Deactivate()
+ */
+ virtual void Deactivate();
+
+ /**
+ * @copydoc Dali::ImfManager::Reset()
+ */
+ virtual void Reset();
+
+ /**
+ * @copydoc Dali::ImfManager::GetContext()
+ */
+ virtual ImfContext* GetContext();
+
+ /**
+ * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
+ */
+ virtual bool RestoreAfterFocusLost() const;
+
+ /**
+ * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
+ */
+ virtual void SetRestoreAfterFocusLost( bool toggle );
+
+ /**
+ * @copydoc Dali::ImfManager::PreEditChanged()
+ */
+ virtual void PreEditChanged( void *data, ImfContext* imfContext, void *event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ virtual void CommitReceived( void *data, ImfContext* imfContext, void *event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ /*Eina_Bool*/
+ virtual bool RetrieveSurrounding( void *data, ImfContext* imfContext, char** text, int* cursorPosition ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteSurrounding()
+ */
+ virtual void DeleteSurrounding( void *data, ImfContext* imfContext, void *event_info ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::SendPrivateCommand()
+ */
+ virtual void SendPrivateCommand( void* data, ImfContext* imfContext, void* event_info ) ;
+
+ // Cursor related
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ virtual void NotifyCursorPosition();
+
+ /**
+ * @copydoc Dali::ImfManager::SetCursorPosition()
+ */
+ virtual void SetCursorPosition( unsigned int cursorPosition ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetCursorPosition()
+ */
+ virtual unsigned int GetCursorPosition() const;
+
+ /**
+ * @copydoc Dali::ImfManager::SetSurroundingText()
+ */
+ virtual void SetSurroundingText( const std::string& text ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetSurroundingText()
+ */
+ virtual const std::string& GetSurroundingText() const;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
+ */
+ virtual void NotifyTextInputMultiLine( bool multiLine ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetTextDirection()
+ */
+ virtual Dali::ImfManager::TextDirection GetTextDirection() ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputMethodArea()
+ */
+ virtual Dali::Rect<int> GetInputMethodArea() ;
+
+ /**
+ * @copydoc Dali::ImfManager::ApplyOptions()
+ */
+ virtual void ApplyOptions( const InputMethodOptions& options ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::SetInputPanelData()
+ */
+ virtual void SetInputPanelData( const std::string& data ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelData()
+ */
+ virtual void GetInputPanelData( std::string& data ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelState()
+ */
+ virtual Dali::ImfManager::State GetInputPanelState() ;
+
+ /**
+ * @copydoc Dali::ImfManager::SetReturnKeyState()
+ */
+ virtual void SetReturnKeyState( bool visible ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::AutoEnableInputPanel()
+ */
+ virtual void AutoEnableInputPanel( bool enabled ) ;
+
+ /**
+ * @copydoc Dali::ImfManager::ShowInputPanel()
+ */
+ virtual void ShowInputPanel() ;
+
+ /**
+ * @copydoc Dali::ImfManager::HideInputPanel()
+ */
+ virtual void HideInputPanel() ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetKeyboardType()
+ */
+ virtual Dali::ImfManager::KeyboardType GetKeyboardType() ;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelLocale()
+ */
+ virtual std::string GetInputPanelLocale() ;
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::ImfManager::ActivatedSignal()
+ */
+ ImfManagerSignalType& ActivatedSignal() { return mActivatedSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::EventReceivedSignal()
+ */
+ ImfEventSignalType& EventReceivedSignal() { return mEventSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::StatusChangedSignal()
+ */
+ ImfStatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::ResizedSignal()
+ */
+ ImfKeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::LanguageChangedSignal()
+ */
+ ImfLanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; }
+
+ /**
+ * @copydoc Dali::ImfManager::KeyboardTypeChangedSignal()
+ */
+ ImfKeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; }
+
+protected:
+
+ /**
+ * Constructor
+ */
+ ImfManager() = default;
+
+ /**
+ * Destructor
+ */
+ ~ImfManager() override;
+
+private:
+
+ ImfManager( const ImfManager& ) = delete;
+ ImfManager& operator=( ImfManager& ) = delete;
+
+protected:
+
+ ImfManagerSignalType mActivatedSignal;
+ ImfEventSignalType mEventSignal;
+ ImfStatusSignalType mKeyboardStatusSignal;
+ ImfKeyboardResizedSignalType mKeyboardResizeSignal;
+ ImfLanguageChangedSignalType mKeyboardLanguageChangedSignal;
+ ImfKeyboardTypeSignalType mKeyboardTypeChangedSignal;
+
+public:
+
+ inline static Internal::Adaptor::ImfManager& GetImplementation(Dali::ImfManager& imfManager)
+ {
+ DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
+
+ BaseObject& handle = imfManager.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::ImfManager&>(handle);
+ }
+
+ inline static const Internal::Adaptor::ImfManager& GetImplementation(const Dali::ImfManager& imfManager)
+ {
+ DALI_ASSERT_ALWAYS( imfManager && "ImfManager handle is empty" );
+
+ const BaseObject& handle = imfManager.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::ImfManager&>(handle);
+ }
+
+};
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_H
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/key-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dlfcn.h>
+#include <map>
+#include <string.h>
+#include <iostream>
+
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace KeyLookup
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gKeyExtensionLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEY_EXTENSION");
+#endif
+
+// Path for loading extension keys
+#if _GLIBCXX_USE_CXX11_ABI
+const char* KEY_EXTENSION_PLUGIN_SO( "libdali-key-extension.so" );
+#else
+const char* KEY_EXTENSION_PLUGIN_SO( "libdali-key-extension-cxx03.so" );
+#endif
+
+class KeyMap
+{
+ public:
+
+ KeyMap():
+ mExtensionKeyLookupTable(NULL),
+ mPlugin(NULL),
+ mHandle(NULL),
+ mCreateKeyExtensionPluginPtr(NULL),
+ mDestroyKeyExtensionPluginPtr(NULL),
+ mLookup( cmpString ),
+ mExtensionLookup( cmpString ),
+ mExtensionLookupCount(0),
+ mIsLookupTableInitialized( false ),
+ mIsExtensionLookupTableInitialized( false )
+ {
+ }
+
+ ~KeyMap()
+ {
+ if( mHandle != NULL )
+ {
+ if( mDestroyKeyExtensionPluginPtr != NULL )
+ {
+ mDestroyKeyExtensionPluginPtr( mPlugin );
+ }
+
+ dlclose( mHandle );
+ }
+ }
+
+ int GetDaliKeyEnum( const char* keyName )
+ {
+ // If lookup table is not initialized, initialize lookup table
+ if( !mIsLookupTableInitialized )
+ {
+ InitializeLookupTable();
+ }
+
+ Lookup::const_iterator i = mLookup.find( keyName );
+
+ if( i == mLookup.end() )
+ {
+ // If cannot find target, find it at the extension
+ // If extension lookup table is not initialized, initialize extension lookup table
+ if( !mIsExtensionLookupTableInitialized )
+ {
+ InitializeExtensionLookupTable();
+ }
+
+ // Find at extension
+ i = mExtensionLookup.find( keyName );
+
+ if( i == mExtensionLookup.end() )
+ {
+ return -1;
+ }
+ else
+ {
+ return (*i).second.first;
+ }
+ }
+ else
+ {
+ return (*i).second.first;
+ }
+ }
+
+ const char* GetKeyName( int daliKeyCode )
+ {
+ // If lookup table is not initialized, initialize lookup table
+ if( !mIsLookupTableInitialized )
+ {
+ InitializeLookupTable();
+ }
+
+ for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i )
+ {
+ if( KeyLookupTable[i].daliKeyCode == daliKeyCode )
+ {
+ return KeyLookupTable[i].keyName;
+ }
+ }
+
+ // If extension lookup table is not initialized, initialize extension lookup table
+ if( !mIsExtensionLookupTableInitialized )
+ {
+ InitializeExtensionLookupTable();
+ }
+
+ for( size_t i = 0; i < mExtensionLookupCount ; ++i )
+ {
+ if( mExtensionKeyLookupTable[i].daliKeyCode == daliKeyCode )
+ {
+ return mExtensionKeyLookupTable[i].keyName;
+ }
+ }
+
+ return NULL;
+ }
+
+ bool IsDeviceButton( const char* keyName )
+ {
+ // If lookup table is not initialized, initialize lookup table
+ if( !mIsLookupTableInitialized )
+ {
+ InitializeLookupTable();
+ }
+
+ Lookup::const_iterator i = mLookup.find( keyName );
+ if( i == mLookup.end() )
+ {
+ // If cannot find target, find it at the extension.
+ // If extension lookup table is not initialized, initialize extension lookup table
+ if( !mIsExtensionLookupTableInitialized )
+ {
+ InitializeExtensionLookupTable();
+ }
+
+ // Find at extension
+ i = mExtensionLookup.find( keyName );
+
+ if( i == mExtensionLookup.end() )
+ {
+ return false;
+ }
+ else
+ {
+ return (*i).second.second;
+ }
+ }
+ else
+ {
+ return (*i).second.second;
+ }
+
+ return false;
+ }
+
+
+ private:
+
+ void InitializeLookupTable()
+ {
+ // create the lookup
+ for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i )
+ {
+ mLookup[ KeyLookupTable[i].keyName ] = DaliKeyType( KeyLookupTable[i].daliKeyCode, KeyLookupTable[i].deviceButton );
+ }
+
+ mIsLookupTableInitialized = true;
+ }
+
+ void InitializeExtensionLookupTable()
+ {
+ // Try to load extension keys
+ char* error = NULL;
+ mHandle = dlopen( KEY_EXTENSION_PLUGIN_SO, RTLD_NOW );
+ error = dlerror();
+
+ if( mHandle == NULL )
+ {
+ DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get handle from libdali-key-extension.so\n" );
+ return;
+ }
+
+ if( error != NULL )
+ {
+ DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "dlopen got error: %s \n", error );
+ return;
+ }
+
+ mCreateKeyExtensionPluginPtr = reinterpret_cast< CreateKeyExtensionPluginFunction >( dlsym( mHandle, "CreateKeyExtensionPlugin" ) );
+ if( mCreateKeyExtensionPluginPtr == NULL )
+ {
+ DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get CreateKeyExtensionPlugin function\n" );
+ return;
+ }
+
+ mPlugin = mCreateKeyExtensionPluginPtr();
+ if( mPlugin == NULL )
+ {
+ DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to create plugin object\n" );
+ return;
+ }
+
+ mDestroyKeyExtensionPluginPtr = reinterpret_cast< DestroyKeyExtensionPluginFunction >( dlsym( mHandle, "DestroyKeyExtensionPlugin" ) );
+ if( mDestroyKeyExtensionPluginPtr == NULL )
+ {
+ DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get DestroyKeyExtensionPlugin function\n" );
+ return;
+ }
+
+ mExtensionKeyLookupTable = mPlugin->GetKeyLookupTable();
+ mExtensionLookupCount = mPlugin->GetKeyLookupTableCount();
+
+ // Add extension keys to lookup
+ for( size_t i = 0; i < mExtensionLookupCount ; ++i )
+ {
+ mExtensionLookup[ mExtensionKeyLookupTable[i].keyName ] = DaliKeyType( mExtensionKeyLookupTable[i].daliKeyCode, mExtensionKeyLookupTable[i].deviceButton );
+ }
+
+ mIsExtensionLookupTableInitialized = true;
+ }
+
+ /**
+ * compare function, to compare string by pointer
+ */
+ static bool cmpString( const char* a, const char* b)
+ {
+ return strcmp(a, b) < 0;
+ }
+
+ KeyExtensionPlugin::KeyLookup* mExtensionKeyLookupTable; ///< Lookup table for extension keys
+ Dali::KeyExtensionPlugin* mPlugin; ///< Key extension plugin handle
+ void* mHandle; ///< Handle for the loaded library
+ typedef Dali::KeyExtensionPlugin* (*CreateKeyExtensionPluginFunction)(); ///< Type of function pointer to get KeyExtensionPlugin object
+ typedef void (*DestroyKeyExtensionPluginFunction)( Dali::KeyExtensionPlugin* plugin ); ///< Type of function pointer to delete KeyExtensionPlugin object
+ CreateKeyExtensionPluginFunction mCreateKeyExtensionPluginPtr; ///< Function pointer to get KeyExtensionPlugin object
+ DestroyKeyExtensionPluginFunction mDestroyKeyExtensionPluginPtr; ///< Function pointer to delete KeyExtensionPlugin object
+
+ typedef std::pair< int, bool > DaliKeyType;
+ typedef std::map<const char* /* key name */, DaliKeyType /* key code */, bool(*) ( char const* a, char const* b) > Lookup;
+ Lookup mLookup;
+ Lookup mExtensionLookup;
+ size_t mExtensionLookupCount; ///< count of extension lookup table
+ bool mIsLookupTableInitialized; ///< flag for basic lookup table initialization
+ bool mIsExtensionLookupTableInitialized; ///< flag for extension lookup table initialization
+};
+KeyMap globalKeyLookup;
+
+} // un-named name space
+
+bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey)
+{
+ int key = globalKeyLookup.GetDaliKeyEnum( keyEvent.keyPressedName.c_str() );
+ return daliKey == key;
+}
+
+bool IsDeviceButton( const char* keyName )
+{
+ return globalKeyLookup.IsDeviceButton( keyName );
+}
+
+const char* GetKeyName( Dali::KEY daliKey )
+{
+ return globalKeyLookup.GetKeyName( daliKey );
+}
+
+int GetDaliKeyCode( const char* keyName )
+{
+ return globalKeyLookup.GetDaliKeyEnum( keyName );
+}
+
+} // namespace KeyLookup
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_KEY_IMPL_H__
+#define __DALI_KEY_IMPL_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/key.h>
+#include <dali/devel-api/adaptor-framework/key-extension-plugin.h>
+#include <dali/devel-api/adaptor-framework/key-devel.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of the Key matching
+ */
+namespace KeyLookup
+{
+
+struct KeyLookup
+{
+ const char* keyName; ///< XF86 key name
+ const Dali::KEY daliKeyCode; ///< Dali key code
+ const bool deviceButton; ///< Whether the key is from a button on the device
+};
+
+extern KeyLookup KeyLookupTable[];
+extern const std::size_t KEY_LOOKUP_COUNT;
+
+/**
+ * @copydoc Dali::IsKey()
+ */
+bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey );
+
+/**
+ * Check if a the given key name string is a button on the device itself.
+ * @param keyName A pointer to the key name
+ * @return true if the key is matched, false if not
+ */
+bool IsDeviceButton( const char* keyName );
+
+/**
+ * Get a key name from a dali key code.
+ * @param daliKey The dali key code
+ * @return The key name. NULL if the daliKey does not exist in the supported key lookup table.
+ */
+const char* GetKeyName( Dali::KEY daliKey );
+
+/**
+ * @brief Get the key code from a key name.
+ * @param[in] keyName The key name
+ * @return The key code. -1 if the daliKey does not exist in the supported key lookup table.
+ */
+int GetDaliKeyCode( const char* keyName );
+
+} // namespace KeyLookup
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_KEY_IMPL_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/long-press-gesture-detector.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+
+#include <dali/public-api/events/touch-point.h>
+#include <dali/public-api/math/vector2.h>
+
+#include <dali/integration-api/events/gesture-requests.h>
+#include <dali/integration-api/events/long-press-gesture-event.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+
+#include <dali/internal/system/generic/system-settings.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/core-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+// TODO: Set these according to DPI
+const float MAXIMUM_MOTION_ALLOWED = 60.0f;
+// TODO: Set this time according to system setting (vconf)
+const unsigned long LONG_PRESS_TIME = 500u;
+} // unnamed namespace
+
+LongPressGestureDetector::LongPressGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::LongPressGestureRequest& request)
+: GestureDetector(screenSize, Gesture::LongPress),
+ mCoreEventInterface(coreEventInterface),
+ mState(Clear),
+ mMinimumTouchesRequired(request.minTouches),
+ mMaximumTouchesRequired(request.maxTouches),
+ mTouchTime(0),
+ mTimerSlot( this )
+{
+ mTimer = Dali::Timer::New(GetSystemValue());
+ mTimer.TickSignal().Connect( mTimerSlot, &LongPressGestureDetector::TimerCallback );
+}
+
+LongPressGestureDetector::~LongPressGestureDetector()
+{
+}
+
+void LongPressGestureDetector::SendEvent(const Integration::TouchEvent& event)
+{
+ unsigned int pointCount( event.GetPointCount() );
+
+ switch (mState)
+ {
+ // Clear: Wait till one point touches the screen before starting timer.
+ case Clear:
+ {
+ const Integration::Point& point = event.points[0];
+
+ if ( point.GetState() == PointState::DOWN )
+ {
+ mTouchPositions.clear();
+ mTouchPositions[point.GetDeviceId()] = point.GetScreenPosition();
+
+ mTouchTime = event.time;
+
+ mTimer.SetInterval(GetSystemValue());
+ mTimer.Start();
+
+ // A long press gesture may be possible, tell Core about this and change state to Touched.
+ mState = Touched;
+ EmitGesture( Gesture::Possible );
+ }
+
+ break;
+ }
+
+ // Touched: Monitor movement and addition/removal of points.
+ case Touched:
+ {
+ if (pointCount > mMaximumTouchesRequired)
+ {
+ // A long press did not occur, tell Core that it was cancelled and change state to Failed.
+ EmitGesture( Gesture::Cancelled );
+ mTouchPositions.clear();
+ mTimer.Stop();
+ mState = Failed;
+ break;
+ }
+
+ bool endLoop(false);
+
+ for ( Integration::PointContainerConstIterator iter = event.points.begin(), endIter = event.points.end();
+ iter != endIter && !endLoop; ++iter)
+ {
+ switch( iter->GetState() )
+ {
+ // add point.
+ case PointState::DOWN:
+ {
+ mTouchPositions[iter->GetDeviceId()] = iter->GetScreenPosition();
+ break;
+ }
+
+ // remove point.
+ case PointState::UP:
+ case PointState::INTERRUPTED:
+ {
+ // System has interrupted us, long press is not possible, inform Core
+ EmitGesture( Gesture::Cancelled );
+ mTouchPositions.clear();
+ mTimer.Stop();
+ mState = ( pointCount == 1 ) ? Clear : Failed; // Change state to Clear if only one point, Failed otherwise.
+ endLoop = true;
+ break;
+ }
+
+ case PointState::MOTION:
+ {
+ const Vector2 touchPosition( mTouchPositions[iter->GetDeviceId()] - iter->GetScreenPosition() );
+ float distanceSquared = touchPosition.LengthSquared();
+
+ if (distanceSquared > ( MAXIMUM_MOTION_ALLOWED * MAXIMUM_MOTION_ALLOWED ) )
+ {
+ // We have moved more than the allowable motion for a long press gesture. Inform Core and change state to Failed.
+ EmitGesture( Gesture::Cancelled );
+ mTimer.Stop();
+ mState = Failed;
+ endLoop = true;
+ }
+ break;
+ }
+
+ case PointState::STATIONARY:
+ case PointState::LEAVE:
+ {
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ // Failed/Finished: Monitor the touches, waiting for all touches to be released.
+ case Failed:
+ case Finished:
+ {
+ // eventually the final touch point will be removed, marking the end of this gesture.
+ if ( pointCount == 1 )
+ {
+ PointState::Type primaryPointState = event.points[0].GetState();
+
+ if ( (primaryPointState == PointState::UP) || (primaryPointState == PointState::INTERRUPTED) )
+ {
+ if(mState == Finished)
+ {
+ // When the last touch point is lifted, we should inform the Core that the Long press has finished.
+ EmitGesture(Gesture::Finished);
+ }
+ mTouchPositions.clear();
+ mState = Clear; // Reset state to clear when last touch point is lifted.
+ }
+ }
+ break;
+ }
+ }
+}
+
+void LongPressGestureDetector::Update(const Integration::GestureRequest& request)
+{
+ const Integration::LongPressGestureRequest& longPress = static_cast<const Integration::LongPressGestureRequest&>(request);
+
+ mMinimumTouchesRequired = longPress.minTouches;
+ mMaximumTouchesRequired = longPress.maxTouches;
+}
+
+bool LongPressGestureDetector::TimerCallback()
+{
+ EmitGesture(Gesture::Started);
+
+ mState = Finished;
+
+ // There is no touch event at this time, so ProcessEvents must be called directly
+ mCoreEventInterface.ProcessCoreEvents();
+
+ return false;
+}
+
+void LongPressGestureDetector::EmitGesture(Gesture::State state)
+{
+ unsigned int touchPoints ( mTouchPositions.size() );
+
+ // We should tell Core about the Possible and Cancelled states regardless of whether we have satisfied long press requirements.
+ if ( (state == Gesture::Possible) ||
+ (state == Gesture::Cancelled) ||
+ (touchPoints >= mMinimumTouchesRequired) )
+ {
+ Integration::LongPressGestureEvent longPress( state );
+ longPress.numberOfTouches = touchPoints;
+
+ for (std::map<int, Vector2>::iterator iter = mTouchPositions.begin(), endIter = mTouchPositions.end();
+ iter != endIter; ++iter)
+ {
+ longPress.point += iter->second;
+ }
+ longPress.point /= touchPoints;
+
+ longPress.time = mTouchTime;
+ if ( state != Gesture::Possible )
+ {
+ longPress.time += GetSystemValue();
+ }
+
+ mCoreEventInterface.QueueCoreEvent(longPress);
+ }
+}
+
+int LongPressGestureDetector::GetSystemValue()
+{
+ return GetLongPressTime( LONG_PRESS_TIME );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
+#define __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <map>
+#include <dali/public-api/adaptor-framework/timer.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+struct TouchEvent;
+struct LongPressGestureRequest;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CoreEventInterface;
+
+/**
+ * When given a set of touch events, this detector attempts to determine if a long press gesture has taken place.
+ * Emits a LongPressGestureEvent (state = Started) when a long press has been detected (Touch held down for more than duration).
+ * Emits a further LongPressGestureEvent (state = Finished) when a long press has been completed (Touch Release).
+ */
+class LongPressGestureDetector : public GestureDetector
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] screenSize The size of the screen.
+ * @param[in] request The long press gesture request.
+ */
+ LongPressGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::LongPressGestureRequest& request);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~LongPressGestureDetector();
+
+public:
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
+ */
+ virtual void SendEvent(const Integration::TouchEvent& event);
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
+ */
+ virtual void Update(const Integration::GestureRequest& request);
+
+private:
+
+ /**
+ * Timer Callback
+ * @return will return false; one-shot timer.
+ */
+ bool TimerCallback();
+
+ /**
+ * Emits the long press gesture if all conditions are applicable.
+ * @param[in] state The state of this gesture event.
+ */
+ void EmitGesture(Gesture::State state);
+
+ /**
+ * Get current system setting value for tap and hold gesture
+ * @return system value for tap and hold gesture [ms]
+ */
+ int GetSystemValue();
+
+private:
+
+ /**
+ * Internal state machine.
+ */
+ enum State
+ {
+ Clear, ///< No gesture detected.
+ Touched, ///< User is touching the screen.
+ Failed, ///< Gesture has failed.
+ Finished ///< Gesture has been detected and sent.
+ };
+
+ CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
+ State mState; ///< The current state of the detector.
+
+ unsigned int mMinimumTouchesRequired; ///< The minimum touches required before emitting a long press.
+ unsigned int mMaximumTouchesRequired; ///< The maximum touches allowable. Any more and a long press is not emitted.
+
+ std::map<int, Vector2> mTouchPositions; ///< A map with all the touch down positions.
+ unsigned long mTouchTime; ///< The time we first pressed down.
+
+ Dali::Timer mTimer; ///< The timer used to determine a long press.
+ SlotDelegate< LongPressGestureDetector > mTimerSlot;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_LONG_PRESS_GESTURE_DETECTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/pan-gesture-detector-base.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+
+#include <dali/public-api/events/touch-point.h>
+
+#include <dali/integration-api/events/gesture-requests.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const float MINIMUM_MOTION_DISTANCE_BEFORE_PAN( 15.0f );
+const float MINIMUM_MOTION_DISTANCE_BEFORE_PAN_SQUARED( MINIMUM_MOTION_DISTANCE_BEFORE_PAN * MINIMUM_MOTION_DISTANCE_BEFORE_PAN );
+const float MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO( 2.0f / 3.0f );
+const unsigned long MAXIMUM_TIME_DIFF_ALLOWED( 500 );
+const unsigned long MINIMUM_TIME_BEFORE_THRESHOLD_ADJUSTMENTS( 100 );
+const unsigned int MINIMUM_MOTION_EVENTS_BEFORE_PAN(2);
+} // unnamed namespace
+
+PanGestureDetectorBase::PanGestureDetectorBase(Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions* environmentOptions)
+: GestureDetector( screenSize, Gesture::Pan ),
+ mState( Clear ),
+ mThresholdAdjustmentsRemaining( 0 ),
+ mThresholdTotalAdjustments( MINIMUM_MOTION_DISTANCE_BEFORE_PAN * MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO ),
+ mPrimaryTouchDownTime( 0 ),
+ mMinimumTouchesRequired( request.minTouches ),
+ mMaximumTouchesRequired( request.maxTouches ),
+ mMinimumDistanceSquared( MINIMUM_MOTION_DISTANCE_BEFORE_PAN_SQUARED ),
+ mMinimumMotionEvents( MINIMUM_MOTION_EVENTS_BEFORE_PAN ),
+ mMotionEvents( 0 )
+{
+ if ( environmentOptions )
+ {
+ int minimumDistance = environmentOptions->GetMinimumPanDistance();
+ if ( minimumDistance >= 0 )
+ {
+ mMinimumDistanceSquared = minimumDistance * minimumDistance;
+
+ // Usually, we do not want to apply the threshold straight away, but phased over the first few pans
+ // Set our distance to threshold adjustments ratio here.
+ mThresholdTotalAdjustments = minimumDistance * MINIMUM_MOTION_DISTANCE_TO_THRESHOLD_ADJUSTMENTS_RATIO;
+ }
+
+ int minimumEvents = environmentOptions->GetMinimumPanEvents();
+ if ( minimumEvents >= 1 )
+ {
+ mMinimumMotionEvents = minimumEvents - 1; // Down is the first event
+ }
+ }
+}
+
+PanGestureDetectorBase::~PanGestureDetectorBase()
+{
+}
+
+void PanGestureDetectorBase::SendEvent(const Integration::TouchEvent& event)
+{
+ PointState::Type primaryPointState(event.points[0].GetState());
+
+ if (primaryPointState == PointState::INTERRUPTED)
+ {
+ if ( ( mState == Started ) || ( mState == Possible ) )
+ {
+ // If our pan had started and we are interrupted, then tell Core that pan is cancelled.
+ mTouchEvents.push_back(event);
+ SendPan(Gesture::Cancelled, event);
+ }
+ mState = Clear; // We should change our state to Clear.
+ mTouchEvents.clear();
+ }
+ else
+ {
+ switch (mState)
+ {
+ case Clear:
+ {
+ if (primaryPointState == PointState::DOWN)
+ {
+ mPrimaryTouchDownLocation = event.points[0].GetScreenPosition();
+ mPrimaryTouchDownTime = event.time;
+ mMotionEvents = 0;
+ if (event.GetPointCount() == mMinimumTouchesRequired)
+ {
+ // We have satisfied the minimum touches required for a pan, tell core that a gesture may be possible and change our state accordingly.
+ mState = Possible;
+ SendPan(Gesture::Possible, event);
+ }
+
+ mTouchEvents.push_back(event);
+ }
+ break;
+ }
+
+ case Possible:
+ {
+ unsigned int pointCount(event.GetPointCount());
+ if ( (pointCount >= mMinimumTouchesRequired)&&(pointCount <= mMaximumTouchesRequired) )
+ {
+ if (primaryPointState == PointState::MOTION)
+ {
+ mTouchEvents.push_back(event);
+ mMotionEvents++;
+
+ Vector2 delta(event.points[0].GetScreenPosition() - mPrimaryTouchDownLocation);
+
+ if ( ( mMotionEvents >= mMinimumMotionEvents ) &&
+ ( delta.LengthSquared() >= mMinimumDistanceSquared ) )
+ {
+ // If the touch point(s) have moved enough distance to be considered a pan, then tell Core that the pan gesture has started and change our state accordingly.
+ mState = Started;
+ SendPan(Gesture::Started, event);
+ }
+ }
+ else if (primaryPointState == PointState::UP)
+ {
+ Vector2 delta(event.points[0].GetScreenPosition() - mPrimaryTouchDownLocation);
+ if(delta.LengthSquared() >= mMinimumDistanceSquared)
+ {
+ SendPan(Gesture::Started, event);
+ mTouchEvents.push_back(event);
+ SendPan(Gesture::Finished, event);
+ }
+ else
+ {
+ // If we have lifted the primary touch point then tell core the pan is cancelled and change our state to Clear.
+ SendPan(Gesture::Cancelled, event);
+ }
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ }
+ else
+ {
+ // We do not satisfy pan conditions, tell Core our Gesture has been cancelled.
+ SendPan(Gesture::Cancelled, event);
+
+ if (pointCount == 1 && primaryPointState == PointState::UP)
+ {
+ // If we have lifted the primary touch point, then change our state to Clear...
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ // ...otherwise change it to Failed.
+ mState = Failed;
+ }
+ }
+ break;
+ }
+
+ case Started:
+ {
+ mTouchEvents.push_back(event);
+
+ unsigned int pointCount(event.GetPointCount());
+ if ( (pointCount >= mMinimumTouchesRequired)&&(pointCount <= mMaximumTouchesRequired) )
+ {
+ switch (primaryPointState)
+ {
+ case PointState::MOTION:
+ // Pan is continuing, tell Core.
+ SendPan(Gesture::Continuing, event);
+ break;
+
+ case PointState::UP:
+ // Pan is finally finished when our primary point is lifted, tell Core and change our state to Clear.
+ SendPan(Gesture::Finished, event);
+ mState = Clear;
+ mTouchEvents.clear();
+ break;
+
+ case PointState::STATIONARY:
+ if (pointCount == mMinimumTouchesRequired)
+ {
+ Integration::PointContainerConstIterator iter = event.points.begin() + 1; // We already know the state of the first point
+ for(; iter != event.points.end(); ++iter)
+ {
+ if(iter->GetState() == PointState::UP)
+ {
+ // The number of touch points will be less than the minimum required. Inform core and change our state to Finished.
+ SendPan(Gesture::Finished, event);
+ mState = Finished;
+ break;
+ }
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+ }
+ else
+ {
+ // We have gone outside of the pan requirements, inform Core that the gesture is finished.
+ SendPan(Gesture::Finished, event);
+
+ if (pointCount == 1 && primaryPointState == PointState::UP)
+ {
+ // If this was the primary point being released, then we change our state back to Clear...
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ // ...otherwise we change it to Finished.
+ mState = Finished;
+ }
+ }
+ break;
+ }
+
+ case Finished:
+ case Failed:
+ {
+ if (primaryPointState == PointState::UP)
+ {
+ // Change our state back to clear when the primary touch point is released.
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ break;
+ }
+ }
+ }
+}
+
+void PanGestureDetectorBase::Update(const Integration::GestureRequest& request)
+{
+ const Integration::PanGestureRequest& pan = static_cast<const Integration::PanGestureRequest&>(request);
+
+ mMinimumTouchesRequired = pan.minTouches;
+ mMaximumTouchesRequired = pan.maxTouches;
+}
+
+void PanGestureDetectorBase::SendPan(Gesture::State state, const Integration::TouchEvent& currentEvent)
+{
+ Integration::PanGestureEvent gesture(state);
+ gesture.currentPosition = currentEvent.points[0].GetScreenPosition();
+ gesture.numberOfTouches = currentEvent.GetPointCount();
+
+ if ( mTouchEvents.size() > 1 )
+ {
+ // Get the second last event in the queue, the last one is the current event
+ const Integration::TouchEvent& previousEvent( *( mTouchEvents.rbegin() + 1 ) );
+
+ Vector2 previousPosition( mPreviousPosition );
+ unsigned long previousTime( previousEvent.time );
+
+ // If we've just started then we want to remove the threshold from Core calculations.
+ if ( state == Gesture::Started )
+ {
+ previousPosition = mPrimaryTouchDownLocation;
+ previousTime = mPrimaryTouchDownTime;
+
+ // If it's a slow pan, we do not want to phase in the threshold over the first few pan-events
+ // A slow pan is defined as one that starts the specified number of milliseconds after the down-event
+ if ( ( currentEvent.time - previousTime ) > MINIMUM_TIME_BEFORE_THRESHOLD_ADJUSTMENTS )
+ {
+ mThresholdAdjustmentsRemaining = mThresholdTotalAdjustments;
+ mThresholdAdjustmentPerFrame = ( gesture.currentPosition - previousPosition ) / mThresholdTotalAdjustments;
+ }
+ else
+ {
+ mThresholdAdjustmentsRemaining = 0;
+ mThresholdAdjustmentPerFrame = Vector2::ZERO;
+ }
+ }
+
+ gesture.previousPosition = previousPosition;
+ gesture.timeDelta = currentEvent.time - previousTime;
+
+ // Apply the threshold with a phased approach
+ if ( mThresholdAdjustmentsRemaining > 0 )
+ {
+ --mThresholdAdjustmentsRemaining;
+ gesture.currentPosition -= mThresholdAdjustmentPerFrame * mThresholdAdjustmentsRemaining;
+ }
+
+ mPreviousPosition = gesture.currentPosition;
+ }
+ else
+ {
+ gesture.previousPosition = gesture.currentPosition;
+ gesture.timeDelta = 0;
+ }
+
+ gesture.time = currentEvent.time;
+
+ EmitPan(gesture);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
+#define __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/math/vector2.h>
+#include <dali/integration-api/events/pan-gesture-event.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+class Core;
+struct TouchEvent;
+struct PanGestureRequest;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class EnvironmentOptions;
+
+/**
+ * When given a set of touch events, this detector attempts to determine if a pan gesture has taken place.
+ */
+class PanGestureDetectorBase : public GestureDetector
+{
+public:
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~PanGestureDetectorBase();
+
+public:
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
+ */
+ virtual void SendEvent(const Integration::TouchEvent& event);
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
+ */
+ virtual void Update(const Integration::GestureRequest& request);
+
+protected:
+
+ /**
+ * Constructor
+ * @param[in] screenSize The size of the screen.
+ * @param[in] request The details of the request.
+ */
+ PanGestureDetectorBase(Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions* environmentOptions);
+
+private:
+
+ /**
+ * Emits the pan gesture event (performs some smoothing operation).
+ * @param[in] state The state of the pan.
+ * @param[in] currentEvent The latest touch event.
+ */
+ void SendPan(Gesture::State state, const Integration::TouchEvent& currentEvent);
+
+ /**
+ * Emits the pan gesture event to the core.
+ * @param[in] gesture The pan gesture event.
+ */
+ virtual void EmitPan(const Integration::PanGestureEvent gesture) = 0;
+
+private:
+
+ /**
+ * Internal state machine.
+ */
+ enum State
+ {
+ Clear, ///< No gesture detected.
+ Possible, ///< The current touch event data suggests that a gesture is possible.
+ Started, ///< A gesture has been detected.
+ Finished, ///< A previously started pan gesture has finished.
+ Failed, ///< Current touch event data suggests a pan gesture is not possible.
+ };
+
+ State mState; ///< The current state of the detector.
+ std::vector<Integration::TouchEvent> mTouchEvents; ///< A container of all touch events after an initial down event.
+
+ Vector2 mPrimaryTouchDownLocation; ///< The initial touch down point.
+ Vector2 mThresholdAdjustmentPerFrame; ///< The adjustment per frame at the start of a slow pan.
+ Vector2 mPreviousPosition; ///< The previous position.
+
+ unsigned int mThresholdAdjustmentsRemaining; ///< No. of threshold adjustments still to apply (for a slow-pan).
+ unsigned int mThresholdTotalAdjustments; ///< The total number of adjustments required.
+
+ unsigned long mPrimaryTouchDownTime; ///< The initial touch down time.
+ unsigned int mMinimumTouchesRequired; ///< The minimum touches required before a pan should be emitted.
+ unsigned int mMaximumTouchesRequired; ///< The maximum touches after which a pan should not be emitted.
+
+ unsigned int mMinimumDistanceSquared; ///< The minimum distance squared before pan should start.
+ unsigned int mMinimumMotionEvents; ///< The minimum motion events before pan should start.
+ unsigned int mMotionEvents; ///< The motion events received so far (before pan is emitted).
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_PAN_GESTURE_DETECTOR_BASE_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/pan-gesture-detector.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/events/gesture-requests.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/core-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+PanGestureDetector::PanGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions& environmentOptions)
+: PanGestureDetectorBase(screenSize, request, &environmentOptions),
+ mCoreEventInterface(coreEventInterface)
+{
+}
+
+PanGestureDetector::~PanGestureDetector()
+{
+}
+
+void PanGestureDetector::EmitPan(const Integration::PanGestureEvent event)
+{
+ mCoreEventInterface.QueueCoreEvent(event);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
+#define __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/math/vector2.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/pan-gesture-detector-base.h>
+#include <dali/integration-api/events/pan-gesture-event.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+struct TouchEvent;
+struct PanGestureRequest;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CoreEventInterface;
+
+/**
+ * Detects a pan gesture and sends it to core.
+ */
+class PanGestureDetector : public PanGestureDetectorBase
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] screenSize The size of the screen.
+ * @param[in] request The details of the request.
+ * @param[in] environmentOptions The environmentOptions.
+ */
+ PanGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::PanGestureRequest& request, EnvironmentOptions& environmentOptions);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~PanGestureDetector();
+
+private:
+
+ /**
+ * Emits the pan gesture event to the core.
+ * @param[in] gesture The pan gesture event.
+ */
+ virtual void EmitPan(const Integration::PanGestureEvent gesture);
+
+private:
+
+ CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_PAN_GESTURE_DETECTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+
+// CLASS HEADER
+#include <dali/internal/input/common/physical-keyboard-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::PhysicalKeyboard PhysicalKeyboard::New()
+{
+ Dali::PhysicalKeyboard keyboardHandle;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ keyboardHandle = Dali::PhysicalKeyboard( new PhysicalKeyboard() );
+ service.Register( typeid( keyboardHandle ), keyboardHandle );
+ }
+
+ return keyboardHandle;
+}
+
+Dali::PhysicalKeyboard PhysicalKeyboard::Get()
+{
+ Dali::PhysicalKeyboard keyboardHandle;
+
+ Dali::SingletonService service = SingletonService::Get();
+ if ( service )
+ {
+ BaseHandle handle = service.GetSingleton( typeid( Dali::PhysicalKeyboard ) );
+ if( handle )
+ {
+ // If so, downcast the handle of singleton to focus manager
+ keyboardHandle = Dali::PhysicalKeyboard( dynamic_cast< PhysicalKeyboard* >( handle.GetObjectPtr() ) );
+ }
+ }
+
+ return keyboardHandle;
+}
+
+bool PhysicalKeyboard::IsAttached() const
+{
+ return mAttached;
+}
+
+void PhysicalKeyboard::KeyReceived( bool fromPhysicalKeyboard )
+{
+ if ( mAttached != fromPhysicalKeyboard )
+ {
+ mAttached = fromPhysicalKeyboard;
+
+ Dali::PhysicalKeyboard handle( this );
+ mStatusChangedSignal.Emit( handle );
+ }
+}
+
+PhysicalKeyboard::~PhysicalKeyboard()
+{
+}
+
+PhysicalKeyboard::PhysicalKeyboard()
+: mAttached( false )
+{
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
+#define __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/physical-keyboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class PhysicalKeyboard : public BaseObject
+{
+public:
+
+ /**
+ * Creates a new instance of the PhysicalKeyboard.
+ */
+ static Dali::PhysicalKeyboard New();
+
+ /**
+ * Gets the singleton instance of the Physical Keyboard.
+ */
+ static Dali::PhysicalKeyboard Get();
+
+ /**
+ * @copydoc Dali::PhysicalKeyboard::IsAttached()
+ */
+ bool IsAttached() const;
+
+ /**
+ * Should be called by the EventHandler when a key is received. If it's received from a physical
+ * keyboard then the parameter should be true.
+ * @param[in] fromPhysicalKeyboard true if received from a physical keyboard, false otherwise.
+ */
+ void KeyReceived( bool fromPhysicalKeyboard );
+
+ // Signals
+
+ /**
+ * @copydoc Dali::PhysicalKeyboard::StatusChangedSignal()
+ */
+ Dali::PhysicalKeyboard::PhysicalKeyboardSignalType& StatusChangedSignal() { return mStatusChangedSignal; }
+
+protected:
+
+ /**
+ * A reference counted object may only be deleted by calling Unreference()
+ */
+ virtual ~PhysicalKeyboard();
+
+private:
+
+ // Undefined
+ PhysicalKeyboard( const PhysicalKeyboard& );
+ PhysicalKeyboard& operator=( PhysicalKeyboard& );
+
+ /**
+ * Constructor
+ */
+ PhysicalKeyboard();
+
+private:
+
+ Dali::PhysicalKeyboard::PhysicalKeyboardSignalType mStatusChangedSignal; ///< Status changed signal
+ bool mAttached; ///< true if the physical keyboard is attached, false otherwise
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Helpers for public-api forwarding methods
+
+inline static Internal::Adaptor::PhysicalKeyboard& GetImplementation( PhysicalKeyboard& keyboard )
+{
+ DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" );
+
+ BaseObject& handle = keyboard.GetBaseObject();
+
+ return static_cast< Internal::Adaptor::PhysicalKeyboard& >( handle );
+}
+
+inline static const Internal::Adaptor::PhysicalKeyboard& GetImplementation( const PhysicalKeyboard& keyboard )
+{
+ DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" );
+
+ const BaseObject& handle = keyboard.GetBaseObject();
+
+ return static_cast< const Internal::Adaptor::PhysicalKeyboard& >( handle );
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_PHYSICAL_KEYBOARD_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/pinch-gesture-detector.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+
+#include <dali/public-api/events/touch-point.h>
+#include <dali/public-api/math/vector2.h>
+
+#include <dali/integration-api/events/pinch-gesture-event.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/core-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const unsigned int MINIMUM_TOUCH_EVENTS_REQUIRED = 4;
+const unsigned int MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START = 4;
+
+inline float GetDistance(const Integration::Point& point1, const Integration::Point& point2)
+{
+ Vector2 vector(point1.GetScreenPosition() - point2.GetScreenPosition());
+ return vector.Length();
+}
+
+inline Vector2 GetCenterPoint(const Integration::Point& point1, const Integration::Point& point2)
+{
+ return Vector2(point1.GetScreenPosition() + point2.GetScreenPosition()) * 0.5f;
+}
+
+} // unnamed namespace
+
+PinchGestureDetector::PinchGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, float minimumPinchDistance)
+: GestureDetector(screenSize, Gesture::Pinch),
+ mCoreEventInterface(coreEventInterface),
+ mState(Clear),
+ mTouchEvents(),
+ mMinimumDistanceDelta(minimumPinchDistance),
+ mStartingDistance(0.0f)
+{
+}
+
+PinchGestureDetector::~PinchGestureDetector()
+{
+}
+
+void PinchGestureDetector::SetMinimumPinchDistance(float distance)
+{
+ mMinimumDistanceDelta = distance;
+}
+
+void PinchGestureDetector::SendEvent(const Integration::TouchEvent& event)
+{
+ int pointCount = event.GetPointCount();
+
+ switch (mState)
+ {
+ case Clear:
+ {
+ if (pointCount == 2)
+ {
+ // Change state to possible as we have two touch points.
+ mState = Possible;
+ mTouchEvents.push_back(event);
+ }
+ break;
+ }
+
+ case Possible:
+ {
+ if (pointCount != 2)
+ {
+ // We no longer have two touch points so change state back to Clear.
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ const Integration::Point& currentPoint1 = event.points[0];
+ const Integration::Point& currentPoint2 = event.points[1];
+
+ if (currentPoint1.GetState() == PointState::UP || currentPoint2.GetState() == PointState::UP)
+ {
+ // One of our touch points has an Up event so change our state back to Clear.
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ mTouchEvents.push_back(event);
+
+ // We can only determine a pinch after a certain number of touch points have been collected.
+ if (mTouchEvents.size() >= MINIMUM_TOUCH_EVENTS_REQUIRED)
+ {
+ const Integration::Point& firstPoint1 = mTouchEvents[0].points[0];
+ const Integration::Point& firstPoint2 = mTouchEvents[0].points[1];
+
+ float firstDistance = GetDistance(firstPoint1, firstPoint2);
+ float currentDistance = GetDistance(currentPoint1, currentPoint2);
+ float distanceChanged = firstDistance - currentDistance;
+
+ // Check if distance has changed enough
+ if (fabsf(distanceChanged) > mMinimumDistanceDelta)
+ {
+ // Remove the first few events from the vector otherwise values are exaggerated
+ mTouchEvents.erase(mTouchEvents.begin(), mTouchEvents.end() - MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START);
+
+ if ( !mTouchEvents.empty() )
+ {
+ mStartingDistance = GetDistance(mTouchEvents.begin()->points[0], mTouchEvents.begin()->points[1]);
+
+ // Send pinch started
+ SendPinch(Gesture::Started, event);
+
+ mState = Started;
+ }
+
+ mTouchEvents.clear();
+ }
+
+ if (mState == Possible)
+ {
+ // No pinch, so restart detection
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ case Started:
+ {
+ if (pointCount != 2)
+ {
+ // Send pinch finished event
+ SendPinch(Gesture::Finished, event);
+
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ const Integration::Point& currentPoint1 = event.points[0];
+ const Integration::Point& currentPoint2 = event.points[1];
+
+ if (currentPoint1.GetState() == PointState::UP || currentPoint2.GetState() == PointState::UP)
+ {
+ mTouchEvents.push_back(event);
+ // Send pinch finished event
+ SendPinch(Gesture::Finished, event);
+
+ mState = Clear;
+ mTouchEvents.clear();
+ }
+ else
+ {
+ mTouchEvents.push_back(event);
+
+ if (mTouchEvents.size() >= MINIMUM_TOUCH_EVENTS_REQUIRED_AFTER_START)
+ {
+ // Send pinch continuing
+ SendPinch(Gesture::Continuing, event);
+
+ mTouchEvents.clear();
+ }
+ }
+ }
+ break;
+ }
+ }
+}
+
+void PinchGestureDetector::Update(const Integration::GestureRequest& request)
+{
+ // Nothing to do.
+}
+
+void PinchGestureDetector::SendPinch(Gesture::State state, const Integration::TouchEvent& currentEvent)
+{
+ Integration::PinchGestureEvent gesture(state);
+
+ if ( !mTouchEvents.empty() )
+ {
+ const Integration::TouchEvent& firstEvent = mTouchEvents[0];
+
+ // Assert if we have been holding TouchEvents that do not have 2 points
+ DALI_ASSERT_DEBUG( firstEvent.GetPointCount() == 2 );
+
+ // We should use the current event in our calculations unless it does not have two points.
+ // If it does not have two points, then we should use the last point in mTouchEvents.
+ Integration::TouchEvent event( currentEvent );
+ if ( event.GetPointCount() != 2 )
+ {
+ event = *mTouchEvents.rbegin();
+ }
+
+ const Integration::Point& firstPoint1( firstEvent.points[0] );
+ const Integration::Point& firstPoint2( firstEvent.points[1] );
+ const Integration::Point& currentPoint1( event.points[0] );
+ const Integration::Point& currentPoint2( event.points[1] );
+
+ float firstDistance = GetDistance(firstPoint1, firstPoint2);
+ float currentDistance = GetDistance(currentPoint1, currentPoint2);
+ gesture.scale = currentDistance / mStartingDistance;
+
+ float distanceDelta = fabsf(firstDistance - currentDistance);
+ unsigned long timeDelta = currentEvent.time - firstEvent.time;
+ gesture.speed = (distanceDelta / timeDelta) * 1000.0f;
+
+ gesture.centerPoint = GetCenterPoint(currentPoint1, currentPoint2);
+ }
+ else
+ {
+ // Something has gone wrong, just cancel the gesture.
+ gesture.state = Gesture::Cancelled;
+ }
+
+ gesture.time = currentEvent.time;
+
+ mCoreEventInterface.QueueCoreEvent(gesture);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
+#define __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+struct TouchEvent;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CoreEventInterface;
+
+/**
+ * When given a set of touch events, this detector attempts to determine if a pinch gesture has taken place.
+ */
+class PinchGestureDetector : public GestureDetector
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] screenSize The size of the screen.
+ */
+ PinchGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, float minimumPinchDistance);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~PinchGestureDetector();
+
+ /**
+ * @brief Sets minimum distance in pixels that the fingers must move towards/away from each other in order to
+ * trigger a pinch gesture
+ *
+ * @param[in] distance The minimum pinch distance in pixels
+ */
+ void SetMinimumPinchDistance(float distance);
+
+public:
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
+ */
+ virtual void SendEvent(const Integration::TouchEvent& event);
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
+ */
+ virtual void Update(const Integration::GestureRequest& request);
+
+private:
+
+ /**
+ * Emits the pinch gesture event to the core.
+ * @param[in] state The state of the pinch (whether it's starting, continuing or finished).
+ * @param[in] currentEvent The latest touch event.
+ */
+ void SendPinch(Gesture::State state, const Integration::TouchEvent& currentEvent);
+
+private:
+
+ /**
+ * Internal state machine.
+ */
+ enum State
+ {
+ Clear, ///< No gesture detected.
+ Possible, ///< The current touch event data suggests that a gesture is possible.
+ Started, ///< A gesture has been detected.
+ };
+
+ CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
+ State mState; ///< The current state of the detector.
+ std::vector<Integration::TouchEvent> mTouchEvents; ///< The touch events since initial touch down.
+
+ float mMinimumDistanceDelta; ///< The minimum distance before a pinch is applicable.
+
+ float mStartingDistance; ///< The distance between the two touch points when the pinch is first detected.
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_PINCH_GESTURE_DETECTOR_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/tap-gesture-detector.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+
+#include <dali/public-api/math/vector2.h>
+
+#include <dali/integration-api/events/gesture-requests.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+#include <dali/internal/system/common/core-event-interface.h>
+
+// INTERNAL INCLUDES
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+// TODO: Set these according to DPI
+const float MAXIMUM_MOTION_ALLOWED = 20.0f;
+const unsigned long MAXIMUM_TIME_ALLOWED = 500u;
+} // unnamed namespace
+
+TapGestureDetector::TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request)
+: GestureDetector(screenSize, Gesture::Tap),
+ mCoreEventInterface(coreEventInterface),
+ mState(Clear),
+ mMinimumTapsRequired(request.minTaps),
+ mMaximumTapsRequired(request.maxTaps),
+ mTapsRegistered(0),
+ mTouchPosition(),
+ mTouchTime(0u),
+ mLastTapTime(0u)
+{
+}
+
+TapGestureDetector::~TapGestureDetector()
+{
+}
+
+void TapGestureDetector::SendEvent(const Integration::TouchEvent& event)
+{
+ if (event.GetPointCount() == 1)
+ {
+ const Integration::Point& point = event.points[0];
+ PointState::Type pointState = point.GetState();
+
+ switch (mState)
+ {
+ case Clear:
+ {
+ if (pointState == PointState::DOWN)
+ {
+ SetupForTouchDown( event, point );
+ }
+ break;
+ }
+
+ case Touched:
+ {
+ unsigned long deltaBetweenTouchDownTouchUp = abs( event.time - mTouchTime ) ;
+
+ if ( pointState == PointState::UP )
+ {
+ if ( deltaBetweenTouchDownTouchUp < MAXIMUM_TIME_ALLOWED )
+ {
+ mLastTapTime = mTouchTime;
+ EmitSingleTap( event.time, point );
+ mState = Registered;
+ }
+ else
+ {
+ mState = Clear;
+ }
+ }
+ else if (pointState == PointState::INTERRUPTED)
+ {
+ mState = Clear;
+ }
+ break;
+ }
+
+ case Registered:
+ {
+ if ( pointState == PointState::UP )
+ {
+ unsigned long deltaBetweenTouchDownTouchUp = abs( event.time - mTouchTime ) ;
+
+ if ( deltaBetweenTouchDownTouchUp < MAXIMUM_TIME_ALLOWED )
+ {
+ // This is a possible multiple tap, so has it been quick enough ?
+ unsigned long timeDelta = abs( event.time - mLastTapTime );
+ if ( timeDelta > MAXIMUM_TIME_ALLOWED ) // If exceeded time between taps then just a single tap.
+ {
+ mLastTapTime = event.time;
+ EmitSingleTap( event.time, point );
+ mState = Registered;
+ }
+ else
+ {
+ ++mTapsRegistered;
+ EmitGesture( Gesture::Started, event.time );
+ mState = Clear;
+ }
+ }
+ else // Delta between touch down and touch up too long to be considered a Tap event
+ {
+ mState = Clear;
+ }
+ }
+ else if (pointState == PointState::DOWN)
+ {
+ const Vector2& screen( point.GetScreenPosition() );
+ Vector2 distanceDelta(abs(mTouchPosition.x - screen.x),
+ abs(mTouchPosition.y - screen.y));
+
+ unsigned long timeDelta = abs( event.time - mLastTapTime );
+
+ if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
+ distanceDelta.y > MAXIMUM_MOTION_ALLOWED ||
+ timeDelta > MAXIMUM_TIME_ALLOWED )
+ {
+ SetupForTouchDown( event, point );
+ }
+ else
+ {
+ EmitPossibleState( event );
+ }
+ }
+ break;
+ }
+
+ case Failed:
+ default:
+ {
+ mState = Clear;
+ break;
+ }
+ }
+ }
+ else
+ {
+ mState = Failed;
+
+ // We have entered a multi-touch event so emit registered gestures if required.
+ EmitGesture(Gesture::Started, event.time);
+ }
+}
+
+void TapGestureDetector::SetupForTouchDown( const Integration::TouchEvent& event, const Integration::Point& point )
+{
+ mTouchPosition = point.GetScreenPosition();
+ mTouchTime = event.time;
+ mLastTapTime = 0u;
+ mTapsRegistered = 0;
+ mState = Touched;
+ EmitPossibleState( event );
+}
+
+void TapGestureDetector::EmitPossibleState( const Integration::TouchEvent& event )
+{
+ Integration::TapGestureEvent tapEvent( Gesture::Possible );
+ tapEvent.point = mTouchPosition;
+ tapEvent.time = event.time;
+ mCoreEventInterface.QueueCoreEvent(tapEvent);
+}
+
+
+void TapGestureDetector::Update(const Integration::GestureRequest& request)
+{
+ const Integration::TapGestureRequest& tap = static_cast<const Integration::TapGestureRequest&>(request);
+
+ mMinimumTapsRequired = tap.minTaps;
+ mMaximumTapsRequired = tap.maxTaps;
+}
+
+void TapGestureDetector::EmitGesture( Gesture::State state, unsigned int time )
+{
+ if ( (state == Gesture::Cancelled) ||
+ (mTapsRegistered >= mMinimumTapsRequired && mTapsRegistered <= mMaximumTapsRequired) )
+
+ {
+ Integration::TapGestureEvent event( state );
+ EmitTap( time, event );
+ }
+}
+
+void TapGestureDetector::EmitSingleTap( unsigned int time, const Integration::Point& point )
+{
+ Integration::TapGestureEvent event( Gesture::Started );
+ const Vector2& screen( point.GetScreenPosition() );
+ Vector2 distanceDelta(abs(mTouchPosition.x - screen.x),
+ abs(mTouchPosition.y - screen.y));
+
+ if (distanceDelta.x > MAXIMUM_MOTION_ALLOWED ||
+ distanceDelta.y > MAXIMUM_MOTION_ALLOWED )
+ {
+ event.state = Gesture::Cancelled;
+ }
+ mTapsRegistered = 1u;
+ EmitTap( time, event );
+}
+
+void TapGestureDetector::EmitTap( unsigned int time, Integration::TapGestureEvent& event )
+{
+ event.numberOfTaps = mTapsRegistered;
+ event.point = mTouchPosition;
+ event.time = time;
+ mCoreEventInterface.QueueCoreEvent(event);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
+#define __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/events/tap-gesture-event.h>
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/integration-api/events/point.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-detector.h>
+
+namespace Dali
+{
+
+namespace Integration
+{
+struct TouchEvent;
+struct TapGestureRequest;
+}
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CoreEventInterface;
+
+/**
+ * When given a set of touch events, this detector attempts to determine if a tap gesture has taken place.
+ */
+class TapGestureDetector : public GestureDetector
+{
+public:
+
+ /**
+ * Constructor
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] screenSize The size of the screen.
+ * @param[in] request The tap gesture request.
+ */
+ TapGestureDetector(CoreEventInterface& coreEventInterface, Vector2 screenSize, const Integration::TapGestureRequest& request);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~TapGestureDetector();
+
+public:
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::SendEvent(const Integration::TouchEvent&)
+ */
+ virtual void SendEvent(const Integration::TouchEvent& event);
+
+ /**
+ * @copydoc Dali::Internal::GestureDetector::Update(const Integration::GestureRequest&)
+ */
+ virtual void Update(const Integration::GestureRequest& request);
+
+private:
+
+ /**
+ * Checks if registered taps are within required bounds and emits tap gesture if they are.
+ *
+ * @param[in] state current state of incomplete gesture
+ * @param[in] time time of this latest touch event
+ */
+ void EmitGesture( Gesture::State state, unsigned int time );
+
+ /**
+ * Initialises tap gesture detector for next tap sequence
+ *
+ * @param[in] event registered touch event
+ * @param[in] point position touch event occurred
+ */
+ void SetupForTouchDown( const Integration::TouchEvent& event, const Integration::Point& point );
+
+ /**
+ * Emit a touch down event for hit testing
+ *
+ * @param[in] event registered touch event
+ */
+ void EmitPossibleState( const Integration::TouchEvent& event );
+
+ /**
+ * Force a touch event sequence to be treated as a single tap
+ *
+ * @param[in] time time of this latest touch event
+ * @param[in] point position touch event occurred
+ */
+ void EmitSingleTap( unsigned int time, const Integration::Point& point );
+
+ /**
+ * Emit a tap event
+ *
+ * @param[in] time time of this latest touch event
+ * @param[in] event registered touch event
+ */
+ void EmitTap( unsigned int time, Integration::TapGestureEvent& event );
+
+private:
+
+ /**
+ * Internal state machine.
+ */
+ enum State
+ {
+ Clear, ///< No gesture detected.
+ Touched, ///< User is touching the screen.
+ Registered, ///< At least one tap has been registered.
+ Failed, ///< Gesture has failed.
+ };
+
+ CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
+ State mState; ///< Current state of the detector.
+
+ int mMinimumTapsRequired; ///< Minimum number of taps required.
+ int mMaximumTapsRequired; ///< Maximum number of taps required.
+ int mTapsRegistered; ///< In current detection, the number of taps registered.
+
+ Vector2 mTouchPosition; ///< The initial touch down position.
+ unsigned long mTouchTime; ///< The initial touch down time.
+ unsigned long mLastTapTime; ///< Time last tap gesture was registered
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_TAP_GESTURE_DETECTOR_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
+#define __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/virtual-keyboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of the virtual keyboard namespace
+ */
+namespace VirtualKeyboard
+{
+
+/**
+ * @copydoc Dali::VirtualKeyboard::Show()
+ */
+void Show();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::Hide()
+ */
+void Hide();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::IsVisible()
+ */
+bool IsVisible();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::ApplySettings()
+ */
+void ApplySettings( const Property::Map& settingsMap );
+
+/**
+ * @copydoc Dali::VirtualKeyboard::SetReturnKeyType()
+ */
+void SetReturnKeyType( const Dali::InputMethod::ActionButton type );
+
+/**
+ * @copydoc Dali::VirtualKeyboard::GetReturnKeyType()
+ */
+Dali::InputMethod::ActionButton GetReturnKeyType();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::EnablePrediction()
+ */
+void EnablePrediction(const bool enable);
+
+/**
+ * @copydoc Dali::VirtualKeyboard::IsPredictionEnabled()
+ */
+bool IsPredictionEnabled();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::GetSizeAndPosition()
+ */
+Rect<int> GetSizeAndPosition();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::RotateKeyboard()
+ */
+void RotateTo(int angle);
+
+/**
+ * @copydox Dali::VirtualKeyboard::StatusChangedSignal()
+ */
+Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal();
+
+/**
+ * @copydox Dali::VirtualKeyboard::ResizedSignal()
+ */
+Dali::VirtualKeyboard::KeyboardResizedSignalType& ResizedSignal();
+
+/**
+ * @copydox Dali::VirtualKeyboard::LanguageChangedSignal()
+ */
+Dali::VirtualKeyboard::LanguageChangedSignalType& LanguageChangedSignal();
+
+/**
+ * @copydoc Dali::VirtualKeyboard::GetTextDirection
+ */
+Dali::VirtualKeyboard::TextDirection GetTextDirection();
+
+} // namespace VirtualKeyboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_VIRTUAL_KEYBOARD_H__
--- /dev/null
+
+
+# module: input, backend: common
+adaptor_input_common_src_files=\
+ ${adaptor_input_dir}/common/drag-and-drop-detector-impl.cpp \
+ ${adaptor_input_dir}/common/gesture-manager.cpp \
+ ${adaptor_input_dir}/common/imf-manager-factory.cpp \
+ ${adaptor_input_dir}/common/imf-manager-impl.cpp \
+ ${adaptor_input_dir}/common/key-impl.cpp \
+ ${adaptor_input_dir}/common/long-press-gesture-detector.cpp \
+ ${adaptor_input_dir}/common/pan-gesture-detector-base.cpp \
+ ${adaptor_input_dir}/common/pan-gesture-detector.cpp \
+ ${adaptor_input_dir}/common/physical-keyboard-impl.cpp \
+ ${adaptor_input_dir}/common/pinch-gesture-detector.cpp \
+ ${adaptor_input_dir}/common/tap-gesture-detector.cpp \
+ ${adaptor_input_dir}/tizen-wayland/ecore-virtual-keyboard.cpp
+
+# module: input, backend: tizen-wayland
+adaptor_input_tizen_wayland_src_files=\
+ ${adaptor_input_dir}/tizen-wayland/imf-manager-factory-ecore-wl.cpp \
+ ${adaptor_input_dir}/tizen-wayland/imf-manager-impl-ecore-wl.cpp \
+ ${adaptor_input_dir}/tizen-wayland/key-grab-ecore-wl.cpp \
+ ${adaptor_input_dir}/tizen-wayland/key-mapping-ecore-wl.cpp \
+ ${adaptor_input_dir}/tizen-wayland/virtual-keyboard-impl-ecore-wl.cpp
+
+# module: input, backend: ubuntu
+adaptor_input_ubuntu_src_files=\
+ ${adaptor_input_dir}/ubuntu/key-mapping-ubuntu.cpp
+
+# module: input, backend: ubuntu-x11
+adaptor_input_ubuntu_x11_src_files=\
+ ${adaptor_input_dir}/ubuntu-x11/imf-manager-factory-x.cpp \
+ ${adaptor_input_dir}/ubuntu-x11/imf-manager-impl-x.cpp \
+ ${adaptor_input_dir}/ubuntu-x11/virtual-keyboard-impl-x.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/virtual-keyboard-impl.h>
+
+// EXTERNAL INCLUDES
+#include <algorithm>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h>
+#include <dali/integration-api/adaptor.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/input/common/imf-manager-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace VirtualKeyboard
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIRTUAL_KEYBOARD");
+#endif
+
+#define TOKEN_STRING(x) #x
+
+//forward declarations
+void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value );
+void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value );
+
+// Signals
+Dali::VirtualKeyboard::StatusSignalType gKeyboardStatusSignal;
+Dali::VirtualKeyboard::VoidSignalType gKeyboardResizeSignal;
+Dali::VirtualKeyboard::VoidSignalType gKeyboardLanguageChangedSignal;
+
+void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
+{
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n" );
+
+ gKeyboardStatusSignal.Emit( true );
+
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n" );
+
+ gKeyboardStatusSignal.Emit( false );
+
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
+ default:
+ {
+ // Do nothing
+ break;
+ }
+ }
+}
+
+void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback\n" );
+
+ // Emit the signal that the language has changed
+ gKeyboardLanguageChangedSignal.Emit();
+}
+
+void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n" );
+
+ // Emit signal that the keyboard is resized
+ gKeyboardResizeSignal.Emit();
+}
+
+} // unnamed namespace
+
+void ConnectCallbacks( Ecore_IMF_Context *imfContext )
+{
+ if( imfContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n" );
+
+ ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL );
+ ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL );
+ ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL );
+ }
+}
+
+void DisconnectCallbacks( Ecore_IMF_Context *imfContext )
+{
+ if( imfContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n" );
+
+ ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
+ ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
+ ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
+ }
+}
+
+void Show()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Show() is deprecated and will be removed from next release. Use ImfManager.Activate() instead.\n" );
+
+ Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) to show the keyboard
+
+ if( imfManager )
+ {
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if( imfContext )
+ {
+ ecore_imf_context_input_panel_show( imfContext );
+ }
+ }
+}
+
+void Hide()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Hide() is deprecated and will be removed from next release. Use ImfManager.Deactivate() instead.\n" );
+
+ if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance*/ )
+ {
+ Dali::ImfManager imfManager = ImfManager::Get();
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if( imfContext )
+ {
+ ecore_imf_context_input_panel_hide( imfContext );
+ }
+ }
+}
+
+bool IsVisible()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IsVisible() is deprecated and will be removed from next release.\n" );
+
+ if( ImfManager::IsAvailable() /* We do not want to create an ImfManager instance */ )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "IMF IsVisible\n" );
+
+ Dali::ImfManager imfManager = ImfManager::Get();
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if ( imfContext )
+ {
+ if (ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_SHOW ||
+ ecore_imf_context_input_panel_state_get(imfContext) == ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW)
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+void ApplySettings( const Property::Map& settingsMap )
+{
+ using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING.
+
+ for ( unsigned int i = 0, count = settingsMap.Count(); i < count; ++i )
+ {
+ Property::Key key = settingsMap.GetKeyAt( i );
+ if( key.type == Property::Key::INDEX )
+ {
+ continue;
+ }
+
+ Property::Value item = settingsMap.GetValue(i);
+
+ if ( key == TOKEN_STRING( ACTION_BUTTON ) )
+ {
+ if ( item.GetType() == Property::INTEGER )
+ {
+ int value = item.Get< int >();
+ VirtualKeyboard::SetReturnKeyType( static_cast<InputMethod::ActionButton>(value) );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" );
+ }
+ }
+}
+
+void EnablePrediction(const bool enable)
+{
+ Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when enabling prediction
+
+ if( imfManager )
+ {
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if ( imfContext )
+ {
+ ecore_imf_context_prediction_allow_set( imfContext, (enable)? EINA_TRUE : EINA_FALSE);
+ }
+ }
+}
+
+bool IsPredictionEnabled()
+{
+ if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManger */ )
+ {
+ Dali::ImfManager imfManager = ImfManager::Get();
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if ( imfContext )
+ {
+ // predictive text is enabled.
+ if ( ecore_imf_context_input_panel_enabled_get( imfContext ) == EINA_TRUE )
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+Rect<int> GetSizeAndPosition()
+{
+ int xPos, yPos, width, height;
+
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetSizeAndPosition() is deprecated and will be removed from next release. Use ImfManager.GetInputMethodArea() instead.\n" );
+
+ width = height = xPos = yPos = 0;
+ Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) as we may need to do some size related setup in the application
+
+ if( imfManager )
+ {
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if( imfContext )
+ {
+ ecore_imf_context_input_panel_geometry_get(imfContext, &xPos, &yPos, &width, &height);
+ }
+ else
+ {
+ DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
+ // return 0 as real size unknown.
+ }
+ }
+
+ return Rect<int>(xPos,yPos,width,height);
+}
+
+Dali::VirtualKeyboard::StatusSignalType& StatusChangedSignal()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: StatusChangedSignal() is deprecated and will be removed from next release. Use ImfManager.StatusChangedSignal() instead.\n" );
+
+ Dali::ImfManager imfManager = ImfManager::Get();
+ return imfManager.StatusChangedSignal();
+}
+
+Dali::VirtualKeyboard::KeyboardResizedSignalType& ResizedSignal()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: ResizedSignal() is deprecated and will be removed from next release. Use ImfManager.ResizedSignal() instead.\n" );
+
+ Dali::ImfManager imfManager = ImfManager::Get();
+ return imfManager.ResizedSignal();
+}
+
+Dali::VirtualKeyboard::LanguageChangedSignalType& LanguageChangedSignal()
+{
+ DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: LanguageChangedSignal() is deprecated and will be removed from next release. Use ImfManager.LanguageChangedSignal() instead.\n" );
+
+ Dali::ImfManager imfManager = ImfManager::Get();
+ return imfManager.LanguageChangedSignal();
+}
+
+Dali::VirtualKeyboard::TextDirection GetTextDirection()
+{
+ Dali::VirtualKeyboard::TextDirection direction ( Dali::VirtualKeyboard::LeftToRight );
+
+ if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
+ {
+ Dali::ImfManager imfManager = ImfManager::Get();
+
+ if ( imfManager )
+ {
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if ( imfContext )
+ {
+ char* locale( NULL );
+ ecore_imf_context_input_panel_language_locale_get( imfContext, &locale );
+
+ if ( locale )
+ {
+ direction = static_cast< Dali::VirtualKeyboard::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
+ free( locale );
+ }
+ }
+ }
+ }
+ return direction;
+}
+
+} // namespace VirtualKeyboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
+#define __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_IMF.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/virtual-keyboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of the virtual keyboard namespace
+ */
+namespace VirtualKeyboard
+{
+
+/**
+ * Connect the virtual keyboard callbacks.
+ * To get the virtual keyboard callbacks then you have to connect these callback.
+ * If you don't connect callbacks, you can't get virtual keyboard signals.
+ * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal.
+ */
+void ConnectCallbacks( Ecore_IMF_Context *imfContext );
+
+/**
+ * Disconnect the virtual keyboard callbacks.
+ * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal.
+ */
+void DisconnectCallbacks( Ecore_IMF_Context *imfContext );
+
+} // namespace VirtualKeyboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/internal/input/tizen-wayland/imf-manager-impl-ecore-wl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class ImfManager;
+
+template<typename T, typename... Args>
+std::unique_ptr<T> MakeUnique(Args&&... args)
+{
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+namespace ImfManagerFactory
+{
+
+// ImfManager Factory to be implemented by the platform
+Dali::ImfManager CreateImfManager()
+{
+ return Dali::Internal::Adaptor::ImfManagerEcoreWl::Get();
+}
+
+}
+
+}
+
+
+
+}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+
+#include <dali/internal/input/tizen-wayland/imf-manager-impl-ecore-wl.h>
+#include <Ecore_Input.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/events/key-event.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/input-method-devel.h>
+#include <dali/integration-api/adaptor.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/window-system/tizen-wayland/window-render-surface-ecore-wl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+#define TOKEN_STRING(x) #x
+
+Ecore_IMF_Input_Panel_Layout panelLayoutMap[] =
+{
+ ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_URL,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_PHONENUMBER,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_IP,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_MONTH,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBERONLY,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_HEX,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_TERMINAL,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_DATETIME,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_EMOTICON,
+ ECORE_IMF_INPUT_PANEL_LAYOUT_VOICE
+};
+
+Ecore_IMF_Autocapital_Type autoCapitalMap[] =
+{
+ ECORE_IMF_AUTOCAPITAL_TYPE_NONE,
+ ECORE_IMF_AUTOCAPITAL_TYPE_WORD,
+ ECORE_IMF_AUTOCAPITAL_TYPE_SENTENCE,
+ ECORE_IMF_AUTOCAPITAL_TYPE_ALLCHARACTER,
+};
+
+Ecore_IMF_Input_Panel_Return_Key_Type returnKeyTypeMap[] =
+{
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND,
+ ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN
+};
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
+#endif
+
+// Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
+size_t Utf8SequenceLength(const unsigned char leadByte)
+{
+ size_t length = 0;
+
+ if ((leadByte & 0x80) == 0 ) //ASCII character (lead bit zero)
+ {
+ length = 1;
+ }
+ else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
+ {
+ length = 2;
+ }
+ else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
+ {
+ length = 3;
+ }
+ else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
+ {
+ length = 4;
+ }
+
+ return length;
+}
+
+// Static function calls used by ecore 'c' style callback registration
+void Commit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ imfManager->CommitReceived( data, imfContext, event_info );
+ }
+}
+
+void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ imfManager->PreEditChanged( data, imfContext, event_info );
+ }
+}
+
+Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
+{
+ if ( data )
+ {
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ return imfManager->RetrieveSurrounding( data, imfContext, text, cursorPosition );
+ }
+ else
+ {
+ return false;
+ }
+}
+
+void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value )
+{
+ if (!data)
+ {
+ return;
+ }
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
+ {
+ imfManager->StatusChangedSignal().Emit( true );
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
+ {
+ imfManager->StatusChangedSignal().Emit( false );
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
+ default:
+ {
+ // Do nothing
+ break;
+ }
+ }
+}
+
+void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value )
+{
+ if (!data)
+ {
+ return;
+ }
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ // Emit the signal that the language has changed
+ imfManager->LanguageChangedSignal().Emit(value);
+}
+
+void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value )
+{
+ if (!data)
+ {
+ return;
+ }
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data ); // Emit signal that the keyboard is resized
+ // Emit signal that the keyboard is resized
+ imfManager->ResizedSignal().Emit(value);
+}
+
+void InputPanelKeyboardTypeChangedCallback( void *data, Ecore_IMF_Context *context, int value )
+{
+ if( !data )
+ {
+ return;
+ }
+
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE:
+ {
+ // Emit Signal that the keyboard type is changed to Software Keyboard
+ imfManager->KeyboardTypeChangedSignal().Emit( Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD );
+ break;
+ }
+ case ECORE_IMF_INPUT_PANEL_HW_KEYBOARD_MODE:
+ {
+ // Emit Signal that the keyboard type is changed to Hardware Keyboard
+ imfManager->KeyboardTypeChangedSignal().Emit( Dali::ImfManager::KeyboardType::HARDWARE_KEYBOARD );
+ break;
+ }
+ }
+}
+
+/**
+ * Called when an IMF delete surrounding event is received.
+ * Here we tell the application that it should delete a certain range.
+ */
+void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ imfManager->DeleteSurrounding( data, imfContext, event_info );
+ }
+}
+
+/**
+ * Called when the input method sends a private command.
+ */
+void PrivateCommand( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManagerEcoreWl* imfManager = reinterpret_cast< ImfManagerEcoreWl* > ( data );
+ imfManager->SendPrivateCommand( data, imfContext, event_info );
+ }
+}
+
+BaseHandle Create()
+{
+ return ImfManagerEcoreWl::Get();
+}
+
+TypeRegistration IMF_MANAGER_TYPE( typeid(Dali::ImfManager), typeid(Dali::BaseHandle), Create );
+
+} // unnamed namespace
+
+bool ImfManagerEcoreWl::IsAvailable()
+{
+ bool available( false );
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ available = service.GetSingleton( typeid( Dali::ImfManager ) );
+ }
+
+ return available;
+}
+
+Dali::ImfManager ImfManagerEcoreWl::Get()
+{
+ Dali::ImfManager manager;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
+ if( handle )
+ {
+ // If so, downcast the handle
+ manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
+ }
+ else if ( Adaptor::IsAvailable() )
+ {
+ // Create instance and register singleton only if the adaptor is available
+
+ Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
+ Any nativeWindow = adaptorImpl.GetNativeWindowHandle();
+
+ // The Ecore_Wl_Window needs to use the ImfManager.
+ // Only when the render surface is window, we can get the Ecore_Wl_Window.
+ Ecore_Wl_Window *ecoreWwin( AnyCast< Ecore_Wl_Window* >( nativeWindow ) );
+ if (ecoreWwin)
+ {
+ // If we fail to get Ecore_Wl_Window, we can't use the ImfManager correctly.
+ // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
+ // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
+
+ manager = Dali::ImfManager( new ImfManagerEcoreWl( ecoreWwin ) );
+ service.Register( typeid( manager ), manager );
+ }
+ else
+ {
+ DALI_LOG_ERROR("Failed to get native window handle\n");
+ }
+ }
+ }
+
+ return manager;
+}
+
+ImfManagerEcoreWl::ImfManagerEcoreWl( Ecore_Wl_Window *ecoreWlwin )
+: mIMFContext(),
+ mIMFCursorPosition( 0 ),
+ mSurroundingText(),
+ mRestoreAfterFocusLost( false ),
+ mIdleCallbackConnected( false )
+{
+ ecore_imf_init();
+ CreateContext( ecoreWlwin );
+
+ ConnectCallbacks();
+}
+
+ImfManagerEcoreWl::~ImfManagerEcoreWl()
+{
+ DisconnectCallbacks();
+
+ DeleteContext();
+ ecore_imf_shutdown();
+}
+
+void ImfManagerEcoreWl::CreateContext( Ecore_Wl_Window *ecoreWlwin )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CreateContext\n" );
+
+ const char *contextId = ecore_imf_context_default_id_get();
+ if( contextId )
+ {
+ mIMFContext = ecore_imf_context_add( contextId );
+
+ if( mIMFContext )
+ {
+ if( ecoreWlwin )
+ {
+ ecore_imf_context_client_window_set( mIMFContext,
+ reinterpret_cast<void*>( ecore_wl_window_id_get(ecoreWlwin)) );
+ }
+ }
+ else
+ {
+ DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
+ }
+ }
+ else
+ {
+ DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
+ }
+}
+
+void ImfManagerEcoreWl::DeleteContext()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteContext\n" );
+
+ if ( mIMFContext )
+ {
+ ecore_imf_context_del( mIMFContext );
+ mIMFContext = NULL;
+ }
+}
+
+// Callbacks for predicitive text support.
+void ImfManagerEcoreWl::ConnectCallbacks()
+{
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ConnectCallbacks\n" );
+
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this );
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this );
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this );
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand, this );
+
+ ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, this );
+ ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, this );
+ ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, this );
+ ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback, this );
+
+ ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this);
+ }
+}
+
+void ImfManagerEcoreWl::DisconnectCallbacks()
+{
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DisconnectCallbacks\n" );
+
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit );
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit );
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding );
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand );
+
+ ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback );
+ ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback );
+ ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback );
+ ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback );
+
+ // We do not need to unset the retrieve surrounding callback.
+ }
+}
+
+void ImfManagerEcoreWl::Activate()
+{
+ // Reset mIdleCallbackConnected
+ mIdleCallbackConnected = false;
+
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Activate\n" );
+
+ ecore_imf_context_focus_in( mIMFContext );
+
+ // emit keyboard activated signal
+ Dali::ImfManager handle( this );
+ mActivatedSignal.Emit( handle );
+ }
+}
+
+void ImfManagerEcoreWl::Deactivate()
+{
+ if( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Deactivate\n" );
+
+ Reset();
+ ecore_imf_context_focus_out( mIMFContext );
+ }
+
+ // Reset mIdleCallbackConnected
+ mIdleCallbackConnected = false;
+}
+
+void ImfManagerEcoreWl::Reset()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Reset\n" );
+
+ if ( mIMFContext )
+ {
+ ecore_imf_context_reset( mIMFContext );
+ }
+}
+
+ImfContext* ImfManagerEcoreWl::GetContext()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetContext\n" );
+
+ return reinterpret_cast<ImfContext*>(mIMFContext);
+}
+
+bool ImfManagerEcoreWl::RestoreAfterFocusLost() const
+{
+ return mRestoreAfterFocusLost;
+}
+
+void ImfManagerEcoreWl::SetRestoreAfterFocusLost( bool toggle )
+{
+ mRestoreAfterFocusLost = toggle;
+}
+
+/**
+ * Called when an IMF Pre-Edit changed event is received.
+ * We are still predicting what the user is typing. The latest string is what the IMF module thinks
+ * the user wants to type.
+ */
+void ImfManagerEcoreWl::PreEditChanged( void*, Ecore_IMF_Context* imfContext, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged\n" );
+
+ char* preEditString( NULL );
+ int cursorPosition( 0 );
+ Eina_List* attrs = NULL;
+ Eina_List* l = NULL;
+
+ Ecore_IMF_Preedit_Attr* attr;
+
+ // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string.
+ // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string.
+ ecore_imf_context_preedit_string_with_attributes_get( imfContext, &preEditString, &attrs, &cursorPosition );
+
+ if ( attrs )
+ {
+ // iterate through the list of attributes getting the type, start and end position.
+ for ( l = attrs, (attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ))
+ {
+#ifdef DALI_PROFILE_UBUNTU
+ if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB3 ) // (Ecore_IMF)
+#else // DALI_PROFILE_UBUNTU
+ if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB4 ) // (Ecore_IMF)
+#endif // DALI_PROFILE_UBUNTU
+ {
+ // check first byte so know how many bytes a character is represented by as keyboard returns cursor position in bytes. Which is different for some languages.
+
+ size_t visualCharacterIndex = 0;
+ size_t byteIndex = 0;
+
+ // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
+ const char leadByte = preEditString[byteIndex];
+ while( leadByte != '\0' )
+ {
+ // attr->end_index is provided as a byte position not character and we need to know the character position.
+ const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character.
+ if ( byteIndex == attr->end_index )
+ {
+ cursorPosition = visualCharacterIndex;
+ break;
+ // end loop as found cursor position that matches byte position
+ }
+ else
+ {
+ byteIndex += currentSequenceLength; // jump to next character
+ visualCharacterIndex++; // increment character count so we know our position for when we get a match
+ }
+
+ DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( preEditString ));
+ }
+ }
+ }
+ }
+
+ if ( Dali::Adaptor::IsAvailable() )
+ {
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::PREEDIT, preEditString, cursorPosition, 0 );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
+
+ if ( callbackData.update )
+ {
+ SetCursorPosition( callbackData.cursorPosition );
+ SetSurroundingText( callbackData.currentText );
+
+ NotifyCursorPosition();
+ }
+
+ if ( callbackData.preeditResetRequired )
+ {
+ Reset();
+ }
+ }
+ free( preEditString );
+}
+
+void ImfManagerEcoreWl::CommitReceived( void*, Ecore_IMF_Context* imfContext, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitReceived\n" );
+
+ if ( Dali::Adaptor::IsAvailable() )
+ {
+ const std::string keyString( static_cast<char*>( event_info ) );
+
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::COMMIT, keyString, 0, 0 );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
+
+ if( callbackData.update )
+ {
+ SetCursorPosition( callbackData.cursorPosition );
+ SetSurroundingText( callbackData.currentText );
+
+ NotifyCursorPosition();
+ }
+ }
+}
+
+/**
+ * Called when an IMF retrieve surround event is received.
+ * Here the IMF module wishes to know the string we are working with and where within the string the cursor is
+ * We need to signal the application to tell us this information.
+ */
+Eina_Bool ImfManagerEcoreWl::RetrieveSurrounding( void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::RetrieveSurrounding\n" );
+
+ Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::GETSURROUNDING, std::string(), 0, 0 );
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
+
+ if( callbackData.update )
+ {
+ if( text )
+ {
+ // The memory allocated by strdup() can be freed by ecore_imf_context_surrounding_get() internally.
+ *text = strdup( callbackData.currentText.c_str() );
+ }
+
+ if( cursorPosition )
+ {
+ mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
+ *cursorPosition = mIMFCursorPosition;
+ }
+ }
+
+ return EINA_TRUE;
+}
+
+/**
+ * Called when an IMF delete surrounding event is received.
+ * Here we tell the application that it should delete a certain range.
+ */
+void ImfManagerEcoreWl::DeleteSurrounding( void* data, Ecore_IMF_Context* imfContext, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurrounding\n" );
+
+ if( Dali::Adaptor::IsAvailable() )
+ {
+ Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast<Ecore_IMF_Event_Delete_Surrounding*>( event_info );
+
+ Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::DELETESURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars );
+ Dali::ImfManager handle( this );
+ mEventSignal.Emit( handle, imfData );
+ }
+}
+
+/**
+ * Called when the input method sends a private command.
+ */
+void ImfManagerEcoreWl::SendPrivateCommand( void* data, Ecore_IMF_Context* imfContext, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SendPrivateCommand\n" );
+
+ if( Dali::Adaptor::IsAvailable() )
+ {
+ const char* privateCommandSendEvent = static_cast<const char*>( event_info );
+
+ Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::PRIVATECOMMAND, privateCommandSendEvent, 0, 0 );
+ Dali::ImfManager handle( this );
+ mEventSignal.Emit( handle, imfData );
+ }
+}
+
+void ImfManagerEcoreWl::NotifyCursorPosition()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition );
+ }
+}
+
+void ImfManagerEcoreWl::SetCursorPosition( unsigned int cursorPosition )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetCursorPosition\n" );
+
+ mIMFCursorPosition = static_cast<int>( cursorPosition );
+}
+
+unsigned int ImfManagerEcoreWl::GetCursorPosition() const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetCursorPosition\n" );
+
+ return static_cast<unsigned int>( mIMFCursorPosition );
+}
+
+void ImfManagerEcoreWl::SetSurroundingText( const std::string& text )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetSurroundingText\n" );
+
+ mSurroundingText = text;
+}
+
+const std::string& ImfManagerEcoreWl::GetSurroundingText() const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetSurroundingText\n" );
+
+ return mSurroundingText;
+}
+
+void ImfManagerEcoreWl::NotifyTextInputMultiLine( bool multiLine )
+{
+ Ecore_IMF_Input_Hints currentHint = ecore_imf_context_input_hint_get(mIMFContext);
+ ecore_imf_context_input_hint_set( mIMFContext,
+ static_cast< Ecore_IMF_Input_Hints >( multiLine ?
+ (currentHint | ECORE_IMF_INPUT_HINT_MULTILINE) :
+ (currentHint & ~ECORE_IMF_INPUT_HINT_MULTILINE)));
+}
+
+Dali::ImfManager::TextDirection ImfManagerEcoreWl::GetTextDirection()
+{
+ Dali::ImfManager::TextDirection direction ( Dali::ImfManager::LeftToRight );
+
+ if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
+ {
+ if ( mIMFContext )
+ {
+ char* locale( NULL );
+ ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale );
+
+ if ( locale )
+ {
+ direction = static_cast< Dali::ImfManager::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
+ free( locale );
+ }
+ }
+ }
+ return direction;
+}
+
+Rect<int> ImfManagerEcoreWl::GetInputMethodArea()
+{
+ int xPos, yPos, width, height;
+
+ width = height = xPos = yPos = 0;
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height );
+ }
+ else
+ {
+ DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
+ // return 0 as real size unknown.
+ }
+
+ return Rect<int>(xPos,yPos,width,height);
+}
+
+void ImfManagerEcoreWl::ApplyOptions( const InputMethodOptions& options )
+{
+ using namespace Dali::InputMethod::Category;
+
+ int index;
+
+ if (mIMFContext == NULL)
+ {
+ DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n");
+ return;
+ }
+
+ if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) )
+ {
+ ecore_imf_context_input_panel_layout_set( mIMFContext, panelLayoutMap[index] );
+ }
+ if ( mOptions.CompareAndSet(AUTO_CAPITALISE, options, index) )
+ {
+ ecore_imf_context_autocapital_type_set( mIMFContext, autoCapitalMap[index] );
+ }
+ if ( mOptions.CompareAndSet(ACTION_BUTTON_TITLE, options, index) )
+ {
+ ecore_imf_context_input_panel_return_key_type_set( mIMFContext, returnKeyTypeMap[index] );
+ }
+ if ( mOptions.CompareAndSet(VARIATION, options, index) )
+ {
+ ecore_imf_context_input_panel_layout_variation_set( mIMFContext, index );
+ }
+}
+
+void ImfManagerEcoreWl::SetInputPanelData( const std::string& data )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetInputPanelData\n" );
+
+ if( mIMFContext )
+ {
+ int length = data.length();
+ ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length );
+ }
+}
+
+void ImfManagerEcoreWl::GetInputPanelData( std::string& data )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelData\n" );
+
+ if( mIMFContext )
+ {
+ int length = 4096; // The max length is 4096 bytes
+ Dali::Vector< char > buffer;
+ buffer.Resize( length );
+ ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length );
+ data = std::string( buffer.Begin(), buffer.End() );
+ }
+}
+
+Dali::ImfManager::State ImfManagerEcoreWl::GetInputPanelState()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelState\n" );
+
+ if( mIMFContext )
+ {
+ int value;
+ value = ecore_imf_context_input_panel_state_get( mIMFContext );
+
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
+ {
+ return Dali::ImfManager::SHOW;
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
+ {
+ return Dali::ImfManager::HIDE;
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
+ {
+ return Dali::ImfManager::WILL_SHOW;
+ break;
+ }
+
+ default:
+ {
+ return Dali::ImfManager::DEFAULT;
+ }
+ }
+ }
+ return Dali::ImfManager::DEFAULT;
+}
+
+void ImfManagerEcoreWl::SetReturnKeyState( bool visible )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetReturnKeyState\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible );
+ }
+}
+
+void ImfManagerEcoreWl::AutoEnableInputPanel( bool enabled )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::AutoEnableInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled );
+ }
+}
+
+void ImfManagerEcoreWl::ShowInputPanel()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ShowInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_show( mIMFContext );
+ }
+}
+
+void ImfManagerEcoreWl::HideInputPanel()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::HideInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_hide( mIMFContext );
+ }
+}
+
+Dali::ImfManager::KeyboardType ImfManagerEcoreWl::GetKeyboardType()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetKeyboardType\n" );
+
+#ifdef OVER_TIZEN_VERSION_4
+ if( mIMFContext )
+ {
+ int value;
+ value = ecore_imf_context_keyboard_mode_get( mIMFContext );
+
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE:
+ {
+ return Dali::ImfManager::SOFTWARE_KEYBOARD;
+ break;
+ }
+ case ECORE_IMF_INPUT_PANEL_HW_KEYBOARD_MODE:
+ {
+ return Dali::ImfManager::HARDWARE_KEYBOARD;
+ break;
+ }
+ }
+ }
+#endif // OVER_TIZEN_VERSION_4
+ return Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD;
+}
+
+std::string ImfManagerEcoreWl::GetInputPanelLocale()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelLocale\n" );
+
+ std::string locale = "";
+
+ if( mIMFContext )
+ {
+ char* value = NULL;
+ ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value );
+
+ if( value )
+ {
+ std::string valueCopy( value );
+ locale = valueCopy;
+
+ // The locale string retrieved must be freed with free().
+ free( value );
+ }
+ }
+ return locale;
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_ECORE_WL_H
+#define DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_ECORE_WL_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_IMF.h>
+#include <Ecore.h>
+#include <Ecore_Wayland.h>
+
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/integration-api/events/key-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/imf-manager-impl.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class DALI_IMPORT_API ImfManagerEcoreWl : public Dali::Internal::Adaptor::ImfManager
+{
+public:
+
+ /**
+ * Check whether the ImfManager is available.
+ * @return true if available, false otherwise
+ */
+ static bool IsAvailable();
+
+ /**
+ * Get the IMF manager instance, it creates the instance if it has not already been created.
+ * Internally, a check should be made using IsAvailable() before this is called as we do not want
+ * to create an instance if not needed by applications.
+ * @see IsAvailable()
+ */
+ static Dali::ImfManager Get();
+
+ /**
+ * Connect Callbacks required for IMF.
+ * If you don't connect imf callbacks, you can't get the key events.
+ * The events are PreeditChanged, Commit, DeleteSurrounding and PrivateCommand.
+ */
+ void ConnectCallbacks() override;
+
+ /**
+ * Disconnect Callbacks attached to imf context.
+ */
+ void DisconnectCallbacks() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Activate()
+ */
+ void Activate() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Deactivate()
+ */
+ void Deactivate() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Reset()
+ */
+ void Reset() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetContext()
+ */
+ ImfContext* GetContext() override;
+
+ /**
+ * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
+ */
+ bool RestoreAfterFocusLost() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
+ */
+ void SetRestoreAfterFocusLost( bool toggle ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::PreEditChanged()
+ */
+ void PreEditChanged( void *data, Ecore_IMF_Context *imfContext, void *event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void CommitReceived( void *data, Ecore_IMF_Context *imfContext, void *event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ Eina_Bool RetrieveSurrounding( void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition );
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteSurrounding()
+ */
+ void DeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info );
+
+ /**
+ * @copydoc Dali::ImfManager::SendPrivateCommand()
+ */
+ void SendPrivateCommand( void* data, Ecore_IMF_Context* imfContext, void* event_info );
+
+ // Cursor related
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void NotifyCursorPosition() override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetCursorPosition()
+ */
+ void SetCursorPosition( unsigned int cursorPosition ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetCursorPosition()
+ */
+ unsigned int GetCursorPosition() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetSurroundingText()
+ */
+ void SetSurroundingText( const std::string& text ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetSurroundingText()
+ */
+ const std::string& GetSurroundingText() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
+ */
+ void NotifyTextInputMultiLine( bool multiLine ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetTextDirection()
+ */
+ Dali::ImfManager::TextDirection GetTextDirection() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputMethodArea()
+ */
+ Dali::Rect<int> GetInputMethodArea() override;
+
+ /**
+ * @copydoc Dali::ImfManager::ApplyOptions()
+ */
+ void ApplyOptions( const InputMethodOptions& options ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetInputPanelData()
+ */
+ void SetInputPanelData( const std::string& data ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelData()
+ */
+ void GetInputPanelData( std::string& data ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelState()
+ */
+ Dali::ImfManager::State GetInputPanelState() override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetReturnKeyState()
+ */
+ void SetReturnKeyState( bool visible ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::AutoEnableInputPanel()
+ */
+ void AutoEnableInputPanel( bool enabled ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::ShowInputPanel()
+ */
+ void ShowInputPanel() override;
+
+ /**
+ * @copydoc Dali::ImfManager::HideInputPanel()
+ */
+ void HideInputPanel() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetKeyboardType()
+ */
+ Dali::ImfManager::KeyboardType GetKeyboardType() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelLocale()
+ */
+ std::string GetInputPanelLocale() override;
+
+protected:
+
+ /**
+ * Destructor.
+ */
+ virtual ~ImfManagerEcoreWl() override;
+
+private:
+ /**
+ * Context created the first time and kept until deleted.
+ * @param[in] ecoreWlwin, The window is created by application.
+ */
+ void CreateContext( Ecore_Wl_Window *ecoreWlwin );
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteContext()
+ */
+ void DeleteContext();
+
+private:
+ // Undefined
+ explicit ImfManagerEcoreWl( Ecore_Wl_Window *ecoreWlwin );
+ explicit ImfManagerEcoreWl( const ImfManager& ) = delete;
+ ImfManagerEcoreWl& operator=( ImfManager& ) = delete;
+
+private:
+ Ecore_IMF_Context* mIMFContext;
+ int mIMFCursorPosition;
+ std::string mSurroundingText;
+
+ bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
+ bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected.
+
+ std::vector<Dali::Integration::KeyEvent> mKeyEvents; ///< Stores key events to be sent from idle call-back.
+ InputMethodOptions mOptions;
+};
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_ECORE_WL_H
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/tizen/key-grab.h>
+
+// EXTERNAL INCLUDES
+#include <Ecore_Wayland.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/window.h>
+#include <dali/internal/input/common/key-impl.h>
+
+#include <iostream>
+#include <string.h>
+
+using namespace std;
+
+namespace Dali
+{
+
+namespace KeyGrab
+{
+
+bool GrabKeyTopmost( Window window, Dali::KEY daliKey )
+{
+ return GrabKey( window, daliKey, TOPMOST);
+}
+
+
+bool UngrabKeyTopmost( Window window, Dali::KEY daliKey )
+{
+ return UngrabKey( window, daliKey );
+}
+
+
+bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode )
+{
+ Ecore_Wl_Window_Keygrab_Mode wlGrabMode;
+ if( grabMode == TOPMOST )
+ {
+ wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_TOPMOST;
+ }
+ else if( grabMode == SHARED )
+ {
+ wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_SHARED;
+ }
+ else if( grabMode == OVERRIDE_EXCLUSIVE )
+ {
+ wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_OVERRIDE_EXCLUSIVE;
+ }
+ else if( grabMode == EXCLUSIVE )
+ {
+ wlGrabMode = ECORE_WL_WINDOW_KEYGRAB_EXCLUSIVE;
+ }
+ else
+ {
+ return false;
+ }
+
+ return ecore_wl_window_keygrab_set( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ),
+ Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ),
+ 0, 0, 0, wlGrabMode );
+}
+
+
+bool UngrabKey( Window window, Dali::KEY daliKey )
+{
+ return ecore_wl_window_keygrab_unset( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ),
+ Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKey ),
+ 0, 0 );
+}
+
+
+bool GrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, const Dali::Vector<KeyGrabMode>& grabModeVector, Dali::Vector<bool>& returnVector)
+{
+ const Dali::Vector<bool>::SizeType returnCount = returnVector.Count();
+ const Dali::Vector<Dali::KEY>::SizeType keyCount = daliKeyVector.Count();
+ const Dali::Vector<KeyGrabMode>::SizeType keyGrabModeCount = grabModeVector.Count();
+
+ if( keyCount != keyGrabModeCount || keyCount != returnCount || keyCount == 0 )
+ {
+ return false;
+ }
+
+ eina_init();
+
+ Eina_List* keyList = NULL;
+ {
+ for( Dali::Vector<float>::SizeType index = 0; index < keyCount; ++index )
+ {
+ Ecore_Wl_Window_Keygrab_Info info;
+ info.key = const_cast<char*>(Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKeyVector[index] ));
+
+ switch( grabModeVector[index] )
+ {
+ case TOPMOST:
+ {
+ info.mode = ECORE_WL_WINDOW_KEYGRAB_TOPMOST;
+ break;
+ }
+ case SHARED:
+ {
+ info.mode = ECORE_WL_WINDOW_KEYGRAB_SHARED;
+ break;
+ }
+ case OVERRIDE_EXCLUSIVE:
+ {
+ info.mode = ECORE_WL_WINDOW_KEYGRAB_OVERRIDE_EXCLUSIVE;
+ break;
+ }
+ case EXCLUSIVE:
+ {
+ info.mode = ECORE_WL_WINDOW_KEYGRAB_EXCLUSIVE;
+ break;
+ }
+ default:
+ {
+ info.mode = ECORE_WL_WINDOW_KEYGRAB_UNKNOWN;
+ break;
+ }
+ }
+
+ keyList = eina_list_append( keyList, &info );
+ }
+ }
+
+ Eina_List* grabList = ecore_wl_window_keygrab_list_set( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ), keyList );
+
+ returnVector.Resize( keyCount, true );
+
+ Eina_List* l = NULL;
+ Eina_List* m = NULL;
+ void *listData = NULL;
+ void *data = NULL;
+ if( grabList != NULL )
+ {
+ EINA_LIST_FOREACH( grabList, m, data )
+ {
+ Dali::Vector<float>::SizeType index = 0;
+ EINA_LIST_FOREACH( keyList, l, listData )
+ {
+ if((static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData))->key == NULL)
+ {
+ DALI_LOG_ERROR("input key list has null data!");
+ break;
+ }
+
+ if( strcmp( static_cast<char*>(data), static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData)->key ) == 0 )
+ {
+ returnVector[index] = false;
+ }
+ ++index;
+ }
+ }
+ }
+
+ eina_list_free( keyList );
+ eina_list_free( grabList );
+ eina_shutdown();
+
+ return true;
+}
+
+bool UngrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, Dali::Vector<bool>& returnVector)
+{
+ const Dali::Vector<bool>::SizeType returnCount = returnVector.Count();
+ const Dali::Vector<Dali::KEY>::SizeType keyCount = daliKeyVector.Count();
+
+ if( keyCount != returnCount ||keyCount == 0 )
+ {
+ return false;
+ }
+
+ eina_init();
+
+ Eina_List* keyList = NULL;
+ {
+ for( Dali::Vector<float>::SizeType index = 0; index < keyCount; ++index )
+ {
+ Ecore_Wl_Window_Keygrab_Info info;
+ info.key = const_cast<char*>(Dali::Internal::Adaptor::KeyLookup::GetKeyName( daliKeyVector[index] ));
+ keyList = eina_list_append( keyList, &info );
+ }
+ }
+
+ Eina_List* ungrabList = ecore_wl_window_keygrab_list_unset( AnyCast<Ecore_Wl_Window*>( window.GetNativeHandle() ), keyList );
+
+ returnVector.Resize( keyCount, true );
+
+ Eina_List* l = NULL;
+ Eina_List* m = NULL;
+ void *listData = NULL;
+ void *data = NULL;
+
+ if( ungrabList != NULL )
+ {
+ EINA_LIST_FOREACH( ungrabList, m, data )
+ {
+ Dali::Vector<float>::SizeType index = 0;
+ EINA_LIST_FOREACH( keyList, l, listData )
+ {
+ if( strcmp( static_cast<char*>(data), static_cast<Ecore_Wl_Window_Keygrab_Info*>(listData)->key ) == 0 )
+ {
+ returnVector[index] = false;
+ }
+ ++index;
+ }
+ }
+ }
+
+ eina_list_free( keyList );
+ eina_list_free( ungrabList );
+ eina_shutdown();
+
+ return true;
+}
+
+} // namespace KeyGrab
+
+} // namespace Dali
+
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/key-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace KeyLookup
+{
+
+// matches a DALI_KEY enum, to a key name
+KeyLookup KeyLookupTable[]=
+{
+ // more than one key name can be assigned to a single dali-key code
+ // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
+
+ { "Escape", DALI_KEY_ESCAPE , false },
+ { "Menu", DALI_KEY_MENU, false },
+
+ // Now literal strings are used as key names instead of defined symbols in utilX,
+ // since these definition in utilX.h is deprecated
+ { "XF86Camera", DALI_KEY_CAMERA, false },
+ { "XF86Camera_Full", DALI_KEY_CONFIG, false },
+ { "XF86PowerOff", DALI_KEY_POWER, true },
+ { "XF86Standby", DALI_KEY_PAUSE, false },
+ { "Cancel", DALI_KEY_CANCEL, false },
+ { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
+ { "XF86AudioStop", DALI_KEY_STOP_CD, false },
+ { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
+ { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
+ { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
+ { "XF86AudioRewind", DALI_KEY_REWIND, false },
+ { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
+ { "XF86AudioMedia", DALI_KEY_MEDIA, false },
+ { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
+ { "XF86AudioMute", DALI_KEY_MUTE, false },
+ { "XF86Menu", DALI_KEY_MENU, true },
+ { "XF86Home", DALI_KEY_HOME, true },
+ { "XF86Back", DALI_KEY_BACK, true },
+ { "XF86Send", DALI_KEY_MENU, true },
+ { "XF86Phone", DALI_KEY_HOME, true },
+ { "XF86Stop", DALI_KEY_BACK, true },
+ { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
+ { "XF86WWW", DALI_KEY_WEBPAGE, false },
+ { "XF86Mail", DALI_KEY_MAIL, false },
+ { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
+ { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
+ { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
+ { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
+ { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
+ { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
+ { "XF86Apps", DALI_KEY_APPS, false },
+ { "XF86Search", DALI_KEY_SEARCH, false },
+ { "XF86Voice", DALI_KEY_VOICE, false },
+ { "Hangul", DALI_KEY_LANGUAGE, false },
+ { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
+ { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
+
+ { "BackSpace", DALI_KEY_BACKSPACE, false },
+ { "Left", DALI_KEY_CURSOR_LEFT, false },
+ { "Right", DALI_KEY_CURSOR_RIGHT, false },
+ { "left", DALI_KEY_CURSOR_LEFT, false }, // To be removed after the key name is fixed in the platform
+ { "right", DALI_KEY_CURSOR_RIGHT, false }, // To be removed after the key name is fixed in the platform
+ { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
+ { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
+ { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
+ { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
+ { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
+ { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
+};
+
+const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
+
+} // namespace KeyLookup
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/virtual-keyboard-impl.h>
+
+// EXTERNAL INCLUDES
+#include <Ecore.h>
+#include <Ecore_Wayland.h>
+#include <Ecore_IMF.h>
+#include <algorithm>
+
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/adaptor.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/input/common/imf-manager-impl.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace VirtualKeyboard
+{
+
+Dali::InputMethod::ActionButton gActionButtonFunction = Dali::InputMethod::ACTION_DEFAULT;
+
+Ecore_IMF_Input_Panel_Return_Key_Type actionButtonMapping(Dali::InputMethod::ActionButton actionButton )
+{
+ switch( actionButton )
+ {
+ case InputMethod::ACTION_DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE;
+ case InputMethod::ACTION_GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO;
+ case InputMethod::ACTION_JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN;
+ case InputMethod::ACTION_LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN;
+ case InputMethod::ACTION_NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT;
+ case InputMethod::ACTION_PREVIOUS: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH;
+ case InputMethod::ACTION_SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND;
+ case InputMethod::ACTION_SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_UNSPECIFIED: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_NONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ }
+}
+
+void RotateTo(int angle)
+{
+}
+
+void SetReturnKeyType( const InputMethod::ActionButton type )
+{
+ Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when setting values
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if( imfContext )
+ {
+ gActionButtonFunction = type;
+ ecore_imf_context_input_panel_return_key_type_set( imfContext, actionButtonMapping( type ) );
+ }
+}
+
+Dali::InputMethod::ActionButton GetReturnKeyType()
+{
+ return gActionButtonFunction;
+}
+
+} // namespace VirtualKeyboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_KEY_GRAB_H__
+#define __DALI_KEY_GRAB_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/public-api/adaptor-framework/key.h>
+
+namespace Dali
+{
+/**
+ * @addtogroup dali_adaptor_framework
+ * @{
+ */
+
+class Window;
+
+/**
+ * @brief Key grab functions.
+ * @SINCE_1_0.0
+ */
+namespace KeyGrab
+{
+
+/**
+ * @brief Grabs the key specified by @a key for @a window only when @a window is the topmost window.
+ *
+ * This function can be used for following example scenarios:
+ * - Mobile - Using volume up/down as zoom up/down in camera apps.
+ *
+ * @SINCE_1_0.0
+ * @param[in] window The window to set
+ * @param[in] daliKey The key code to grab (defined in key.h)
+ * @return true if the grab succeeds
+ */
+DALI_IMPORT_API bool GrabKeyTopmost( Window window, Dali::KEY daliKey );
+
+/**
+ * @brief Ungrabs the key specified by @a key for @a window.
+ *
+ * @SINCE_1_0.0
+ * @param[in] window The window to set
+ * @param[in] daliKey The key code to ungrab (defined in key.h)
+ * @return true if the ungrab succeeds
+ * @note If this function is called between key down and up events of a grabbed key,
+ * an application doesn't receive the key up event.
+ */
+DALI_IMPORT_API bool UngrabKeyTopmost( Window window, Dali::KEY daliKey );
+
+/**
+ * @brief Enumeration for key grab mode for platform-level APIs.
+ * @SINCE_1_0.0
+ */
+enum KeyGrabMode
+{
+ TOPMOST = 0, ///< Grab a key only when on the top of the grabbing-window stack mode. @SINCE_1_0.0
+ SHARED, ///< Grab a key together with the other client window(s) mode. @SINCE_1_0.0
+ OVERRIDE_EXCLUSIVE, ///< Grab a key exclusively regardless of the grabbing-window's position on the window stack with the possibility of overriding the grab by the other client window mode. @SINCE_1_0.0
+ EXCLUSIVE ///< Grab a key exclusively regardless of the grabbing-window's position on the window stack mode. @SINCE_1_0.0
+};
+
+/**
+ * @PLATFORM
+ * @brief Grabs the key specified by @a key for @a window in @a grabMode.
+ *
+ * @details This function can be used for following example scenarios:
+ * - TV - A user might want to change the volume or channel of the background TV contents while focusing on the foregrund app.
+ * - Mobile - When a user presses Home key, the homescreen appears regardless of current foreground app.
+ * - Mobile - Using volume up/down as zoom up/down in camera apps.
+ *
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PLATFORM
+ * @PRIVILEGE_KEYGRAB
+ * @param[in] window The window to set
+ * @param[in] daliKey The key code to grab (defined in key.h)
+ * @param[in] grabMode The grab mode for the key
+ * @return true if the grab succeeds
+ */
+DALI_IMPORT_API bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode );
+
+/**
+ * @PLATFORM
+ * @brief Ungrabs the key specified by @a key for @a window.
+ *
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PLATFORM
+ * @PRIVILEGE_KEYGRAB
+ * @param[in] window The window to set
+ * @param[in] daliKey The key code to ungrab (defined in key.h)
+ * @return true if the ungrab succeeds
+ * @note If this function is called between key down and up events of a grabbed key,
+ * an application doesn't receive the key up event.
+ */
+DALI_IMPORT_API bool UngrabKey( Window window, Dali::KEY daliKey );
+
+
+/**
+ * @PLATFORM
+ * @brief Grabs the list of keys specified by Dali::Vector of keys for @a window in Dali::Vector of grabModes.
+ *
+ * @details This function can be used for following example scenarios:
+ * - TV - A user might want to change the volume or channel of the background TV contents while focusing on the foregrund app.
+ * - Mobile - When a user presses Home key, the homescreen appears regardless of current foreground app.
+ * - Mobile - Using volume up/down as zoom up/down in camera apps.
+ *
+ * @SINCE_1_2.0
+ * @PRIVLEVEL_PLATFORM
+ * @PRIVILEGE_KEYGRAB
+ * @param[in] window The window to set
+ * @param[in] daliKeyVector The Dali::Vector of key codes to grab (defined in key.h)
+ * @param[in] grabModeVector The Dali::Vector of grab modes for the keys
+ * @param[in] returnVector The Dali::Vector of return boolean values for the results of multiple grab succeeds/fails
+ * @return bool false when error occurs
+ */
+DALI_IMPORT_API bool GrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, const Dali::Vector<KeyGrabMode>& grabModeVector, Dali::Vector<bool>& returnVector);
+
+
+/**
+ * @PLATFORM
+ * @brief Ungrabs the list of keys specified by Dali::Vector of keys for @a window.
+ *
+ * @SINCE_1_2.0
+ * @PRIVLEVEL_PLATFORM
+ * @PRIVILEGE_KEYGRAB
+ * @param[in] window The window to set
+ * @param[in] daliKeyVector The Dali::Vector of key codes to ungrab (defined in key.h)
+ * @param[in] returnVector The Dali::Vector of return boolean values for the results of multiple ungrab succeeds/fails
+ * @return bool false when error occurs
+ * @note If this function is called between key down and up events of a grabbed key,
+ * an application doesn't receive the key up event.
+ */
+DALI_IMPORT_API bool UngrabKeyList( Window window, const Dali::Vector<Dali::KEY>& daliKeyVector, Dali::Vector<bool>& returnVector);
+
+
+} // namespace KeyGrab
+
+/**
+ * @}
+ */
+} // namespace Dali
+
+#endif // __DALI_KEY_GRAB_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+#include <dali/internal/input/ubuntu-x11/imf-manager-impl-x.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class ImfManager;
+
+template<typename T, typename... Args>
+std::unique_ptr<T> MakeUnique(Args&&... args)
+{
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+namespace ImfManagerFactory
+{
+
+// ImfManager Factory to be implemented by the platform
+Dali::ImfManager CreateImfManager()
+{
+ return Dali::Internal::Adaptor::ImfManagerX::Get();
+}
+
+}
+
+}
+
+
+
+}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/ubuntu-x11/imf-manager-impl-x.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/events/key-event.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/adaptor.h>
+#include <dali/internal/window-system/ubuntu-x11/window-render-surface-x.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/internal/input/common/virtual-keyboard-impl.h>
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
+#endif
+
+// Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
+size_t Utf8SequenceLength(const unsigned char leadByte)
+{
+ size_t length = 0;
+
+ if ((leadByte & 0x80) == 0 ) //ASCII character (lead bit zero)
+ {
+ length = 1;
+ }
+ else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
+ {
+ length = 2;
+ }
+ else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
+ {
+ length = 3;
+ }
+ else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
+ {
+ length = 4;
+ }
+
+ return length;
+}
+
+// Static function calls used by ecore 'c' style callback registration
+void Commit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
+ imfManager->CommitReceived( data, imfContext, event_info );
+ }
+}
+
+void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
+ imfManager->PreEditChanged( data, imfContext, event_info );
+ }
+}
+
+Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
+{
+ if ( data )
+ {
+ ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
+ return imfManager->RetrieveSurrounding( data, imfContext, text, cursorPosition );
+ }
+ else
+ {
+ return false;
+ }
+}
+
+/**
+ * Called when an IMF delete surrounding event is received.
+ * Here we tell the application that it should delete a certain range.
+ */
+void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
+{
+ if ( data )
+ {
+ ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
+ imfManager->DeleteSurrounding( data, imfContext, event_info );
+ }
+}
+
+} // unnamed namespace
+
+bool ImfManagerX::IsAvailable()
+{
+ bool available( false );
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ available = service.GetSingleton( typeid( Dali::ImfManager ) );
+ }
+
+ return available;
+}
+
+Dali::ImfManager ImfManagerX::Get()
+{
+ Dali::ImfManager manager;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
+ if( handle )
+ {
+ // If so, downcast the handle
+ manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
+ }
+ else if ( Adaptor::IsAvailable() )
+ {
+ // Create instance and register singleton only if the adaptor is available
+
+ Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
+ Any nativeWindow = adaptorImpl.GetNativeWindowHandle();
+
+ // The Ecore_X_Window needs to use the ImfManager.
+ // Only when the render surface is window, we can get the Ecore_X_Window.
+ Ecore_X_Window ecoreXwin( AnyCast<Ecore_X_Window>(nativeWindow) );
+ if (ecoreXwin)
+ {
+ // If we fail to get Ecore_X_Window, we can't use the ImfManager correctly.
+ // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
+ // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
+
+ manager = Dali::ImfManager( new ImfManagerX( ecoreXwin ) );
+ service.Register( typeid( manager ), manager );
+ }
+ else
+ {
+ DALI_LOG_ERROR("Failed to get native window handle\n");
+ }
+ }
+ }
+
+ return manager;
+}
+
+ImfManagerX::ImfManagerX( Ecore_X_Window ecoreXwin )
+: mIMFContext(),
+ mIMFCursorPosition( 0 ),
+ mSurroundingText(),
+ mRestoreAfterFocusLost( false ),
+ mIdleCallbackConnected( false )
+{
+ ecore_imf_init();
+ CreateContext( ecoreXwin );
+
+ ConnectCallbacks();
+ VirtualKeyboard::ConnectCallbacks( mIMFContext );
+}
+
+ImfManagerX::~ImfManagerX()
+{
+ VirtualKeyboard::DisconnectCallbacks( mIMFContext );
+ DisconnectCallbacks();
+
+ DeleteContext();
+ ecore_imf_shutdown();
+}
+
+void ImfManagerX::CreateContext( Ecore_X_Window ecoreXwin )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CreateContext\n" );
+
+ const char *contextId = ecore_imf_context_default_id_get();
+ if( contextId )
+ {
+ mIMFContext = ecore_imf_context_add( contextId );
+
+ if( mIMFContext )
+ {
+ if( ecoreXwin )
+ {
+ ecore_imf_context_client_window_set( mIMFContext, reinterpret_cast<void*>( ecoreXwin ) );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "IMF Unable to get IMF Context\n");
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "IMF Unable to get IMF Context\n");
+ }
+}
+
+void ImfManagerX::DeleteContext()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteContext\n" );
+
+ if ( mIMFContext )
+ {
+ ecore_imf_context_del( mIMFContext );
+ mIMFContext = NULL;
+ }
+}
+
+// Callbacks for predicitive text support.
+void ImfManagerX::ConnectCallbacks()
+{
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ConnectCallbacks\n" );
+
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this );
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this );
+ ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this );
+
+ ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this);
+ }
+}
+
+void ImfManagerX::DisconnectCallbacks()
+{
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DisconnectCallbacks\n" );
+
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit );
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit );
+ ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding );
+
+ // We do not need to unset the retrieve surrounding callback.
+ }
+}
+
+void ImfManagerX::Activate()
+{
+ // Reset mIdleCallbackConnected
+ mIdleCallbackConnected = false;
+
+ if ( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Activate\n" );
+
+ ecore_imf_context_focus_in( mIMFContext );
+
+ // emit keyboard activated signal
+ Dali::ImfManager handle( this );
+ mActivatedSignal.Emit( handle );
+ }
+}
+
+void ImfManagerX::Deactivate()
+{
+ if( mIMFContext )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Deactivate\n" );
+
+ Reset();
+ ecore_imf_context_focus_out( mIMFContext );
+ }
+
+ // Reset mIdleCallbackConnected
+ mIdleCallbackConnected = false;
+}
+
+void ImfManagerX::Reset()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Reset\n" );
+
+ if ( mIMFContext )
+ {
+ ecore_imf_context_reset( mIMFContext );
+ }
+}
+
+ImfContext* ImfManagerX::GetContext()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetContext\n" );
+
+ return mIMFContext;
+}
+
+bool ImfManagerX::RestoreAfterFocusLost() const
+{
+ return mRestoreAfterFocusLost;
+}
+
+void ImfManagerX::SetRestoreAfterFocusLost( bool toggle )
+{
+ mRestoreAfterFocusLost = toggle;
+}
+
+/**
+ * Called when an IMF Pre-Edit changed event is received.
+ * We are still predicting what the user is typing. The latest string is what the IMF module thinks
+ * the user wants to type.
+ */
+void ImfManagerX::PreEditChanged( void*, ImfContext * context, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged\n" );
+
+ auto imfContext = reinterpret_cast<Ecore_IMF_Context*>(context);
+
+ char* preEditString( NULL );
+ int cursorPosition( 0 );
+ Eina_List* attrs = NULL;
+ Eina_List* l = NULL;
+
+ Ecore_IMF_Preedit_Attr* attr;
+
+ // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string.
+ // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string.
+ ecore_imf_context_preedit_string_with_attributes_get( imfContext, &preEditString, &attrs, &cursorPosition );
+
+ if ( attrs )
+ {
+ // iterate through the list of attributes getting the type, start and end position.
+ for ( l = attrs, (attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast<Ecore_IMF_Preedit_Attr*>( eina_list_data_get(l) ) ))
+ {
+#ifdef DALI_PROFILE_UBUNTU
+ if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB3 ) // (Ecore_IMF)
+#else // DALI_PROFILE_UBUNTU
+ if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB4 ) // (Ecore_IMF)
+#endif // DALI_PROFILE_UBUNTU
+ {
+ // check first byte so know how many bytes a character is represented by as keyboard returns cursor position in bytes. Which is different for some languages.
+
+ size_t visualCharacterIndex = 0;
+ size_t byteIndex = 0;
+
+ // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
+ const char leadByte = preEditString[byteIndex];
+ while( leadByte != '\0' )
+ {
+ // attr->end_index is provided as a byte position not character and we need to know the character position.
+ const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character.
+ if ( byteIndex == attr->end_index )
+ {
+ cursorPosition = visualCharacterIndex;
+ break;
+ // end loop as found cursor position that matches byte position
+ }
+ else
+ {
+ byteIndex += currentSequenceLength; // jump to next character
+ visualCharacterIndex++; // increment character count so we know our position for when we get a match
+ }
+
+ DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( preEditString ));
+ }
+ }
+ }
+ }
+
+ if ( Dali::Adaptor::IsAvailable() )
+ {
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::PREEDIT, preEditString, cursorPosition, 0 );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
+
+ if( callbackData.update )
+ {
+ mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
+
+ NotifyCursorPosition();
+ }
+
+ if( callbackData.preeditResetRequired )
+ {
+ Reset();
+ }
+ }
+ free( preEditString );
+}
+
+void ImfManagerX::CommitReceived( void*, ImfContext* context, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitReceived\n" );
+
+ if ( Dali::Adaptor::IsAvailable() )
+ {
+ const std::string keyString( static_cast<char*>( event_info ) );
+
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfEventData imfEventData( Dali::ImfManager::COMMIT, keyString, 0, 0 );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
+
+ if( callbackData.update )
+ {
+ mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
+
+ NotifyCursorPosition();
+ }
+ }
+}
+
+/**
+ * Called when an IMF retrieve surround event is received.
+ * Here the IMF module wishes to know the string we are working with and where within the string the cursor is
+ * We need to signal the application to tell us this information.
+ */
+bool ImfManagerX::RetrieveSurrounding( void* data, ImfContext* context, char** text, int* cursorPosition )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::RetrieveSurrounding\n" );
+
+ Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::GETSURROUNDING, std::string(), 0, 0 );
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
+
+ if( callbackData.update )
+ {
+ if( text )
+ {
+ *text = strdup( callbackData.currentText.c_str() );
+ }
+
+ if( cursorPosition )
+ {
+ mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
+ *cursorPosition = mIMFCursorPosition;
+ }
+ }
+
+ return EINA_TRUE;
+}
+
+/**
+ * Called when an IMF delete surrounding event is received.
+ * Here we tell the application that it should delete a certain range.
+ */
+void ImfManagerX::DeleteSurrounding( void* data, ImfContext* context, void* event_info )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurrounding\n" );
+
+ if( Dali::Adaptor::IsAvailable() )
+ {
+ Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast<Ecore_IMF_Event_Delete_Surrounding*>( event_info );
+
+ Dali::ImfManager::ImfEventData imfData( Dali::ImfManager::DELETESURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars );
+ Dali::ImfManager handle( this );
+ Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfData );
+
+ if( callbackData.update )
+ {
+ mIMFCursorPosition = static_cast<int>( callbackData.cursorPosition );
+
+ NotifyCursorPosition();
+ }
+ }
+}
+
+void ImfManagerX::NotifyCursorPosition()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition );
+ }
+}
+
+void ImfManagerX::SetCursorPosition( unsigned int cursorPosition )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetCursorPosition\n" );
+
+ mIMFCursorPosition = static_cast<int>( cursorPosition );
+}
+
+unsigned int ImfManagerX::GetCursorPosition() const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetCursorPosition\n" );
+
+ return static_cast<unsigned int>( mIMFCursorPosition );
+}
+
+void ImfManagerX::SetSurroundingText( const std::string& text )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetSurroundingText\n" );
+
+ mSurroundingText = text;
+}
+
+const std::string& ImfManagerX::GetSurroundingText() const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetSurroundingText\n" );
+
+ return mSurroundingText;
+}
+
+void ImfManagerX::NotifyTextInputMultiLine( bool multiLine )
+{
+}
+
+Dali::ImfManager::TextDirection ImfManagerX::GetTextDirection()
+{
+ Dali::ImfManager::TextDirection direction ( Dali::ImfManager::LeftToRight );
+
+ if ( ImfManager::IsAvailable() /* We do not want to create an instance of ImfManager */ )
+ {
+ if ( mIMFContext )
+ {
+ char* locale( NULL );
+ ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale );
+
+ if ( locale )
+ {
+ direction = static_cast< Dali::ImfManager::TextDirection >( Locale::GetDirection( std::string( locale ) ) );
+ free( locale );
+ }
+ }
+ }
+ return direction;
+}
+
+Rect<int> ImfManagerX::GetInputMethodArea()
+{
+ int xPos, yPos, width, height;
+
+ width = height = xPos = yPos = 0;
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height );
+ }
+ else
+ {
+ DALI_LOG_WARNING("VKB Unable to get IMF Context so GetSize unavailable\n");
+ }
+
+ return Rect<int>(xPos,yPos,width,height);
+}
+
+void ImfManagerX::ApplyOptions( const InputMethodOptions& options )
+{
+ using namespace Dali::InputMethod::Category;
+
+ int index;
+
+ if (mIMFContext == NULL)
+ {
+ DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n");
+ return;
+ }
+
+ if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) )
+ {
+ }
+ if ( mOptions.CompareAndSet(AUTO_CAPITALISE, options, index) )
+ {
+ }
+ if ( mOptions.CompareAndSet(ACTION_BUTTON_TITLE, options, index) )
+ {
+ }
+ if ( mOptions.CompareAndSet(VARIATION, options, index) )
+ {
+ }
+}
+
+void ImfManagerX::SetInputPanelData( const std::string& data )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetInputPanelData\n" );
+
+ if( mIMFContext )
+ {
+ int length = data.length();
+ ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length );
+ }
+}
+
+void ImfManagerX::GetInputPanelData( std::string& data )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelData\n" );
+
+ if( mIMFContext )
+ {
+ int length = 4096; // The max length is 4096 bytes
+ Dali::Vector< char > buffer;
+ buffer.Resize( length );
+ ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length );
+ data = std::string( buffer.Begin(), buffer.End() );
+ }
+}
+
+Dali::ImfManager::State ImfManagerX::GetInputPanelState()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelState\n" );
+
+ if( mIMFContext )
+ {
+ int value;
+ value = ecore_imf_context_input_panel_state_get( mIMFContext );
+
+ switch (value)
+ {
+ case ECORE_IMF_INPUT_PANEL_STATE_SHOW:
+ {
+ return Dali::ImfManager::SHOW;
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_HIDE:
+ {
+ return Dali::ImfManager::HIDE;
+ break;
+ }
+
+ case ECORE_IMF_INPUT_PANEL_STATE_WILL_SHOW:
+ {
+ return Dali::ImfManager::WILL_SHOW;
+ break;
+ }
+
+ default:
+ {
+ return Dali::ImfManager::DEFAULT;
+ }
+ }
+ }
+ return Dali::ImfManager::DEFAULT;
+}
+
+void ImfManagerX::SetReturnKeyState( bool visible )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetReturnKeyState\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible );
+ }
+}
+
+void ImfManagerX::AutoEnableInputPanel( bool enabled )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::AutoEnableInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled );
+ }
+}
+
+void ImfManagerX::ShowInputPanel()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ShowInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_show( mIMFContext );
+ }
+}
+
+void ImfManagerX::HideInputPanel()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::HideInputPanel\n" );
+
+ if( mIMFContext )
+ {
+ ecore_imf_context_input_panel_hide( mIMFContext );
+ }
+}
+
+Dali::ImfManager::KeyboardType ImfManagerX::GetKeyboardType()
+{
+ return Dali::ImfManager::KeyboardType::SOFTWARE_KEYBOARD;
+}
+
+std::string ImfManagerX::GetInputPanelLocale()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetInputPanelLocale\n" );
+
+ std::string locale = "";
+
+ if( mIMFContext )
+ {
+ char* value = NULL;
+ ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value );
+
+ if( value )
+ {
+ std::string valueCopy( value );
+ locale = valueCopy;
+
+ // The locale string retrieved must be freed with free().
+ free( value );
+ }
+ }
+ return locale;
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_X_H
+#define DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_X_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_IMF.h>
+#include <Ecore_X.h>
+
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/imf-manager.h>
+#include <dali/internal/input/common/imf-manager-impl.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class DALI_IMPORT_API ImfManagerX : public Dali::Internal::Adaptor::ImfManager
+{
+public:
+
+ /**
+ * Check whether the ImfManager is available.
+ * @return true if available, false otherwise
+ */
+ static bool IsAvailable();
+
+ /**
+ * Get the IMF manager instance, it creates the instance if it has not already been created.
+ * Internally, a check should be made using IsAvailable() before this is called as we do not want
+ * to create an instance if not needed by applications.
+ * @see IsAvailable()
+ */
+ static Dali::ImfManager Get();
+
+ /**
+ * Constructor
+ * @param[in] ecoreXwin, The window is created by application.
+ */
+ explicit ImfManagerX( Ecore_X_Window ecoreXwin );
+
+ /**
+ * Connect Callbacks required for IMF.
+ * If you don't connect imf callbacks, you can't get the key events.
+ * The events are PreeditChanged, Commit and DeleteSurrounding.
+ */
+ void ConnectCallbacks() override;
+
+ /**
+ * Disconnect Callbacks attached to imf context.
+ */
+ void DisconnectCallbacks() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Activate()
+ */
+ void Activate() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Deactivate()
+ */
+ void Deactivate() override;
+
+ /**
+ * @copydoc Dali::ImfManager::Reset()
+ */
+ void Reset() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetContext()
+ */
+ ImfContext* GetContext() override;
+
+ /**
+ * @copydoc Dali::ImfManager::RestoreAfterFocusLost()
+ */
+ bool RestoreAfterFocusLost() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetRestoreAfterFocusLost()
+ */
+ void SetRestoreAfterFocusLost( bool toggle ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::PreEditChanged()
+ */
+ void PreEditChanged( void* data, ImfContext* imfContext, void* event_info ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void CommitReceived( void* data, ImfContext* imfContext, void* event_info ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ bool RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteSurrounding()
+ */
+ void DeleteSurrounding( void* data, ImfContext* imfContext, void* event_info );
+
+
+ void SendPrivateCommand( void* data, ImfContext* imfContext, void* event_info ) override
+ {
+
+ }
+
+
+ // Cursor related
+ /**
+ * @copydoc Dali::ImfManager::NotifyCursorPosition()
+ */
+ void NotifyCursorPosition() override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetCursorPosition()
+ */
+ void SetCursorPosition( unsigned int cursorPosition ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetCursorPosition()
+ */
+ unsigned int GetCursorPosition() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetSurroundingText()
+ */
+ void SetSurroundingText( const std::string& text ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetSurroundingText()
+ */
+ const std::string& GetSurroundingText() const override;
+
+ /**
+ * @copydoc Dali::ImfManager::NotifyTextInputMultiLine()
+ */
+ void NotifyTextInputMultiLine( bool multiLine ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetTextDirection()
+ */
+ Dali::ImfManager::TextDirection GetTextDirection() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputMethodArea()
+ */
+ Dali::Rect<int> GetInputMethodArea() override;
+
+ /**
+ * @copydoc Dali::ImfManager::ApplyOptions()
+ */
+ void ApplyOptions( const InputMethodOptions& options ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetInputPanelData()
+ */
+ void SetInputPanelData( const std::string& data ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelData()
+ */
+ void GetInputPanelData( std::string& data ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelState()
+ */
+ Dali::ImfManager::State GetInputPanelState() override;
+
+ /**
+ * @copydoc Dali::ImfManager::SetReturnKeyState()
+ */
+ void SetReturnKeyState( bool visible ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::AutoEnableInputPanel()
+ */
+ void AutoEnableInputPanel( bool enabled ) override;
+
+ /**
+ * @copydoc Dali::ImfManager::ShowInputPanel()
+ */
+ void ShowInputPanel() override;
+
+ /**
+ * @copydoc Dali::ImfManager::HideInputPanel()
+ */
+ void HideInputPanel() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetKeyboardType()
+ */
+ Dali::ImfManager::KeyboardType GetKeyboardType() override;
+
+ /**
+ * @copydoc Dali::ImfManager::GetInputPanelLocale()
+ */
+ std::string GetInputPanelLocale() override;
+
+protected:
+
+ /**
+ * Destructor.
+ */
+ ~ImfManagerX() override;
+
+private:
+ /**
+ * Context created the first time and kept until deleted.
+ * @param[in] ecoreXwin, The window is created by application.
+ */
+ void CreateContext( Ecore_X_Window ecoreXwin );
+
+ /**
+ * @copydoc Dali::ImfManager::DeleteContext()
+ */
+ void DeleteContext();
+
+private:
+ // Undefined
+ ImfManagerX( const ImfManagerX& );
+ ImfManagerX& operator=( ImfManagerX& ) = delete;
+
+private:
+ Ecore_IMF_Context* mIMFContext;
+ int mIMFCursorPosition;
+ std::string mSurroundingText;
+
+ bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained.
+ bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected.
+ InputMethodOptions mOptions;
+};
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_INPUT_COMMON_IMF_MANAGER_IMPL_X_H
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/virtual-keyboard-impl.h>
+
+// EXTERNAL INCLUDES
+#include <X11/Xlib.h>
+#include <Ecore_X.h>
+#include <algorithm>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/adaptor.h>
+#include <dali/internal/system/common/locale-utils.h>
+#include <dali/internal/input/ubuntu-x11/imf-manager-impl-x.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace VirtualKeyboard
+{
+
+Dali::InputMethod::ActionButton gActionButtonFunction = Dali::InputMethod::ACTION_DEFAULT;
+
+Ecore_IMF_Input_Panel_Return_Key_Type actionButtonMapping(Dali::InputMethod::ActionButton actionButton )
+{
+ switch( actionButton )
+ {
+ case InputMethod::ACTION_DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE;
+ case InputMethod::ACTION_GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO;
+ case InputMethod::ACTION_JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN;
+ case InputMethod::ACTION_LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN;
+ case InputMethod::ACTION_NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT;
+ case InputMethod::ACTION_PREVIOUS: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH;
+ case InputMethod::ACTION_SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND;
+ case InputMethod::ACTION_SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_UNSPECIFIED: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ case InputMethod::ACTION_NONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT;
+ }
+}
+
+void RotateTo(int angle)
+{
+ // Get focus window used by Keyboard and rotate it
+ Display* display = XOpenDisplay(0);
+ if (display)
+ {
+ ::Window focusWindow;
+ int revert;
+ // Get Focus window
+ XGetInputFocus(display, &focusWindow, &revert);
+
+ ecore_x_window_prop_property_set( focusWindow,
+ ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE,
+ ECORE_X_ATOM_CARDINAL, 32, &angle, 1 );
+ XCloseDisplay(display);
+ }
+}
+
+void SetReturnKeyType( const InputMethod::ActionButton type )
+{
+ Dali::ImfManager imfManager = ImfManager::Get(); // Create ImfManager instance (if required) when setting values
+ Ecore_IMF_Context* imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+
+ if( imfContext )
+ {
+ gActionButtonFunction = type;
+ ecore_imf_context_input_panel_return_key_type_set( imfContext, actionButtonMapping( type ) );
+ }
+}
+
+Dali::InputMethod::ActionButton GetReturnKeyType()
+{
+ return gActionButtonFunction;
+}
+
+} // namespace VirtualKeyboard
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/input/common/key-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace KeyLookup
+{
+
+// matches a DALI_KEY enum, to a key name
+KeyLookup KeyLookupTable[]=
+{
+ // more than one key name can be assigned to a single dali-key code
+ // e.g. "Menu" and "XF86Menu" are both assigned to DALI_KEY_MENU
+
+ { "Escape", DALI_KEY_ESCAPE, false },
+ { "Menu", DALI_KEY_MENU, false },
+
+ // Now literal strings are used as key names instead of defined symbols in utilX,
+ // since these definition in utilX.h is deprecated
+ { "XF86Camera", DALI_KEY_CAMERA, false },
+ { "XF86Camera_Full", DALI_KEY_CONFIG, false },
+ { "XF86PowerOff", DALI_KEY_POWER, true },
+ { "XF86Standby", DALI_KEY_PAUSE, false },
+ { "Cancel", DALI_KEY_CANCEL, false },
+ { "XF86AudioPlay", DALI_KEY_PLAY_CD, false },
+ { "XF86AudioStop", DALI_KEY_STOP_CD, false },
+ { "XF86AudioPause", DALI_KEY_PAUSE_CD, false },
+ { "XF86AudioNext", DALI_KEY_NEXT_SONG, false },
+ { "XF86AudioPrev", DALI_KEY_PREVIOUS_SONG, false },
+ { "XF86AudioRewind", DALI_KEY_REWIND, false },
+ { "XF86AudioForward", DALI_KEY_FASTFORWARD, false },
+ { "XF86AudioMedia", DALI_KEY_MEDIA, false },
+ { "XF86AudioPlayPause", DALI_KEY_PLAY_PAUSE, false },
+ { "XF86AudioMute", DALI_KEY_MUTE, false },
+ { "XF86Menu", DALI_KEY_MENU, true },
+ { "XF86Home", DALI_KEY_HOME, true },
+ { "XF86Back", DALI_KEY_BACK, true },
+ { "XF86Send", DALI_KEY_MENU, true },
+ { "XF86Phone", DALI_KEY_HOME, true },
+ { "XF86Stop", DALI_KEY_BACK, true },
+ { "XF86HomePage", DALI_KEY_HOMEPAGE, false },
+ { "XF86WWW", DALI_KEY_WEBPAGE, false },
+ { "XF86Mail", DALI_KEY_MAIL, false },
+ { "XF86ScreenSaver", DALI_KEY_SCREENSAVER, false },
+ { "XF86MonBrightnessUp", DALI_KEY_BRIGHTNESS_UP, false },
+ { "XF86MonBrightnessDown", DALI_KEY_BRIGHTNESS_DOWN, false },
+ { "XF86SoftKBD", DALI_KEY_SOFT_KBD, false },
+ { "XF86QuickPanel", DALI_KEY_QUICK_PANEL, false },
+ { "XF86TaskPane", DALI_KEY_TASK_SWITCH, false },
+ { "XF86Apps", DALI_KEY_APPS, false },
+ { "XF86Search", DALI_KEY_SEARCH, false },
+ { "XF86Voice", DALI_KEY_VOICE, false },
+ { "Hangul", DALI_KEY_LANGUAGE, false },
+ { "XF86AudioRaiseVolume", DALI_KEY_VOLUME_UP, true },
+ { "XF86AudioLowerVolume", DALI_KEY_VOLUME_DOWN, true },
+
+ { "BackSpace", DALI_KEY_BACKSPACE, false },
+ { "Left", DALI_KEY_CURSOR_LEFT, false },
+ { "Right", DALI_KEY_CURSOR_RIGHT, false },
+ { "Shift_L", DALI_KEY_SHIFT_LEFT, false },
+ { "Shift_R", DALI_KEY_SHIFT_RIGHT, false },
+ { "Delete", static_cast<Dali::KEY>( DevelKey::DALI_KEY_DELETE ), false },
+ { "Control_L", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_LEFT ), false },
+ { "Control_R", static_cast<Dali::KEY>( DevelKey::DALI_KEY_CONTROL_RIGHT ), false },
+ { "Return", static_cast<Dali::KEY>( DevelKey::DALI_KEY_RETURN ), false }
+};
+
+const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup ));
+
+} // namespace KeyLookup
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/legacy/common/tizen-platform-abstraction.h>
+
+// EXTERNAL INCLUDES
+#include <dirent.h>
+#include <fstream>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/bitmap.h>
+#include <dali/integration-api/resource-types.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/image-loader.h>
+#include <dali/internal/system/common/file-reader.h>
+#include <dali/internal/imaging/common/pixel-buffer-impl.h>
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+TizenPlatformAbstraction::TizenPlatformAbstraction()
+: mDataStoragePath( "" )
+{
+}
+
+TizenPlatformAbstraction::~TizenPlatformAbstraction()
+{
+}
+
+ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( const std::string& filename,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection )
+{
+ return ImageLoader::GetClosestImageSize( filename, size, fittingMode, samplingMode, orientationCorrection );
+}
+
+ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection )
+{
+ return ImageLoader::GetClosestImageSize( resourceBuffer, size, fittingMode, samplingMode, orientationCorrection );
+}
+
+Integration::ResourcePointer TizenPlatformAbstraction::LoadImageSynchronously(const Integration::BitmapResourceType& resource, const std::string& resourcePath)
+{
+ return ImageLoader::LoadImageSynchronously( resource, resourcePath );
+}
+
+Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer( const Integration::BitmapResourceType& resource, uint8_t * buffer, size_t size )
+{
+ Integration::BitmapPtr resultBitmap;
+ Dali::Devel::PixelBuffer bitmap;
+
+ Dali::Internal::Platform::FileReader fileReader( buffer, size );
+ FILE * const fp = fileReader.GetFile();
+ if( fp )
+ {
+ bool result = ImageLoader::ConvertStreamToBitmap( resource, "", fp, bitmap );
+ if ( !result || !bitmap )
+ {
+ bitmap.Reset();
+ DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" );
+ }
+ else
+ {
+ Integration::Bitmap::Profile profile{Integration::Bitmap::Profile::BITMAP_2D_PACKED_PIXELS};
+
+ // For backward compatibility the Bitmap must be created
+ auto retval = Integration::Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD);
+
+ retval->GetPackedPixelsProfile()->ReserveBuffer(
+ bitmap.GetPixelFormat(),
+ bitmap.GetWidth(),
+ bitmap.GetHeight(),
+ bitmap.GetWidth(),
+ bitmap.GetHeight()
+ );
+
+ auto& impl = Dali::GetImplementation(bitmap);
+
+ std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer());
+ resultBitmap.Reset(retval);
+ }
+ }
+
+ return resultBitmap;
+}
+
+bool TizenPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
+{
+ bool result = false;
+
+#ifdef SHADERBIN_CACHE_ENABLED
+ std::string path;
+
+ // First check the system location where shaders are stored at install time:
+ path = DALI_SHADERBIN_DIR;
+ path += filename;
+ result = LoadFile( path, buffer );
+
+ // Fallback to the cache of shaders stored after previous runtime compilations:
+ // On desktop this looks in the current working directory that the app was launched from.
+ if( mResourceLoader && result == false )
+ {
+ path = mDataStoragePath;
+ path += filename;
+ result = LoadFile( path, buffer );
+ }
+#endif
+
+ return result;
+}
+
+bool TizenPlatformAbstraction::SaveShaderBinaryFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const
+{
+ bool result = false;
+
+#ifdef SHADERBIN_CACHE_ENABLED
+
+ // Use the cache of shaders stored after previous runtime compilations:
+ // On desktop this looks in the current working directory that the app was launched from.
+ std::string path = mDataStoragePath;
+ path += filename;
+ result = SaveFile( path, buffer, numBytes );
+
+#endif
+
+ return result;
+}
+
+void TizenPlatformAbstraction::SetDataStoragePath( const std::string& path )
+{
+ mDataStoragePath = path;
+}
+
+TizenPlatformAbstraction* CreatePlatformAbstraction()
+{
+ return new TizenPlatformAbstraction();
+}
+
+bool SaveFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes )
+{
+ DALI_ASSERT_DEBUG( 0 != filename.length());
+
+ bool result = false;
+
+ std::filebuf buf;
+ buf.open(filename.c_str(), std::ios::out | std::ios_base::trunc | std::ios::binary);
+ if( buf.is_open() )
+ {
+ std::ostream stream(&buf);
+
+ // determine size of buffer
+ int length = static_cast<int>(numBytes);
+
+ // write contents of buffer to the file
+ stream.write(reinterpret_cast<const char*>(buffer), length);
+
+ if( !stream.bad() )
+ {
+ result = true;
+ }
+ }
+
+ return result;
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+
+
+# module: legacy, backend: common
+adaptor_legacy_common_src_files=\
+ ${adaptor_legacy_dir}/common/tizen-platform-abstraction.cpp
\ No newline at end of file
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_AUTOMATION_H__
+#define __DALI_INTERNAL_ADAPTOR_AUTOMATION_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+// EXTERNAL INCLUDES
+#include <string>
+
+// INTERNAL INCLUDES
+#include <dali/internal/network/common/client-send-data-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * @brief The automation functions allow a way to control Dali via a network socket.
+ *
+ * The functions must be called from the event thread only.
+ *
+ * Any functions which require a response to be sent back to the network client
+ * use the ClientSendDataInterface interface.
+
+ * E.g.
+ * Dali network client thread <---- "dump_scene" from network
+ * Dali main thread "json data" -----> network
+ *
+ */
+namespace Automation
+{
+
+/**
+ * @brief Sets properties on an Actor.
+ * No ClientSendDataInterface required, as no response is sent back
+ * @param[in] message set property message
+ */
+void SetProperty( const std::string& message );
+
+
+/**
+ * @brief Dumps the actor tree to the client
+ * @param[in] clientId unique network client id
+ * @param[in] sendData interface to transmit data to the client
+ */
+void DumpScene( unsigned int clientId, ClientSendDataInterface* sendData );
+
+
+} // namespace Automation
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H__
+#define __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <pthread.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-marker.h>
+#include <dali/integration-api/trigger-event-factory-interface.h>
+#include <dali/internal/network/common/client-send-data-interface.h>
+#include <dali/internal/network/common/socket-factory-interface.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * @brief Network Performance client
+ *
+ * Every time a client connects to Dali, a NetworkPerformanceClient object is created.
+ * It is responsible for processing incoming commands, and storing the client state
+ * (e.g. what performance markers it wants).
+ *
+ * Certain commands such as dump-scene need to be run on the main Dali event thread.
+ * To achieve this, a trigger event is used which executes a function on the main thread.
+ * The sendDataInterface is then used with the client id to transmit the data to the client.
+ * The reason for using a client id is because the client
+ * can be deleted in between receiving a command and sending a response.
+ * E.g.
+ * NetworkPerformanceClient (own thread, id 5) <--- Dump Scene Command
+ * delete NetworkPerformanceClient <--- Connection closed
+ * MainThread. Send scene data to client 5. Client 5 has been deleted so don't send the data.
+ *
+ */
+class NetworkPerformanceClient
+{
+public:
+
+ /**
+ * @brief Constructor
+ * @param thread thread pointer
+ * @param socket socket interface
+ * @param clientId unique client id
+ * @param triggerEventFactory used to create trigger events
+ * @param sendDataInterface used to send data to the socket from main thread
+ * @param SocketFactoryInterface used to delete the socket when the client is destroyed
+ */
+ NetworkPerformanceClient( pthread_t* thread,
+ SocketInterface *socket,
+ unsigned int clientId,
+ TriggerEventFactoryInterface& triggerEventFactory,
+ ClientSendDataInterface& sendDataInterface,
+ SocketFactoryInterface& socketFactory );
+
+ /**
+ * @brief Destructor
+ */
+ ~NetworkPerformanceClient();
+
+ /**
+ * @return client unique id
+ */
+ unsigned int GetId() const;
+
+ /**
+ * @return socket interface
+ */
+ SocketInterface& GetSocket();
+
+ /**
+ * @brief Write data to a socket. Can be called from any thread
+ * @copydoc Dali::SocketInterface::Send
+ */
+ bool WriteSocket( const void* buffer, unsigned int bufferSizeInBytes );
+
+ /**
+ * @brief Process a command
+ * @param buffer pointer to command data
+ * @param bufferSizeInBytes how big the buffer is in bytes
+ */
+ void ProcessCommand( char* buffer, unsigned int bufferSizeInBytes );
+
+ /**
+ * @brief Write a marker to the socket, if this client is filtering this marker.
+ * @param marker
+ */
+ bool TransmitMarker( const PerformanceMarker& marker, const char* const description );
+
+ /**
+ * @brief If the client is waiting inside a select statement, this will cause it
+ * to break out.
+ */
+ void ExitSelect();
+
+ /**
+ * @brief get the thread running the client
+ * @return thread pointer
+ */
+ pthread_t* GetThread();
+
+private:
+
+ pthread_t* mThread; ///< thread for the client
+ SocketInterface* mSocket; ///< socket interface
+ PerformanceMarker::MarkerFilter mMarkerBitmask; ///< What markers are currently filtered
+ TriggerEventFactoryInterface& mTriggerEventFactory; ///< Trigger event factory
+ ClientSendDataInterface& mSendDataInterface; ///< used to send data to a client from the main event thread
+ SocketFactoryInterface& mSocketFactoryInterface; ///< used to delete the socket
+ unsigned int mClientId; ///< unique client id
+ bool mConsoleClient; ///< if connected via a console then all responses are in ASCII, not binary packed data.
+
+};
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
+#define __DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <pthread.h>
+#include <dali/devel-api/threading/mutex.h>
+#include <dali/public-api/common/dali-vector.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+#include <dali/internal/network/common/network-performance-client.h>
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class SocketInterface;
+class PerformanceMarker;
+
+/**
+ * @brief The class listens for incoming connections on a dedicated thread.
+ *
+ * When a new connection is established a client thread is spawned to
+ * handle that connection, along with a NetworkPerformanceClient object.
+ * The NetworkPerformanceClient object performs processing of incoming
+ * commands and holds the per-client state information for performance monitoring.
+ *
+ * Server->Start()
+ * - Open socket
+ * - Spawns a thread to listen for incoming connections
+ * <---- New connection
+ * - Spawns a client thread to communicate with new client
+ *
+ * Server->Stop()
+ * - Stops listening thread
+ * - Stops all client threads
+ */
+class NetworkPerformanceServer : public ClientSendDataInterface
+{
+
+public:
+
+ /**
+ * @brief Constructor
+ * @param[in] adaptorServices adaptor internal services
+ * @param[in] logOptions log options
+ */
+ NetworkPerformanceServer( AdaptorInternalServices& adaptorServices, const EnvironmentOptions& logOptions );
+
+
+ /**
+ * @brief Start the server, to be called form Dali main thread
+ * @pre Can only be called form Dali main thread
+ */
+ void Start();
+
+ /**
+ * @brief Stop the server
+ * @pre Can only be called form Dali main thread
+ */
+ void Stop();
+
+ /**
+ * @return true if the server is running
+ */
+ bool IsRunning() const;
+
+ /**
+ * @brief Transmit a marker to any clients are listening for this marker.
+ * @param[in] marker performance marker
+ * @param[in] description marker description
+ * @pre Can be called from any thread
+ *
+ */
+ void TransmitMarker( const PerformanceMarker& marker, const char* const description );
+
+ /**
+ * Destructor
+ */
+ ~NetworkPerformanceServer();
+
+protected: // ClientSendDataInterface
+
+ /**
+ * @copydoc ClientSendDataInterface::ClientSendDataInterface()
+ */
+ virtual void SendData( const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId );
+
+private:
+
+ /**
+ * Helper for the thread calling the entry function.
+ * @param[in] This A pointer to the current RenderThread object
+ */
+ static void* ConnectionListenerFunc( void* This )
+ {
+ ( static_cast<NetworkPerformanceServer*>( This ) )->ConnectionListener();
+ return NULL;
+ }
+
+ /**
+ * Helper for the thread calling the entry function.
+ * @param[in] This A pointer to the current RenderThread object
+ */
+ static void* ClientThreadFunc( void* data );
+
+ /**
+ * @brief Client thread function
+ * @param client network client object
+ */
+ void ClientThread( NetworkPerformanceClient* client );
+
+ /**
+ * @brief Stop all client threads
+ */
+ void StopClients();
+
+ /**
+ * @brief Waits for new connections to be made
+ */
+ void ConnectionListener();
+
+ /**
+ * @brief Add a new client to the client list
+ * @param clientSocket client socket
+ * @param clientThread client thread
+ * @return client
+ */
+ NetworkPerformanceClient* AddClient( SocketInterface* clientSocket, pthread_t* clientThread );
+
+ /**
+ * @brief Delete a client from the client list
+ * @param client network client
+ */
+ void DeleteClient( NetworkPerformanceClient* client );
+
+ NetworkPerformanceServer( const NetworkPerformanceServer& ); ///< undefined copy constructor
+ NetworkPerformanceServer& operator=( const NetworkPerformanceServer& ); ///< undefined assignment operator
+
+
+ TriggerEventFactoryInterface& mTriggerEventFactory; ///< used to create trigger events
+ SocketFactoryInterface& mSocketFactory; ///< used to create sockets
+ const EnvironmentOptions& mLogOptions; ///< log options
+ Dali::Vector< NetworkPerformanceClient* > mClients; ///< list of connected clients
+ pthread_t mServerThread; ///< thread that listens for new connections
+ SocketInterface* mListeningSocket; ///< socket used to listen for new connections
+ Dali::Mutex mClientListMutex; ///< mutex
+ unsigned int mClientUniqueId; ///< increments for every client connection
+ volatile unsigned int mClientCount; ///< client count
+ bool mLogFunctionInstalled; ///< whether the log function is installed
+
+};
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif //__DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
+#define __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/network/common/socket-interface.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * @brief abstract class to create and destroy sockets
+ */
+class SocketFactoryInterface
+{
+public:
+
+ /**
+ * @brief Create a new socket
+ * @param protocol network protocol
+ * @return true on success, false on failure
+ */
+ virtual SocketInterface* NewSocket( SocketInterface::Protocol protocol ) = 0;
+
+ /**
+ * @brief destroy a socket
+ * @param[in] socket socket to destroy
+ */
+ virtual void DestroySocket( SocketInterface* socket ) = 0;
+
+protected:
+
+ /**
+ * @brief Constructor
+ */
+ SocketFactoryInterface( )
+ {
+ }
+
+ /**
+ * @brief Virtual destructor
+ */
+ virtual ~SocketFactoryInterface()
+ {
+ }
+
+private:
+
+ // Undefined copy constructor.
+ SocketFactoryInterface( const SocketFactoryInterface& );
+
+ // Undefined assignment operator.
+ SocketFactoryInterface& operator=( const SocketFactoryInterface& );
+
+};
+
+
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+// CLASS HEADER
+#include <dali/internal/network/common/socket-factory.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/network/common/socket-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+SocketInterface* SocketFactory::NewSocket( SocketInterface::Protocol protocol )
+{
+ return new Socket( protocol );
+}
+
+void SocketFactory::DestroySocket( SocketInterface* socketInterface )
+{
+ Socket* socket( static_cast<Socket* >( socketInterface ));
+ delete socket;
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
+#define __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/network/common/socket-factory-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * @brief concrete implementation of the socket factory interface
+ */
+class SocketFactory : public SocketFactoryInterface
+{
+public:
+
+
+ /**
+ * @brief Constructor
+ */
+ SocketFactory( )
+ {
+ }
+
+ /**
+ * @brief destructor
+ */
+ virtual ~SocketFactory()
+ {
+ }
+
+ /**
+ * @copydoc SocketFactoryInterface::NewSocket()
+ */
+ virtual SocketInterface* NewSocket( SocketInterface::Protocol protocol );
+
+ /**
+ * @copydoc SocketFactoryInterface::DestroySocket()
+ */
+ virtual void DestroySocket( SocketInterface* socket );
+
+};
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/network/common/socket-impl.h>
+
+// EXTERNAL INCLUDES
+#include <string.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <errno.h>
+#include <unistd.h>
+#include <dali/integration-api/debug.h>
+
+// Sockets enums like INADDR_ANY use C-Casts
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+namespace
+{
+const unsigned int MAX_SOCKET_DATA_WRITE_SIZE = 1024 * 1024 * 10 ; // limit maximum size to write to 10 MB
+}
+
+Socket::Socket( Protocol protocol , int fileDescriptor )
+:mSocketFileDescriptor( fileDescriptor ),
+ mBound(false),
+ mListening(false),
+ mQuitPipeCreated(false),
+ mBlocked(false)
+{
+ int addressFamily( AF_INET );
+ int netProtocol( IPPROTO_TCP );
+ int type( SOCK_STREAM ); // for TCP
+
+ if( protocol == UDP )
+ {
+ type = SOCK_DGRAM;
+ netProtocol = IPPROTO_UDP;
+ }
+ if( mSocketFileDescriptor == -1)
+ {
+ mSocketFileDescriptor = socket( addressFamily,type, netProtocol);
+ if( mSocketFileDescriptor == -1 )
+ {
+ DALI_LOG_ERROR( "Unable to create socket\n" );
+ }
+ }
+ else
+ {
+ // socket already open
+ mBound = true;
+ }
+}
+
+Socket::~Socket()
+{
+ if( SocketIsOpen() )
+ {
+ CloseSocket();
+ }
+}
+
+bool Socket::SocketIsOpen() const
+{
+ return (mSocketFileDescriptor != -1);
+}
+
+bool Socket::CloseSocket()
+{
+
+ if( ! SocketIsOpen() )
+ {
+ DALI_LOG_ERROR("Socket already closed or is invalid \n");
+ return false;
+ }
+
+ int ret = close( mSocketFileDescriptor );
+ mSocketFileDescriptor = -1;
+ mListening = false;
+ mBound = false;
+
+ if( ret == -1 )
+ {
+ DALI_LOG_ERROR("Socket close failed\n");
+ return false;
+ }
+ return true;
+}
+
+bool Socket::Bind( uint16_t port )
+{
+ if( ! SocketIsOpen() || mBound )
+ {
+ DALI_LOG_ERROR("Socket is invalid, or already bound\n");
+ return false;
+ }
+ struct sockaddr_in serverAddress;
+
+ memset( &serverAddress, 0, sizeof(serverAddress) );
+ serverAddress.sin_family = AF_INET; // internet
+ serverAddress.sin_port = htons( port ); // host-to-net short (16-bit) translation
+ serverAddress.sin_addr.s_addr = htonl( INADDR_ANY ); // binds the socket to all available interfaces
+
+ int ret = bind( mSocketFileDescriptor,
+ reinterpret_cast< struct sockaddr* >( &serverAddress ),
+ sizeof(serverAddress));
+
+ if( ret == -1 )
+ {
+ char buf[512];
+ DALI_LOG_ERROR( "bind failed for port %d %s \n", port, strerror_r( errno, buf, 512 ) );
+ return false;
+ }
+
+ mBound = true;
+
+ return true;
+}
+
+bool Socket::Listen( int blacklog)
+{
+ if( ! mBound || mListening )
+ {
+ DALI_LOG_ERROR("socket is not bound, or already opened for listening\n");
+ return false;
+ }
+ int ret = listen( mSocketFileDescriptor, blacklog);
+
+ if( ret == -1 )
+ {
+ DALI_LOG_ERROR("Listen failed\n");
+ return false;
+ }
+
+ mListening = true;
+
+ return true;
+}
+
+SocketInterface* Socket::Accept() const
+{
+ if( !mListening )
+ {
+ DALI_LOG_ERROR("socket is not being listened to\n");
+ return NULL;
+ }
+
+ struct sockaddr clientAddress;
+
+ socklen_t addressLength(sizeof(sockaddr_in));
+
+ int clientFileDescriptor = accept( mSocketFileDescriptor, &clientAddress, &addressLength);
+ if( clientFileDescriptor == -1 )
+ {
+ DALI_LOG_ERROR("Accept failed\n");
+ return NULL;
+ }
+
+ // create a new socket, only TCP supports connections
+ Socket* client = new Socket( TCP, clientFileDescriptor );
+
+ return client;
+}
+
+bool Socket::CreateQuitPipe()
+{
+ if( !mQuitPipeCreated )
+ {
+ // create a pipe file descriptor to be able to break from the Select statement
+ //
+ int ret = pipe( mQuitPipe );
+ if( ret != 0)
+ {
+ DALI_LOG_ERROR("Pipe creation failed\n");
+ return false;
+ }
+ mQuitPipeCreated = true;
+ }
+ return true;
+}
+void Socket::DeleteQuitPipe()
+{
+ if( mQuitPipeCreated )
+ {
+ close( mQuitPipe[0] );
+ close( mQuitPipe[1] );
+ }
+}
+
+SocketInterface::SelectReturn Socket::Select()
+{
+ bool ok = CreateQuitPipe();
+ if( !ok )
+ {
+ return ERROR;
+ }
+
+ fd_set readFileDescriptors, exceptFileDescriptors;
+ FD_ZERO(&readFileDescriptors);
+ FD_ZERO(&exceptFileDescriptors);
+
+ FD_SET(mSocketFileDescriptor,&readFileDescriptors );
+ FD_SET(mQuitPipe[0],&readFileDescriptors );
+
+ FD_SET(mSocketFileDescriptor,&exceptFileDescriptors);
+
+ unsigned int maxFd = mQuitPipe[0] > mSocketFileDescriptor ? mQuitPipe[0]: mSocketFileDescriptor;
+
+ for( ;; )
+ {
+ // this will block waiting for file descriptors
+ int ret = select( maxFd+1, &readFileDescriptors, NULL, &exceptFileDescriptors, NULL );
+ if( ret == -1 )
+ {
+ DALI_LOG_ERROR("select failed\n");
+ return ERROR;
+ }
+ else if ( FD_ISSET( mQuitPipe[0] , &readFileDescriptors ))
+ {
+ // ExitSelect() called
+ return QUIT;
+ }
+ else if ( FD_ISSET( mSocketFileDescriptor, &readFileDescriptors ))
+ {
+ // socket data received
+ return DATA_AVAILABLE;
+ }
+ }
+ return QUIT;
+}
+
+void Socket::ExitSelect()
+{
+ if( mQuitPipeCreated )
+ {
+ // write a single character to the pipe (can be anything)
+ char c = ' ';
+ int ret = write( mQuitPipe[1], &c, 1);
+ if( ret < 1 )
+ {
+ DALI_LOG_ERROR("ExitSelect failed!\n");
+ }
+ return;
+ }
+}
+
+bool Socket::ReuseAddress( bool reUse )
+{
+ if( ! SocketIsOpen() | mBound )
+ {
+ DALI_LOG_ERROR("Socket is invalid or already bound \n");
+ return false;
+ }
+
+ int reUseInteger = reUse; // convert it to an int
+
+ int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &reUseInteger, sizeof(reUseInteger));
+ if( ret == -1 )
+ {
+ char buf[512];
+ DALI_LOG_ERROR( "SO_REUSEADDR option failed %s \n", strerror_r( errno, buf, 512 ) );
+ return false;
+ }
+ return true;
+}
+
+bool Socket::SetBufferSize( SocketInterface::BufferType type, unsigned int size )
+{
+ if( ! SocketIsOpen() || mBound )
+ {
+ DALI_LOG_ERROR("Socket is invalid or already bound \n");
+ return false;
+ }
+ int option = SO_RCVBUF;
+ if( type == SocketInterface::SEND_BUFFER )
+ {
+ option = SO_SNDBUF;
+ }
+
+ int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET,option,&size,sizeof(size));
+ if( ret == -1 )
+ {
+ DALI_LOG_ERROR("SO_RCVBUF / SO_SNDBUF option failed \n");
+ return false;
+ }
+ return true;
+}
+
+bool Socket::Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead )
+{
+ bytesRead = 0;
+
+ if( !SocketIsOpen() )
+ {
+ DALI_LOG_ERROR("Socket is invalid \n");
+ return false;
+ }
+
+ bytesRead = read( mSocketFileDescriptor, buffer, bufferSizeInBytes );
+
+ return true;
+}
+
+bool Socket::Write( const void* buffer, unsigned int bufferSizeInBytes )
+{
+ if( !SocketIsOpen() )
+ {
+ DALI_LOG_ERROR("Socket is invalid \n");
+ return false;
+ }
+
+ // check we don't try to write more than 10MB ( this can be increased if required)
+ if( bufferSizeInBytes > MAX_SOCKET_DATA_WRITE_SIZE )
+ {
+ DALI_LOG_ERROR("Writing %d bytes exceeds MAX_SOCKET_DATA_WRITE_SIZE of %d bytes \n", bufferSizeInBytes, MAX_SOCKET_DATA_WRITE_SIZE);
+ return false;
+ }
+
+ int bytesWritten = 0;
+
+ // write isn't guaranteed to write the entire buffer in one go
+
+ while( bytesWritten != static_cast< int>(bufferSizeInBytes))
+ {
+ const char* byteBuffer = static_cast<const char *>( buffer );
+ byteBuffer+=bytesWritten;
+
+ int ret = write( mSocketFileDescriptor, byteBuffer, bufferSizeInBytes - bytesWritten );
+ if( ret < 1)
+ {
+ DALI_LOG_ERROR("Socket writer error \n");
+ return false;
+ }
+ else
+ {
+ bytesWritten += ret;
+ }
+ }
+ return true;
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
+#define __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/network/common/socket-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * @brief Concrete implementation of a socket under Linux.
+ *
+ * Provides automatic closing of socket on destruction.
+ */
+class Socket : public SocketInterface
+{
+public:
+
+ /**
+ * @brief Constructor
+ * @param protocol network protocol
+ * @param fileDescriptor option file descriptor if the socket is already open
+ */
+ Socket( Protocol protocol , int fileDescriptor = -1 );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketIsOpen()
+ */
+ virtual bool SocketIsOpen() const;
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::CloseSocket
+ */
+ virtual bool CloseSocket();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Bind
+ */
+ virtual bool Bind( uint16_t port ) ;
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Listen
+ */
+ virtual bool Listen( int blacklog);
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Accept
+ */
+ virtual SocketInterface* Accept() const ;
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Select
+ */
+ virtual SelectReturn Select( );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::ExitSelect
+ */
+ virtual void ExitSelect();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Recieve
+ */
+ virtual bool Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::Send
+ */
+ virtual bool Write( const void* buffer, unsigned int bufferLength );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::ReuseAddress
+ */
+ virtual bool ReuseAddress( bool reUse );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::SocketInterface::SetBufferSize
+ *
+ */
+ virtual bool SetBufferSize( SocketInterface::BufferType type, unsigned int bufferSizeInBytes );
+
+ /**
+ * @brief Virtual destructor
+ */
+ virtual ~Socket();
+
+private:
+
+
+ /**
+ * @brief Helper to create the quit pipe
+ */
+ bool CreateQuitPipe();
+
+ /**
+ * @brief Helper to delete the quit pipe
+ */
+ void DeleteQuitPipe();
+
+ int mSocketFileDescriptor; ///< file descriptor
+ int mQuitPipe[2]; ///< Pipe to inform Select to quit.
+ bool mBound:1; ///< whether the socket is bound
+ bool mListening:1; ///< whether the socket is being listen to
+ bool mQuitPipeCreated:1; ///< whether the quit pipe has been created
+ bool mBlocked:1; ///< whether the socket is blocked waiting for a connection
+};
+
+
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_BASE_TRACE_INTERFACE_H__
+#define __DALI_INTERNAL_BASE_TRACE_INTERFACE_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-marker.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Abstract Tracing Interface.
+ * Used to log trace messages.
+ * E.g. On Linux this may use ftrace
+ *
+ */
+class TraceInterface
+{
+
+public:
+
+ /**
+ * Write a trace message
+ * @param marker performance marker
+ * @param traceMessage trace message
+ */
+ virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage ) = 0;
+
+protected:
+
+ /**
+ * Constructor
+ */
+ TraceInterface()
+ {
+ }
+
+ /**
+ * virtual destructor
+ */
+ virtual ~TraceInterface()
+ {
+ }
+
+ // Undefined copy constructor.
+ TraceInterface( const TraceInterface& );
+
+ // Undefined assignment operator.
+ TraceInterface& operator=( const TraceInterface& );
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif
--- /dev/null
+
+
+# module: network, backend: common
+adaptor_network_common_src_files=\
+ ${adaptor_network_dir}/common/socket-factory.cpp \
+ ${adaptor_network_dir}/common/socket-impl.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/sensor/common/tilt-sensor-factory.h>
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+namespace TiltSensorFactory
+{
+__attribute__((weak)) Dali::Internal::Adaptor::TiltSensor* Create()
+{
+ // default implementation returns 'dummy' sensor
+ return new Internal::Adaptor::TiltSensor();
+}
+
+Dali::TiltSensor Get()
+{
+ Dali::TiltSensor sensor;
+
+ Dali::SingletonService service(SingletonService::Get());
+
+ if (service)
+ {
+ // Check whether the keyboard focus manager is already created
+ Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::TiltSensor));
+ if (handle)
+ {
+ // If so, downcast the handle of singleton to keyboard focus manager
+ sensor = Dali::TiltSensor(dynamic_cast< TiltSensor * >( handle.GetObjectPtr()));
+ }
+ else
+ {
+ // Create a singleton instance
+ sensor = Dali::TiltSensor(TiltSensorFactory::Create());
+ service.Register(typeid(sensor), sensor);
+ handle = sensor;
+ }
+ }
+ return sensor;
+}
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
\ No newline at end of file
--- /dev/null
+#ifndef DALI_SENSOR_COMMON_TILT_SENSOR_FACTORY_H
+#define DALI_SENSOR_COMMON_TILT_SENSOR_FACTORY_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/devel-api/adaptor-framework/tilt-sensor.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class TiltSensor;
+
+namespace TiltSensorFactory
+{
+
+/**
+ * Creates new instance of tilt sensor implementation
+ * @return pointer to tilt sensor implementation instance
+ */
+__attribute__((weak)) Dali::Internal::Adaptor::TiltSensor* Create();
+
+/**
+ * Obtains existing or creates new instance of the tilt sensor
+ * @return Tilt sensor handle
+ */
+Dali::TiltSensor Get();
+
+} // TiltSensorFactory
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_SENSOR_COMMON_TILT_SENSOR_FACTORY_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+TiltSensor::TiltSensor() = default;
+
+TiltSensor::~TiltSensor() = default;
+
+bool TiltSensor::Start()
+{
+ return false;
+}
+
+void TiltSensor::Stop()
+{
+
+}
+
+bool TiltSensor::IsStarted() const
+{
+ return false;
+}
+
+float TiltSensor::GetRoll() const
+{
+ return 0.0f;
+}
+
+float TiltSensor::GetPitch() const
+{
+ return 0.0f;
+}
+
+Quaternion TiltSensor::GetRotation() const
+{
+ return Quaternion::IDENTITY;
+}
+
+
+TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal()
+{
+ static TiltSensor::TiltedSignalType signal;
+ return signal;
+}
+
+
+void TiltSensor::SetUpdateFrequency(float frequencyHertz)
+{
+
+}
+
+float TiltSensor::GetUpdateFrequency() const
+{
+ return 0.0f;
+}
+
+void TiltSensor::SetRotationThreshold(Radian rotationThreshold)
+{
+
+}
+
+/**
+ * @copydoc Dali::TiltSensor::GetRotationThreshold()
+ */
+Radian TiltSensor::GetRotationThreshold() const
+{
+ return Radian();
+}
+
+/**
+ * Connects a callback function with the object's signals.
+ * @param[in] object The object providing the signal.
+ * @param[in] tracker Used to disconnect the signal.
+ * @param[in] signalName The signal to connect to.
+ * @param[in] functor A newly allocated FunctorDelegate.
+ * @return True if the signal was connected.
+ * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
+ */
+bool TiltSensor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
\ No newline at end of file
--- /dev/null
+#ifndef DALI_SENSOR_COMMON_TILT_SENSOR_IMPL_H
+#define DALI_SENSOR_COMMON_TILT_SENSOR_IMPL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/timer.h>
+#include <dali/devel-api/adaptor-framework/tilt-sensor.h>
+#include <deque>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * TiltSensor provides pitch & roll values when the device is tilted.
+ */
+class TiltSensor : public Dali::BaseObject
+{
+public:
+
+ /**
+ * Constructor
+ */
+ TiltSensor();
+
+ /**
+ * Destructor
+ */
+ ~TiltSensor() override;
+
+ typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType;
+
+ /**
+ * @copydoc Dali::TiltSensor::Start()
+ */
+ virtual bool Start();
+
+ /**
+ * @copydoc Dali::TiltSensor::Stop()
+ */
+ virtual void Stop();
+
+ /**
+ * @copydoc Dali::TiltSensor::IsStarted()
+ */
+ virtual bool IsStarted() const;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRoll()
+ */
+ virtual float GetRoll() const;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetPitch()
+ */
+ virtual float GetPitch() const;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotation()
+ */
+ virtual Quaternion GetRotation() const;
+
+ /**
+ * @copydoc Dali::TiltSensor::TiltedSignal()
+ */
+ virtual TiltedSignalType& TiltedSignal();
+
+ /**
+ * @copydoc Dali::TiltSensor::SetUpdateFrequency()
+ */
+ virtual void SetUpdateFrequency( float frequencyHertz );
+
+ /**
+ * @copydoc Dali::TiltSensor::GetUpdateFrequency()
+ */
+ virtual float GetUpdateFrequency() const;
+
+ /**
+ * @copydoc Dali::TiltSensor::SetRotationThreshold()
+ */
+ virtual void SetRotationThreshold(Radian rotationThreshold);
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotationThreshold()
+ */
+ virtual Radian GetRotationThreshold() const;
+
+ /**
+ * Connects a callback function with the object's signals.
+ * @param[in] object The object providing the signal.
+ * @param[in] tracker Used to disconnect the signal.
+ * @param[in] signalName The signal to connect to.
+ * @param[in] functor A newly allocated FunctorDelegate.
+ * @return True if the signal was connected.
+ * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
+ */
+ static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+inline Internal::Adaptor::TiltSensor& GetImplementation(Dali::TiltSensor& sensor)
+{
+ DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
+
+ BaseObject& handle = sensor.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::TiltSensor&>(handle);
+}
+
+inline const Internal::Adaptor::TiltSensor& GetImplementation(const Dali::TiltSensor& sensor)
+{
+ DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" );
+
+ const BaseObject& handle = sensor.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::TiltSensor&>(handle);
+}
+
+} // namespace Dali
+
+#endif // DALI_SENSOR_COMMON_TILT_SENSOR_IMPL_H
--- /dev/null
+
+
+# module: sensor, backend: common
+adaptor_sensor_common_src_files=\
+ ${adaptor_sensor_dir}/common/tilt-sensor-factory.cpp \
+ ${adaptor_sensor_dir}/common/tilt-sensor-impl.cpp
+
+# module: sensor, backend: tizen
+adaptor_sensor_tizen_src_files=\
+ ${adaptor_sensor_dir}/tizen/tilt-sensor-factory-tizen.cpp \
+ ${adaptor_sensor_dir}/tizen/tilt-sensor-impl-tizen.cpp
+
+# module: sensor, backend: ubuntu
+adaptor_sensor_ubuntu_src_files=\
+ ${adaptor_sensor_dir}/ubuntu/tilt-sensor-factory-ubuntu.cpp \
+ ${adaptor_sensor_dir}/ubuntu/tilt-sensor-impl-ubuntu.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace TiltSensorFactory
+{
+
+Dali::Internal::Adaptor::TiltSensor* Create()
+{
+ return Dali::Internal::Adaptor::TiltSensorTizen::New();
+}
+
+} // TiltSensorFactory
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h>
+#include <dali/internal/sensor/common/tilt-sensor-factory.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace // unnamed namespace
+{
+const char* const SIGNAL_TILTED = "tilted";
+
+const float MAX_ORIENTATION_ROLL_VALUE = 90.f;
+const float MAX_ORIENTATION_PITCH_VALUE = 180.f;
+const float MAX_ACCELEROMETER_VALUE = 9.8f;
+
+// Type Registration
+Dali::BaseHandle Create()
+{
+ return Dali::Internal::Adaptor::TiltSensorFactory::Get();
+}
+
+Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), Create );
+
+Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal );
+
+} // unnamed namespace
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#ifdef SENSOR_ENABLED
+static void sensor_changed_cb (sensor_h sensor, sensor_event_s *event, void *user_data)
+{
+ TiltSensorTizen* tiltSensor = reinterpret_cast< TiltSensorTizen* >( user_data );
+
+ if(tiltSensor)
+ {
+ tiltSensor->Update(event);
+ }
+
+ return;
+}
+
+static std::string get_sensor_error_string(int errorValue)
+{
+ std::string ret;
+
+ switch(errorValue)
+ {
+ case SENSOR_ERROR_IO_ERROR:
+ ret = "SENSOR_ERROR_IO_ERROR";
+ break;
+ case SENSOR_ERROR_INVALID_PARAMETER:
+ ret = "SENSOR_ERROR_INVALID_PARAMETER";
+ break;
+ case SENSOR_ERROR_NOT_SUPPORTED:
+ ret = "SENSOR_ERROR_NOT_SUPPORTED";
+ break;
+ case SENSOR_ERROR_PERMISSION_DENIED:
+ ret = "SENSOR_ERROR_PERMISSION_DENIED";
+ break;
+ case SENSOR_ERROR_OUT_OF_MEMORY:
+ ret = "SENSOR_ERROR_OUT_OF_MEMORY";
+ break;
+ case SENSOR_ERROR_NOT_NEED_CALIBRATION:
+ ret = "SENSOR_ERROR_NOT_NEED_CALIBRATION";
+ break;
+ case SENSOR_ERROR_OPERATION_FAILED:
+ ret = "SENSOR_ERROR_OPERATION_FAILED";
+ break;
+ }
+
+ return ret;
+}
+#endif
+
+TiltSensorTizen* TiltSensorTizen::New()
+{
+ return new TiltSensorTizen();
+}
+
+TiltSensorTizen::~TiltSensorTizen()
+{
+ Disconnect();
+}
+
+bool TiltSensorTizen::Connect()
+{
+#ifdef SENSOR_ENABLED
+ if(mState != DISCONNECTED)
+ {
+ Stop();
+ Disconnect();
+ }
+
+ const int interval = 1000/mFrequencyHertz;
+
+ int ret = 0;
+ bool isSupported = false;
+
+ // try to use Orientation sensor at first for less power consumption.
+ ret = sensor_is_supported(SENSOR_ORIENTATION, &isSupported);
+
+ if(ret < 0)
+ {
+ DALI_LOG_ERROR("sensor_is_supported() failed : %s\n", get_sensor_error_string(ret).c_str());
+ return false;
+ }
+
+ if(isSupported == true)
+ {
+ mSensorType = SENSOR_ORIENTATION;
+ }
+ else
+ {
+ DALI_LOG_ERROR("sensor does not support SENSOR_ORIENTATION\n");
+
+ sensor_is_supported(SENSOR_ACCELEROMETER, &isSupported);
+
+ if(isSupported == false)
+ {
+ DALI_LOG_ERROR("sensor does not support both SENSOR_ORIENTATION and SENSOR_ACCELEROMETER\n");
+ return false;
+ }
+
+ mSensorType = SENSOR_ACCELEROMETER;
+ }
+
+ ret = sensor_get_default_sensor(mSensorType, &mSensor); /* mSensor should not be deleted */
+
+ if(ret < 0)
+ {
+ DALI_LOG_ERROR("sensor_get_default_sensor() failed : %s\n", get_sensor_error_string(ret).c_str());
+ return false;
+ }
+
+ sensor_create_listener(mSensor, &mSensorListener);
+ sensor_listener_set_event_cb(mSensorListener, interval, sensor_changed_cb, this);
+ sensor_listener_set_interval(mSensorListener, interval);
+
+ sensor_listener_set_option(mSensorListener, SENSOR_OPTION_DEFAULT /* Not receive data when LCD is off and in power save mode */);
+
+ mState = CONNECTED;
+
+ return true;
+#endif
+
+ return false;
+}
+
+void TiltSensorTizen::Disconnect()
+{
+ if(mSensorListener)
+ {
+ if(mState == STARTED)
+ {
+ Stop();
+ }
+
+ if(mState == STOPPED || mState == CONNECTED)
+ {
+#ifdef SENSOR_ENABLED
+ sensor_listener_unset_event_cb(mSensorListener);
+ sensor_listener_stop(mSensorListener);
+ sensor_destroy_listener(mSensorListener);
+#endif
+ mSensor = NULL;
+ mSensorListener = NULL;
+ mState = DISCONNECTED;
+ }
+ }
+}
+
+bool TiltSensorTizen::Start()
+{
+ if( mSensorListener && ( mState == CONNECTED || mState == STOPPED ) )
+ {
+#ifdef SENSOR_ENABLED
+ int ret = 0;
+ ret = sensor_listener_start(mSensorListener);
+ if(ret != SENSOR_ERROR_NONE)
+ {
+ DALI_LOG_ERROR("sensor_listener_start() failed : %s\n", get_sensor_error_string(ret).c_str());
+ Disconnect();
+ return false;
+ }
+
+ mState = STARTED;
+ return true;
+#endif
+ }
+ else
+ {
+ if( mState == STARTED )
+ {
+ DALI_LOG_ERROR("TiltSensor is already started. Current state [%d]\n", mState);
+ }
+ else
+ {
+ // mState is DISCONNECTED
+ DALI_LOG_ERROR("TiltSensor is disconnected. Current state [%d]\n", mState);
+ }
+ return false;
+ }
+ return false;
+}
+
+void TiltSensorTizen::Stop()
+{
+#ifdef SENSOR_ENABLED
+ if(mSensorListener && mState == STARTED)
+ {
+ sensor_listener_stop( mSensorListener );
+ mState = STOPPED;
+ }
+#endif
+}
+
+bool TiltSensorTizen::IsStarted() const
+{
+ return ( mSensorListener && mState == STARTED );
+}
+
+float TiltSensorTizen::GetRoll() const
+{
+ return mRoll;
+}
+
+float TiltSensorTizen::GetPitch() const
+{
+ return mPitch;
+}
+
+Quaternion TiltSensorTizen::GetRotation() const
+{
+ return mRotation;
+}
+
+TiltSensor::TiltedSignalType& TiltSensorTizen::TiltedSignal()
+{
+ return mTiltedSignal;
+}
+
+void TiltSensorTizen::SetUpdateFrequency( float frequencyHertz )
+{
+ DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" );
+
+ if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) )
+ {
+ mFrequencyHertz = frequencyHertz;
+
+#ifdef SENSOR_ENABLED
+ if(mSensorListener)
+ {
+ const int interval = 1000/mFrequencyHertz;
+ sensor_listener_set_interval(mSensorListener, interval);
+ }
+#endif
+ }
+}
+
+float TiltSensorTizen::GetUpdateFrequency() const
+{
+ return mFrequencyHertz;
+}
+
+void TiltSensorTizen::SetRotationThreshold(Radian rotationThreshold)
+{
+ mRotationThreshold = rotationThreshold;
+}
+
+Radian TiltSensorTizen::GetRotationThreshold() const
+{
+ return mRotationThreshold;
+}
+
+bool TiltSensorTizen::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+{
+ bool connected( true );
+ TiltSensor* sensor = dynamic_cast<TiltSensor*>( object );
+
+ if( sensor && SIGNAL_TILTED == signalName )
+ {
+ sensor->TiltedSignal().Connect( tracker, functor );
+ }
+ else
+ {
+ // signalName does not match any signal
+ connected = false;
+ }
+
+ return connected;
+}
+
+TiltSensorTizen::TiltSensorTizen()
+: mState(DISCONNECTED),
+ mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ),
+ mSensor( NULL ),
+ mSensorListener( NULL ),
+ mRoll( 0.0f ),
+ mPitch( 0.0f ),
+ mRotation( Radian(0.0f), Vector3::YAXIS ),
+ mRotationThreshold( 0.0f )
+{
+ // connect sensor
+ Connect();
+}
+
+#ifdef SENSOR_ENABLED
+void TiltSensorTizen::Update(sensor_event_s *event)
+{
+ Radian newRoll( 0.0f );
+ Radian newPitch( 0.0f );
+ Quaternion newRotation;
+
+ if(mSensorType == SENSOR_ORIENTATION)
+ {
+ newRoll = Clamp( float(event->values[2] / MAX_ORIENTATION_ROLL_VALUE) /* -90 < roll < 90 */, -1.0f/*min*/, 1.0f/*max*/ );
+ newPitch = Clamp( float(event->values[1] / MAX_ORIENTATION_PITCH_VALUE) /* -180 < pitch < 180 */, -1.0f/*min*/, 1.0f/*max*/ );
+ }
+ else if(mSensorType == SENSOR_ACCELEROMETER)
+ {
+ newRoll = Clamp( float(event->values[0] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ );
+ newPitch = Clamp( float(event->values[1] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ );
+ }
+ else
+ {
+ DALI_LOG_ERROR("Invalid sensor type\n");
+ return;
+ }
+
+ newRotation = Quaternion( Radian( newRoll * Math::PI * -0.5f ), Vector3::YAXIS ) *
+ Quaternion( Radian( newPitch * Math::PI * -0.5f ), Vector3::XAXIS );
+
+ Radian angle(Quaternion::AngleBetween(newRotation, mRotation));
+
+ // If the change in value is more than the threshold then emit tilted signal.
+ if( angle >= mRotationThreshold )
+ {
+ mRoll = newRoll;
+ mPitch = newPitch;
+ mRotation = newRotation;
+
+ // emit signal
+ if ( !mTiltedSignal.Empty() )
+ {
+ Dali::TiltSensor handle( this );
+ mTiltedSignal.Emit( handle );
+ }
+ }
+}
+#endif // SENSOR_ENABLED
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_SENSOR_TIZEN_TILT_SENSOR_IMPL_TIZEN_H
+#define DALI_SENSOR_TIZEN_TILT_SENSOR_IMPL_TIZEN_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#ifdef CAPI_SYSTEM_SENSOR_SUPPORT
+#include <sensor/sensor.h>
+#define SENSOR_ENABLED
+#endif
+
+#include <deque>
+#include <dali/public-api/object/base-object.h>
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/timer.h>
+#include <dali/devel-api/adaptor-framework/tilt-sensor.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * TiltSensorTizen provides pitch & roll values when the device is tilted.
+ */
+class TiltSensorTizen : public Dali::Internal::Adaptor::TiltSensor
+{
+public:
+
+ typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType;
+
+ /**
+ * Public constructor
+ * @return New instance of TiltSensorTizen
+ */
+ static TiltSensorTizen* New();
+
+ /**
+ * @copydoc Dali::TiltSensor::Start()
+ */
+ bool Start() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::Stop()
+ */
+ void Stop() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::IsStarted()
+ */
+ bool IsStarted() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRoll()
+ */
+ float GetRoll() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetPitch()
+ */
+ float GetPitch() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotation()
+ */
+ Quaternion GetRotation() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::TiltedSignal()
+ */
+ TiltedSignalType& TiltedSignal() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::SetUpdateFrequency()
+ */
+ void SetUpdateFrequency( float frequencyHertz ) override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetUpdateFrequency()
+ */
+ float GetUpdateFrequency() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::SetRotationThreshold()
+ */
+ void SetRotationThreshold(Radian rotationThreshold) override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotationThreshold()
+ */
+ Radian GetRotationThreshold() const override;
+
+ /**
+ * Connects a callback function with the object's signals.
+ * @param[in] object The object providing the signal.
+ * @param[in] tracker Used to disconnect the signal.
+ * @param[in] signalName The signal to connect to.
+ * @param[in] functor A newly allocated FunctorDelegate.
+ * @return True if the signal was connected.
+ * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
+ */
+ static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
+
+ /**
+ * Update sensor data
+ * @note This is called by static sensor callback function
+ * @param[in] event sensor event data
+ */
+#ifdef SENSOR_ENABLED
+ void Update(sensor_event_s *event);
+#endif
+
+
+private:
+
+ enum State
+ {
+ DISCONNECTED,
+ CONNECTED,
+ STARTED,
+ STOPPED
+ };
+
+ /**
+ * Private constructor; see also TiltSensor::New()
+ */
+ TiltSensorTizen();
+
+ /**
+ * Destructor
+ */
+ virtual ~TiltSensorTizen();
+
+ /**
+ * Connect sensor device
+ */
+ bool Connect();
+ /**
+ * Disconnect sensor device
+ */
+ void Disconnect();
+
+ // Undefined
+ TiltSensorTizen(const TiltSensor&);
+
+ // Undefined
+ TiltSensorTizen& operator=(TiltSensor&);
+
+private:
+ State mState;
+ float mFrequencyHertz;
+
+#ifdef SENSOR_ENABLED
+ sensor_type_e mSensorType;
+ sensor_h mSensor;
+ sensor_listener_h mSensorListener;
+#else
+ int mSensorType;
+ int* mSensor;
+ int* mSensorListener;
+#endif
+
+ float mRoll;
+ float mPitch;
+ Quaternion mRotation;
+
+ Radian mRotationThreshold;
+
+ TiltedSignalType mTiltedSignal;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_SENSOR_TIZEN_TILT_SENSOR_IMPL_TIZEN_H
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+namespace TiltSensorFactory
+{
+
+Dali::Internal::Adaptor::TiltSensor* Create()
+{
+ return Dali::Internal::Adaptor::TiltSensorUbuntu::New();
+}
+
+} // TiltSensorFactory
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h>
+#include <dali/internal/sensor/common/tilt-sensor-factory.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace // unnamed namespace
+{
+
+const char* const SIGNAL_TILTED = "tilted";
+
+const int NUMBER_OF_SAMPLES = 10;
+
+const float MAX_ACCELEROMETER_XY_VALUE = 9.8f;
+
+// Type Registration
+Dali::BaseHandle GetInstance()
+{
+ return Dali::Internal::Adaptor::TiltSensorFactory::Get();
+}
+
+Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), GetInstance );
+
+Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal );
+
+} // unnamed namespace
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+TiltSensorUbuntu* TiltSensorUbuntu::New()
+{
+ return new TiltSensorUbuntu();
+}
+
+TiltSensorUbuntu::~TiltSensorUbuntu()
+{
+ Stop();
+}
+
+bool TiltSensorUbuntu::Start()
+{
+ // Make sure sensor API is responding
+ bool success = Update();
+
+ if ( success )
+ {
+ if ( !mTimer )
+ {
+ mTimer = Dali::Timer::New( 1000.0f / mFrequencyHertz );
+ mTimer.TickSignal().Connect( mTimerSlot, &TiltSensorUbuntu::Update );
+ }
+
+ if ( mTimer &&
+ !mTimer.IsRunning() )
+ {
+ mTimer.Start();
+ }
+ }
+
+ return success;
+}
+
+void TiltSensorUbuntu::Stop()
+{
+ if ( mTimer )
+ {
+ mTimer.Stop();
+ mTimer.Reset();
+ }
+}
+
+bool TiltSensorUbuntu::IsStarted() const
+{
+ return ( mTimer && mTimer.IsRunning() );
+}
+
+float TiltSensorUbuntu::GetRoll() const
+{
+ return mRoll;
+}
+
+float TiltSensorUbuntu::GetPitch() const
+{
+ return mPitch;
+}
+
+Quaternion TiltSensorUbuntu::GetRotation() const
+{
+ return mRotation;
+}
+
+TiltSensor::TiltedSignalType& TiltSensorUbuntu::TiltedSignal()
+{
+ return mTiltedSignal;
+}
+
+void TiltSensorUbuntu::SetUpdateFrequency( float frequencyHertz )
+{
+ DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" );
+
+ if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) )
+ {
+ mFrequencyHertz = frequencyHertz;
+
+ if ( mTimer )
+ {
+ mTimer.SetInterval( 1000.0f / mFrequencyHertz );
+ }
+ }
+}
+
+float TiltSensorUbuntu::GetUpdateFrequency() const
+{
+ return mFrequencyHertz;
+}
+
+void TiltSensorUbuntu::SetRotationThreshold(Radian rotationThreshold)
+{
+ mRotationThreshold = rotationThreshold;
+}
+
+Radian TiltSensorUbuntu::GetRotationThreshold() const
+{
+ return mRotationThreshold;
+}
+
+bool TiltSensorUbuntu::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+{
+ bool connected( true );
+ TiltSensor* sensor = dynamic_cast<TiltSensor*>( object );
+
+ if( sensor && ( SIGNAL_TILTED == signalName ) )
+ {
+ sensor->TiltedSignal().Connect( tracker, functor );
+ }
+ else
+ {
+ // signalName does not match any signal
+ connected = false;
+ }
+
+ return connected;
+}
+
+TiltSensorUbuntu::TiltSensorUbuntu()
+: mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ),
+ mTimerSlot( this ),
+ mSensorFrameworkHandle( -1 ),
+ mRoll( 0.0f ),
+ mPitch( 0.0f ),
+ mRotation( Dali::ANGLE_0, Vector3::YAXIS ),
+ mRotationThreshold( 0.0f )
+{
+ mRollValues.resize( NUMBER_OF_SAMPLES, 0.0f );
+ mPitchValues.resize( NUMBER_OF_SAMPLES, 0.0f );
+}
+
+bool TiltSensorUbuntu::Update()
+{
+ float newRoll = 0.0f;
+ float newPitch = 0.0f;
+ Quaternion newRotation;
+
+ Radian angle(Quaternion::AngleBetween(newRotation, mRotation));
+ // If the change in value is more than the threshold then emit tilted signal.
+ if( angle > mRotationThreshold )
+ {
+ mRoll = newRoll;
+ mPitch = newPitch;
+ mRotation = newRotation;
+
+ if ( !mTiltedSignal.Empty() )
+ {
+ Dali::TiltSensor handle( this );
+ mTiltedSignal.Emit( handle );
+ }
+ }
+
+ return true;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_SENSOR_UBUNTU_TILT_SENSOR_IMPL_UBUNTU_H
+#define DALI_SENSOR_UBUNTU_TILT_SENSOR_IMPL_UBUNTU_H
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <deque>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/sensor/common/tilt-sensor-impl.h>
+#include <dali/devel-api/adaptor-framework/tilt-sensor.h>
+#include <dali/public-api/adaptor-framework/timer.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * TiltSensor provides pitch & roll values when the device is tilted.
+ */
+class TiltSensorUbuntu : public Dali::Internal::Adaptor::TiltSensor
+{
+public:
+
+ typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType;
+
+ /**
+ * Public constructor
+ * @return New instance of TiltSensorUbuntu
+ */
+ static TiltSensorUbuntu* New();
+
+ /**
+ * @copydoc Dali::TiltSensor::Start()
+ */
+ bool Start() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::Stop()
+ */
+ void Stop() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::IsStarted()
+ */
+ bool IsStarted() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRoll()
+ */
+ float GetRoll() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetPitch()
+ */
+ float GetPitch() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotation()
+ */
+ Quaternion GetRotation() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::TiltedSignal()
+ */
+ TiltedSignalType& TiltedSignal() override;
+
+ /**
+ * @copydoc Dali::TiltSensor::SetUpdateFrequency()
+ */
+ void SetUpdateFrequency( float frequencyHertz ) override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetUpdateFrequency()
+ */
+ float GetUpdateFrequency() const override;
+
+ /**
+ * @copydoc Dali::TiltSensor::SetRotationThreshold()
+ */
+ void SetRotationThreshold(Radian rotationThreshold) override;
+
+ /**
+ * @copydoc Dali::TiltSensor::GetRotationThreshold()
+ */
+ Radian GetRotationThreshold() const override;
+
+ /**
+ * Connects a callback function with the object's signals.
+ * @param[in] object The object providing the signal.
+ * @param[in] tracker Used to disconnect the signal.
+ * @param[in] signalName The signal to connect to.
+ * @param[in] functor A newly allocated FunctorDelegate.
+ * @return True if the signal was connected.
+ * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
+ */
+ static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
+
+private:
+
+ /**
+ * Private constructor; see also TiltSensor::New()
+ */
+ TiltSensorUbuntu();
+
+ /**
+ * Destructor
+ */
+ virtual ~TiltSensorUbuntu() override;
+
+ /**
+ * Timer callback to update the tilt values
+ */
+ bool Update();
+
+ // Undefined
+ TiltSensorUbuntu(const TiltSensorUbuntu&) = delete;
+
+ // Undefined
+ TiltSensorUbuntu& operator=(TiltSensorUbuntu&) = delete;
+
+private:
+
+ float mFrequencyHertz;
+ Dali::Timer mTimer;
+ SlotDelegate< TiltSensorUbuntu > mTimerSlot;
+
+ int mSensorFrameworkHandle;
+
+ float mRoll;
+ float mPitch;
+ Quaternion mRotation;
+
+ Radian mRotationThreshold;
+
+ std::deque<float> mRollValues;
+ std::deque<float> mPitchValues;
+
+ TiltedSignalType mTiltedSignal;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_SENSOR_UBUNTU_TILT_SENSOR_IMPL_UBUNTU_H
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/styling/common/style-monitor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+#include <fstream>
+#include <sstream>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_STYLE_MONITOR");
+#endif
+
+/**
+ * Use font client to get the system default font family
+ * @param[in] fontClient handle to font client
+ * @param[out] fontFamily string representing font family
+ */
+void GetSystemDefaultFontFamily( TextAbstraction::FontClient& fontClient, std::string& fontFamily )
+{
+ TextAbstraction::FontDescription defaultFontDescription;
+ if ( fontClient )
+ {
+ fontClient.GetDefaultPlatformFontDescription( defaultFontDescription );
+ fontFamily = defaultFontDescription.family;
+ }
+}
+
+} // unnamed namespace
+
+Dali::StyleMonitor StyleMonitor::Get()
+{
+ Dali::StyleMonitor styleMonitor;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::StyleMonitor ) );
+ if( handle )
+ {
+ // If so, downcast the handle
+ styleMonitor = Dali::StyleMonitor( dynamic_cast< StyleMonitor* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ styleMonitor = Dali::StyleMonitor( new StyleMonitor() );
+ service.Register( typeid( styleMonitor ), styleMonitor );
+ }
+ }
+
+ return styleMonitor;
+}
+
+StyleMonitor::StyleMonitor()
+: mDefaultFontSize(-1)
+{
+ mFontClient = TextAbstraction::FontClient::Get();
+ GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleMonitor::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() );
+ mDefaultFontSize = mFontClient.GetDefaultFontSize();
+}
+
+StyleMonitor::~StyleMonitor()
+{
+}
+
+void StyleMonitor::StyleChanged( StyleChange::Type styleChange )
+{
+ switch ( styleChange )
+ {
+ case StyleChange::DEFAULT_FONT_CHANGE:
+ {
+ if ( mFontClient )
+ {
+ mFontClient.ResetSystemDefaults();
+ GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily );
+ }
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleChanged::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() );
+ break;
+ }
+
+ case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
+ {
+ mDefaultFontSize = mFontClient.GetDefaultFontSize();
+ break;
+ }
+
+ case StyleChange::THEME_CHANGE:
+ {
+ break;
+ }
+ }
+
+ EmitStyleChangeSignal(styleChange);
+}
+
+std::string StyleMonitor::GetDefaultFontFamily() const
+{
+ return mDefaultFontFamily;
+}
+
+std::string StyleMonitor::GetDefaultFontStyle() const
+{
+ return mDefaultFontStyle;
+}
+
+int StyleMonitor::GetDefaultFontSize() const
+{
+ return mDefaultFontSize;
+}
+
+const std::string& StyleMonitor::GetTheme() const
+{
+ return mUserDefinedThemeFilePath;
+}
+
+void StyleMonitor::SetTheme(const std::string& path)
+{
+ mUserDefinedThemeFilePath = path;
+ EmitStyleChangeSignal( StyleChange::THEME_CHANGE );
+}
+
+bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output )
+{
+ bool retval( false );
+ std::ifstream in( filename.c_str(), std::ios::in );
+ if( in )
+ {
+ std::stringstream buffer;
+ buffer << in.rdbuf();
+
+ output = buffer.str();
+
+ in.close();
+ retval = true;
+ }
+ return retval;
+}
+
+Dali::StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal()
+{
+ return mStyleChangeSignal;
+}
+
+void StyleMonitor::EmitStyleChangeSignal( StyleChange::Type styleChange )
+{
+ if( !mStyleChangeSignal.Empty() )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::EmitStyleChangeSignal\n" );
+ Dali::StyleMonitor handle( this );
+ mStyleChangeSignal.Emit( handle, styleChange );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_STYLE_MONITOR_H__
+#define __DALI_INTERNAL_STYLE_MONITOR_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/devel-api/text-abstraction/font-client.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * This holds the platform's style information.
+ * It provides a signal when any aspect of the default style changes on the device.
+ */
+class StyleMonitor : public BaseObject
+{
+public:
+
+ // Creation & Destruction
+
+ /**
+ * Constructor.
+ */
+ StyleMonitor();
+
+ /**
+ * Retrieve the initialized instance of the StyleMonitor.
+ * @return Handle to StyleMonitor.
+ */
+ static Dali::StyleMonitor Get();
+
+ // Style Change Notifications
+
+ /**
+ * Informs the Style Monitor that the style has changed.
+ * @param[in] styleChange The details of the change.
+ */
+ void StyleChanged( StyleChange::Type styleChange );
+
+ // Style Information
+
+ /**
+ * @copydoc Dali::StyleMonitor::GetDefaultFontFamily() const
+ */
+ std::string GetDefaultFontFamily() const;
+
+ /**
+ * @copydoc Dali::StyleMonitor::GetDefaultFontStyle() const
+ */
+ std::string GetDefaultFontStyle() const;
+
+ /**
+ * @copydoc Dali::StyleMonitor::GetDefaultFontSize() const
+ */
+ int GetDefaultFontSize() const;
+
+ /**
+ * @copydoc Dali::StyleMonitor::GetTheme() const
+ */
+ const std::string& GetTheme() const;
+
+ /**
+ * @copydoc Dali::StyleMonitor::SetTheme()
+ */
+ void SetTheme(const std::string& themeFilePath);
+
+ /**
+ * @copydoc Dali::StyleMonitor::LoadThemeFile()
+ */
+ bool LoadThemeFile( const std::string& filename, std::string& output );
+
+ // Signals
+
+ /**
+ * @copydoc Dali::StyleMonitor::StyleChangeSignal()
+ */
+ Dali::StyleMonitor::StyleChangeSignalType& StyleChangeSignal();
+
+protected:
+
+ /**
+ * Virtual Destructor.
+ */
+ virtual ~StyleMonitor();
+
+private:
+
+ /**
+ * Emit the style change signal.
+ * @param[in] styleChange The details of the style change
+ */
+ inline void EmitStyleChangeSignal( StyleChange::Type styleChange );
+
+private:
+
+ Dali::StyleMonitor::StyleChangeSignalType mStyleChangeSignal; ///< Emitted when the style changes
+
+ TextAbstraction::FontClient mFontClient;
+ std::string mDefaultFontFamily; ///< The system default font family
+ std::string mDefaultFontStyle; ///< The default font style
+ std::string mUserDefinedThemeFilePath; ///< String containing the user defined theme file path
+ int mDefaultFontSize; ///< The default accessibility font size e.g. 0 is smallest
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Additional Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::StyleMonitor& GetImplementation(Dali::StyleMonitor& monitor)
+{
+ DALI_ASSERT_ALWAYS(monitor && "Monitor handle is empty");
+ BaseObject& handle = monitor.GetBaseObject();
+ return static_cast<Internal::Adaptor::StyleMonitor&>(handle);
+}
+
+inline const Internal::Adaptor::StyleMonitor& GetImplementation(const Dali::StyleMonitor& monitor)
+{
+ DALI_ASSERT_ALWAYS(monitor && "Monitor handle is empty");
+ const BaseObject& handle = monitor.GetBaseObject();
+ return static_cast<const Internal::Adaptor::StyleMonitor&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_STYLE_MONITOR_H__
--- /dev/null
+
+
+# module: styling, backend: common
+adaptor_styling_common_src_files=\
+ ${adaptor_styling_dir}/common/style-monitor-impl.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/abort-handler.h>
+
+// EXTERNAL INCLUDES
+#include <cstring>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+AbortHandler* AbortHandler::gInstance(NULL);
+
+AbortHandler::AbortHandler( CallbackBase* callback )
+: mSignalMask( 0 ),
+ mCallback( callback )
+{
+ DALI_ASSERT_ALWAYS( gInstance == NULL && "Only one instance of abort handler allowed" );
+ gInstance = this;
+
+ memset( mSignalOldHandlers, 0, sizeof(SignalHandlerFuncPtr) * (_NSIG-1));
+}
+
+AbortHandler::~AbortHandler()
+{
+ delete mCallback;
+
+ int signum;
+ for ( signum = 1; signum < _NSIG; signum++ )
+ {
+ if ( mSignalMask & (1 << (signum-1) ) )
+ {
+ // set signals back to default handling
+ signal( signum, mSignalOldHandlers[signum-1] );
+ }
+ }
+ gInstance = NULL;
+}
+
+bool AbortHandler::AbortOnSignal( int signum )
+{
+ bool status = false;
+
+ if ( signum < _NSIG )
+ {
+ SignalHandlerFuncPtr signalHandlerPrevious = signal( signum, &AbortHandler::SignalHandler );
+
+// SIG_ERR is a macro with C cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ if ( SIG_ERR != signalHandlerPrevious )
+ {
+ mSignalOldHandlers[signum-1] = signalHandlerPrevious;
+ mSignalMask |= ( 1 << (signum-1) );
+ status = true;
+ }
+ }
+#pragma GCC diagnostic pop
+ return status;
+}
+
+void AbortHandler::SignalHandler( int signum )
+{
+ if( gInstance )
+ {
+ if( gInstance->mCallback )
+ {
+ CallbackBase::Execute( *gInstance->mCallback );
+ }
+ }
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
+#define __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <signal.h>
+#include <dali/public-api/signals/callback.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * Class to listen to system signals and trigger an abort callback
+ * when they occur.
+ *
+ * This class maintains a process wide singleton, as the signal(2) system
+ * call is process specific, not thread specific.
+ *
+ * Currently, this precludes having multiple DALi instances in the same process.
+ */
+class AbortHandler
+{
+public:
+ /**
+ * Constructor
+ * @param[in] callback The function to call when abort signals occur
+ * @note The ownership of callback is passed onto this class.
+ */
+ AbortHandler( CallbackBase* callback );
+
+ /**
+ * Destructor
+ */
+ ~AbortHandler();
+
+ /**
+ * Add a signal you want to be handled by this abort handler.
+ * @param[in] signum The signal number (from signum.h)
+ * @return true if the signal handler was installed ok
+ */
+ bool AbortOnSignal( int signum );
+
+private:
+ /**
+ * Signal handler - Called when signal is received.
+ * Stops the application.
+ */
+ static void SignalHandler( int signum );
+
+ /**
+ * Default constructor - undefined
+ */
+ AbortHandler();
+
+ /**
+ * Copy constructor - undefined
+ */
+ AbortHandler(const AbortHandler& rhs);
+
+ /**
+ * Assignment operator - undefined
+ */
+ AbortHandler& operator=(const AbortHandler& rhs);
+
+private:
+ typedef void (*SignalHandlerFuncPtr )( int );
+
+ // _NSIG comes from the signal.h linux system header, defining the number of signals.
+ SignalHandlerFuncPtr mSignalOldHandlers[_NSIG-1];
+ unsigned long long mSignalMask;
+
+ CallbackBase* mCallback;
+
+ static AbortHandler* gInstance;
+};
+
+} // Namespace Adaptor
+} // Namespace Internal
+} // Namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/callback-manager-ecore.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Structure contains the callback function and control options
+ */
+struct CallbackData
+{
+
+ /**
+ * Constructor
+ */
+ CallbackData( CallbackBase* callback )
+ : mCallback(callback),
+ mRemoveFromContainerFunction(NULL),
+ mIdler(NULL)
+ {
+ }
+ /**
+ * Destructor
+ */
+ ~CallbackData()
+ {
+ delete mCallback;
+ delete mRemoveFromContainerFunction;
+ }
+
+ CallbackBase* mCallback; ///< call back
+ CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container
+ Ecore_Idler* mIdler; ///< ecore idler
+ };
+
+namespace
+{
+
+/**
+ * Called from the main thread while idle.
+ */
+Eina_Bool IdleCallback(void *data)
+{
+ CallbackData *callbackData = static_cast< CallbackData * >( data );
+
+ // remove callback data from the container
+ CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData );
+
+ // run the function
+ CallbackBase::Execute( *callbackData->mCallback );
+
+ // delete our data
+ delete callbackData;
+
+ // CALLBACK Cancel will delete the idler so we don't need to call ecore_idler_del
+ return ECORE_CALLBACK_CANCEL;
+}
+
+} // unnamed namespace
+
+EcoreCallbackManager::EcoreCallbackManager()
+:mRunning(false)
+{
+}
+
+
+void EcoreCallbackManager::Start()
+{
+ DALI_ASSERT_DEBUG( mRunning == false );
+
+ mRunning = true;
+}
+
+void EcoreCallbackManager::Stop()
+{
+ // make sure we're not called twice
+ DALI_ASSERT_DEBUG( mRunning == true );
+
+ RemoveAllCallbacks();
+
+ mRunning = false;
+
+}
+
+bool EcoreCallbackManager::AddIdleCallback( CallbackBase* callback )
+{
+ if( !mRunning )
+ {
+ return false;
+ }
+
+ CallbackData* callbackData = new CallbackData( callback );
+
+ callbackData->mRemoveFromContainerFunction = MakeCallback( this, &EcoreCallbackManager::RemoveCallbackFromContainer );
+
+ // add the call back to the container
+ mCallbackContainer.push_front(callbackData);
+
+ // add the idler
+ callbackData->mIdler = ecore_idler_add( IdleCallback, callbackData);
+
+ DALI_ASSERT_ALWAYS( ( callbackData->mIdler != NULL ) && "Idle method not created" );
+
+ return true;
+}
+
+void EcoreCallbackManager::RemoveIdleCallback( CallbackBase* callback )
+{
+ for( CallbackList::iterator it = mCallbackContainer.begin(),
+ endIt = mCallbackContainer.end();
+ it != endIt;
+ ++it )
+ {
+ CallbackData* data = *it;
+
+ if( data->mCallback == callback )
+ {
+ // remove callback data from the container.
+ CallbackBase::Execute( *data->mRemoveFromContainerFunction, data );
+
+ ecore_idler_del( data->mIdler );
+ }
+ }
+}
+
+void EcoreCallbackManager::RemoveCallbackFromContainer(CallbackData *callbackData)
+{
+ mCallbackContainer.remove(callbackData);
+}
+
+void EcoreCallbackManager::RemoveAllCallbacks()
+{
+ // always called from main thread
+ for( CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter)
+ {
+ CallbackData* data = (*iter);
+
+ ecore_idler_del( data->mIdler );
+
+ delete data;
+
+ }
+ mCallbackContainer.clear();
+}
+
+// Creates a concrete interface for CallbackManager
+CallbackManager* CallbackManager::New()
+{
+ return new EcoreCallbackManager;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_ECORE_CALLBACK_MANAGER_H__
+#define __DALI_ECORE_CALLBACK_MANAGER_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <list>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/callback-manager.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+struct CallbackData;
+
+/**
+ * Ecore interface to install call backs in the applications main loop.
+ */
+class EcoreCallbackManager : public CallbackManager
+{
+
+public:
+
+ /**
+ * @brief constructor
+ */
+ EcoreCallbackManager();
+
+ /**
+ * @brief destructor
+ */
+ ~EcoreCallbackManager()
+ {
+ }
+
+ /**
+ * @copydoc CallbackManager::AddIdleCallback()
+ */
+ virtual bool AddIdleCallback( CallbackBase* callback );
+
+ /**
+ * @copydoc CallbackManager::RemoveIdleCallback()
+ */
+ virtual void RemoveIdleCallback( CallbackBase* callback );
+
+ /**
+ * @copydoc CallbackManager::Start()
+ */
+ virtual void Start();
+
+ /**
+ * @copydoc CallbackManager::Stop()
+ */
+ virtual void Stop();
+
+private:
+
+ /**
+ * @brief Remove all idle call backs that are pending
+ * Called by Stop()
+ * Always called from the main thread
+ */
+ void RemoveAllCallbacks();
+
+ /**
+ * @brief Removes a single call back from the container
+ * Always called from main thread
+ * @param callbackData callback data
+ */
+ void RemoveCallbackFromContainer(CallbackData *callbackData);
+
+ /**
+ * @brief Remove a standard call back from ecore
+ * Always called from main thread
+ * @param callbackData callback data
+ */
+ void RemoveStandardCallback(CallbackData *callbackData);
+
+
+ typedef std::list<CallbackData *> CallbackList;
+
+ bool mRunning; ///< flag is set to true if when running
+ CallbackList mCallbackContainer; ///< container of live idle callbacks
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_ECORE_CALLBACK_MANAGER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/command-line-options.h>
+
+// EXTERNAL INCLUDES
+#include <getopt.h>
+#include <stdlib.h>
+#include <string.h>
+#include <iostream>
+
+#include <dali/public-api/common/dali-vector.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+struct Argument
+{
+ const char * const opt;
+ const char * const optDescription;
+
+ void Print()
+ {
+ const std::ios_base::fmtflags flags = std::cout.flags();
+ std::cout << std::left << " --";
+ std::cout.width( 18 );
+ std::cout << opt;
+ std::cout << optDescription;
+ std::cout << std::endl;
+ std::cout.flags( flags );
+ }
+};
+
+Argument EXPECTED_ARGS[] =
+{
+ { "no-vsync", "Disable VSync on Render" },
+ { "width", "Stage Width" },
+ { "height", "Stage Height" },
+ { "dpi", "Emulated DPI" },
+ { "view", "Stereocopic 3D view mode ([0]=MONO, 1=STEREO_HORIZONTAL, 2=STEREO_VERTICAL, 3=STEREO_INTERLACED)" },
+ { "stereo-base", "Distance in millimeters between left/right cameras [65.0]" },
+ { "help", "Help" },
+ { NULL, NULL }
+};
+
+enum Option
+{
+ OPTION_NO_VSYNC = 0,
+ OPTION_STAGE_WIDTH,
+ OPTION_STAGE_HEIGHT,
+ OPTION_DPI,
+ OPTION_STEREO_MODE,
+ OPTION_STEREO_BASE,
+ OPTION_HELP
+};
+
+typedef Dali::Vector< int > UnhandledContainer;
+
+void ShowHelp()
+{
+ std::cout << "Available options:" << std::endl;
+ Argument* arg = EXPECTED_ARGS;
+ while ( arg->opt )
+ {
+ arg->Print();
+ ++arg;
+ }
+}
+
+} // unnamed namespace
+
+CommandLineOptions::CommandLineOptions(int *argc, char **argv[])
+: noVSyncOnRender(0),
+ stageWidth(0), stageHeight(0),
+ viewMode(0),
+ stereoBase(65)
+{
+ // Exit gracefully if no arguments provided
+ if ( !argc || !argv )
+ {
+ return;
+ }
+
+ if ( *argc > 1 )
+ {
+ // We do not want to print out errors.
+ int origOptErrValue( opterr );
+ opterr = 0;
+
+ int help( 0 );
+
+ const struct option options[]=
+ {
+ { EXPECTED_ARGS[OPTION_NO_VSYNC].opt, no_argument, &noVSyncOnRender, 1 }, // "--no-vsync"
+ { EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w' }, // "--width"
+ { EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h' }, // "--height"
+ { EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd' }, // "--dpi"
+ { EXPECTED_ARGS[OPTION_STEREO_MODE].opt, required_argument, NULL, 'v' }, // "--view"
+ { EXPECTED_ARGS[OPTION_STEREO_BASE].opt, required_argument, NULL, 's' }, // "--stereo-base"
+ { EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?' }, // "--help"
+ { 0, 0, 0, 0 } // end of options
+ };
+
+ int shortOption( 0 );
+ int optionIndex( 0 );
+
+ const char* optString = "-w:h:d:v:s:"; // The '-' ensures that argv is NOT permuted
+ bool optionProcessed( false );
+
+ UnhandledContainer unhandledOptions; // We store indices of options we do not handle here
+
+ do
+ {
+ shortOption = getopt_long( *argc, *argv, optString, options, &optionIndex );
+
+ switch ( shortOption )
+ {
+ case 0:
+ {
+ // Check if we want help
+ if ( help )
+ {
+ ShowHelp();
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case 'w':
+ {
+ if ( optarg )
+ {
+ stageWidth = atoi( optarg );
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case 'h':
+ {
+ if ( optarg )
+ {
+ stageHeight = atoi( optarg );
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case 'd':
+ {
+ if ( optarg )
+ {
+ stageDPI.assign( optarg );
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case 'v':
+ {
+ if ( optarg )
+ {
+ viewMode = atoi(optarg);
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case 's':
+ {
+ if ( optarg )
+ {
+ stereoBase = atoi(optarg);
+ optionProcessed = true;
+ }
+ break;
+ }
+
+ case -1:
+ {
+ // All command-line options have been parsed.
+ break;
+ }
+
+ default:
+ {
+ unhandledOptions.PushBack( optind - 1 );
+ break;
+ }
+ }
+ } while ( shortOption != -1 );
+
+ // Take out the options we have processed
+ if ( optionProcessed )
+ {
+ if ( unhandledOptions.Count() > 0 )
+ {
+ int index( 1 );
+
+ // Overwrite the argv with the values from the unhandled indices
+ const UnhandledContainer::ConstIterator endIter = unhandledOptions.End();
+ for ( UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter )
+ {
+ (*argv)[ index++ ] = (*argv)[ *iter ];
+ }
+ *argc = unhandledOptions.Count() + 1; // +1 for the program name
+ }
+ else
+ {
+ // There are no unhandled options, so we should just have the program name
+ *argc = 1;
+ }
+
+ optind = 1; // Reset to start
+ }
+
+ opterr = origOptErrValue; // Reset opterr value.
+ }
+}
+
+CommandLineOptions::~CommandLineOptions()
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/environment-options.h>
+
+// EXTERNAL INCLUDES
+#include <cstdlib>
+#include <dali/integration-api/render-controller.h>
+#include <dali/public-api/math/math-utils.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-variables.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const unsigned int DEFAULT_STATISTICS_LOG_FREQUENCY = 2;
+const int DEFAULT_MULTI_SAMPLING_LEVEL = -1;
+const bool DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING = true;
+const bool DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING = true;
+
+unsigned int GetIntegerEnvironmentVariable( const char* variable, unsigned int defaultValue )
+{
+ const char* variableParameter = std::getenv(variable);
+
+ // if the parameter exists convert it to an integer, else return the default value
+ unsigned int intValue = variableParameter ? std::atoi(variableParameter) : defaultValue;
+ return intValue;
+}
+
+bool GetIntegerEnvironmentVariable( const char* variable, int& intValue )
+{
+ const char* variableParameter = std::getenv(variable);
+
+ if( !variableParameter )
+ {
+ return false;
+ }
+ // if the parameter exists convert it to an integer, else return the default value
+ intValue = std::atoi(variableParameter);
+ return true;
+}
+
+bool GetFloatEnvironmentVariable( const char* variable, float& floatValue )
+{
+ const char* variableParameter = std::getenv(variable);
+
+ if( !variableParameter )
+ {
+ return false;
+ }
+ // if the parameter exists convert it to an integer, else return the default value
+ floatValue = std::atof(variableParameter);
+ return true;
+}
+
+const char * GetCharEnvironmentVariable( const char * variable )
+{
+ return std::getenv( variable );
+}
+
+} // unnamed namespace
+
+EnvironmentOptions::EnvironmentOptions()
+: mLogFunction( NULL ),
+ mWindowName(),
+ mWindowClassName(),
+ mNetworkControl( 0 ),
+ mFpsFrequency( 0 ),
+ mUpdateStatusFrequency( 0 ),
+ mObjectProfilerInterval( 0 ),
+ mPerformanceStatsLevel( 0 ),
+ mPerformanceStatsFrequency( DEFAULT_STATISTICS_LOG_FREQUENCY ),
+ mPerformanceTimeStampOutput( 0 ),
+ mPanGestureLoggingLevel( 0 ),
+ mWindowWidth( 0u ),
+ mWindowHeight( 0u ),
+ mRenderRefreshRate( 1u ),
+ mMaxTextureSize( 0 ),
+ mRenderToFboInterval( 0u ),
+ mPanGesturePredictionMode( -1 ),
+ mPanGesturePredictionAmount( -1 ), ///< only sets value in pan gesture if greater than 0
+ mPanGestureMaxPredictionAmount( -1 ),
+ mPanGestureMinPredictionAmount( -1 ),
+ mPanGesturePredictionAmountAdjustment( -1 ),
+ mPanGestureSmoothingMode( -1 ),
+ mPanGestureSmoothingAmount( -1.0f ),
+ mPanGestureUseActualTimes( -1 ),
+ mPanGestureInterpolationTimeRange( -1 ),
+ mPanGestureScalarOnlyPredictionEnabled( -1 ),
+ mPanGestureTwoPointPredictionEnabled( -1 ),
+ mPanGestureTwoPointInterpolatePastTime( -1 ),
+ mPanGestureTwoPointVelocityBias( -1.0f ),
+ mPanGestureTwoPointAccelerationBias( -1.0f ),
+ mPanGestureMultitapSmoothingRange( -1 ),
+ mPanMinimumDistance( -1 ),
+ mPanMinimumEvents( -1 ),
+ mGlesCallTime( 0 ),
+ mMultiSamplingLevel( DEFAULT_MULTI_SAMPLING_LEVEL ),
+ mIndicatorVisibleMode( -1 ),
+ mThreadingMode( ThreadingMode::COMBINED_UPDATE_RENDER ),
+ mGlesCallAccumulate( false ),
+ mDepthBufferRequired( DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING ),
+ mStencilBufferRequired( DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING )
+{
+ ParseEnvironmentOptions();
+}
+
+EnvironmentOptions::~EnvironmentOptions()
+{
+}
+
+void EnvironmentOptions::SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction )
+{
+ mLogFunction = logFunction;
+}
+
+void EnvironmentOptions::InstallLogFunction() const
+{
+ Dali::Integration::Log::InstallLogFunction( mLogFunction );
+}
+
+void EnvironmentOptions::UnInstallLogFunction() const
+{
+ Dali::Integration::Log::UninstallLogFunction();
+}
+
+unsigned int EnvironmentOptions::GetNetworkControlMode() const
+{
+ return mNetworkControl;
+}
+unsigned int EnvironmentOptions::GetFrameRateLoggingFrequency() const
+{
+ return mFpsFrequency;
+}
+
+unsigned int EnvironmentOptions::GetUpdateStatusLoggingFrequency() const
+{
+ return mUpdateStatusFrequency;
+}
+
+unsigned int EnvironmentOptions::GetObjectProfilerInterval() const
+{
+ return mObjectProfilerInterval;
+}
+
+unsigned int EnvironmentOptions::GetPerformanceStatsLoggingOptions() const
+{
+ return mPerformanceStatsLevel;
+}
+unsigned int EnvironmentOptions::GetPerformanceStatsLoggingFrequency() const
+{
+ return mPerformanceStatsFrequency;
+}
+unsigned int EnvironmentOptions::GetPerformanceTimeStampOutput() const
+{
+ return mPerformanceTimeStampOutput;
+}
+
+unsigned int EnvironmentOptions::GetPanGestureLoggingLevel() const
+{
+ return mPanGestureLoggingLevel;
+}
+
+int EnvironmentOptions::GetPanGesturePredictionMode() const
+{
+ return mPanGesturePredictionMode;
+}
+
+int EnvironmentOptions::GetPanGesturePredictionAmount() const
+{
+ return mPanGesturePredictionAmount;
+}
+
+int EnvironmentOptions::GetPanGestureMaximumPredictionAmount() const
+{
+ return mPanGestureMaxPredictionAmount;
+}
+
+int EnvironmentOptions::GetPanGestureMinimumPredictionAmount() const
+{
+ return mPanGestureMinPredictionAmount;
+}
+
+int EnvironmentOptions::GetPanGesturePredictionAmountAdjustment() const
+{
+ return mPanGesturePredictionAmountAdjustment;
+}
+
+int EnvironmentOptions::GetPanGestureSmoothingMode() const
+{
+ return mPanGestureSmoothingMode;
+}
+
+float EnvironmentOptions::GetPanGestureSmoothingAmount() const
+{
+ return mPanGestureSmoothingAmount;
+}
+
+int EnvironmentOptions::GetPanGestureUseActualTimes() const
+{
+ return mPanGestureUseActualTimes;
+}
+
+int EnvironmentOptions::GetPanGestureInterpolationTimeRange() const
+{
+ return mPanGestureInterpolationTimeRange;
+}
+
+int EnvironmentOptions::GetPanGestureScalarOnlyPredictionEnabled() const
+{
+ return mPanGestureScalarOnlyPredictionEnabled;
+}
+
+int EnvironmentOptions::GetPanGestureTwoPointPredictionEnabled() const
+{
+ return mPanGestureTwoPointPredictionEnabled;
+}
+
+int EnvironmentOptions::GetPanGestureTwoPointInterpolatePastTime() const
+{
+ return mPanGestureTwoPointInterpolatePastTime;
+}
+
+float EnvironmentOptions::GetPanGestureTwoPointVelocityBias() const
+{
+ return mPanGestureTwoPointVelocityBias;
+}
+
+float EnvironmentOptions::GetPanGestureTwoPointAccelerationBias() const
+{
+ return mPanGestureTwoPointAccelerationBias;
+}
+
+int EnvironmentOptions::GetPanGestureMultitapSmoothingRange() const
+{
+ return mPanGestureMultitapSmoothingRange;
+}
+
+int EnvironmentOptions::GetMinimumPanDistance() const
+{
+ return mPanMinimumDistance;
+}
+
+int EnvironmentOptions::GetMinimumPanEvents() const
+{
+ return mPanMinimumEvents;
+}
+
+unsigned int EnvironmentOptions::GetWindowWidth() const
+{
+ return mWindowWidth;
+}
+
+unsigned int EnvironmentOptions::GetWindowHeight() const
+{
+ return mWindowHeight;
+}
+
+int EnvironmentOptions::GetGlesCallTime() const
+{
+ return mGlesCallTime;
+}
+
+bool EnvironmentOptions::GetGlesCallAccumulate() const
+{
+ return mGlesCallAccumulate;
+}
+
+const std::string& EnvironmentOptions::GetWindowName() const
+{
+ return mWindowName;
+}
+
+const std::string& EnvironmentOptions::GetWindowClassName() const
+{
+ return mWindowClassName;
+}
+
+ThreadingMode::Type EnvironmentOptions::GetThreadingMode() const
+{
+ return mThreadingMode;
+}
+
+unsigned int EnvironmentOptions::GetRenderRefreshRate() const
+{
+ return mRenderRefreshRate;
+}
+
+int EnvironmentOptions::GetMultiSamplingLevel() const
+{
+ return mMultiSamplingLevel;
+}
+
+unsigned int EnvironmentOptions::GetMaxTextureSize() const
+{
+ return mMaxTextureSize;
+}
+
+int EnvironmentOptions::GetIndicatorVisibleMode() const
+{
+ return mIndicatorVisibleMode;
+}
+
+unsigned int EnvironmentOptions::GetRenderToFboInterval() const
+{
+ return mRenderToFboInterval;
+}
+
+bool EnvironmentOptions::PerformanceServerRequired() const
+{
+ return ( ( GetPerformanceStatsLoggingOptions() > 0) ||
+ ( GetPerformanceTimeStampOutput() > 0 ) ||
+ ( GetNetworkControlMode() > 0) );
+}
+
+bool EnvironmentOptions::DepthBufferRequired() const
+{
+ return mDepthBufferRequired;
+}
+
+bool EnvironmentOptions::StencilBufferRequired() const
+{
+ return mStencilBufferRequired;
+}
+
+void EnvironmentOptions::ParseEnvironmentOptions()
+{
+ // get logging options
+ mFpsFrequency = GetIntegerEnvironmentVariable( DALI_ENV_FPS_TRACKING, 0 );
+ mUpdateStatusFrequency = GetIntegerEnvironmentVariable( DALI_ENV_UPDATE_STATUS_INTERVAL, 0 );
+ mObjectProfilerInterval = GetIntegerEnvironmentVariable( DALI_ENV_OBJECT_PROFILER_INTERVAL, 0 );
+ mPerformanceStatsLevel = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS, 0 );
+ mPerformanceStatsFrequency = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS_FREQUENCY, 0 );
+ mPerformanceTimeStampOutput = GetIntegerEnvironmentVariable( DALI_ENV_PERFORMANCE_TIMESTAMP_OUTPUT, 0 );
+ mNetworkControl = GetIntegerEnvironmentVariable( DALI_ENV_NETWORK_CONTROL, 0 );
+ mPanGestureLoggingLevel = GetIntegerEnvironmentVariable( DALI_ENV_LOG_PAN_GESTURE, 0 );
+
+ int predictionMode;
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_MODE, predictionMode) )
+ {
+ mPanGesturePredictionMode = predictionMode;
+ }
+ int predictionAmount(-1);
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_AMOUNT, predictionAmount) )
+ {
+ if( predictionAmount < 0 )
+ {
+ // do not support times in the past
+ predictionAmount = 0;
+ }
+ mPanGesturePredictionAmount = predictionAmount;
+ }
+ int minPredictionAmount(-1);
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MIN_PREDICTION_AMOUNT, minPredictionAmount) )
+ {
+ if( minPredictionAmount < 0 )
+ {
+ // do not support times in the past
+ minPredictionAmount = 0;
+ }
+ mPanGestureMinPredictionAmount = minPredictionAmount;
+ }
+ int maxPredictionAmount(-1);
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MAX_PREDICTION_AMOUNT, maxPredictionAmount) )
+ {
+ if( minPredictionAmount > -1 && maxPredictionAmount < minPredictionAmount )
+ {
+ // maximum amount should not be smaller than minimum amount
+ maxPredictionAmount = minPredictionAmount;
+ }
+ mPanGestureMaxPredictionAmount = maxPredictionAmount;
+ }
+ int predictionAmountAdjustment(-1);
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_PREDICTION_AMOUNT_ADJUSTMENT, predictionAmountAdjustment) )
+ {
+ if( predictionAmountAdjustment < 0 )
+ {
+ // negative amount doesn't make sense
+ predictionAmountAdjustment = 0;
+ }
+ mPanGesturePredictionAmountAdjustment = predictionAmountAdjustment;
+ }
+ int smoothingMode;
+ if( GetIntegerEnvironmentVariable(DALI_ENV_PAN_SMOOTHING_MODE, smoothingMode) )
+ {
+ mPanGestureSmoothingMode = smoothingMode;
+ }
+ float smoothingAmount = 1.0f;
+ if( GetFloatEnvironmentVariable(DALI_ENV_PAN_SMOOTHING_AMOUNT, smoothingAmount) )
+ {
+ smoothingAmount = Clamp(smoothingAmount, 0.0f, 1.0f);
+ mPanGestureSmoothingAmount = smoothingAmount;
+ }
+
+ int useActualTimes( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_USE_ACTUAL_TIMES, useActualTimes ) )
+ {
+ mPanGestureUseActualTimes = useActualTimes == 0 ? 0 : 1;
+ }
+
+ int interpolationTimeRange( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_INTERPOLATION_TIME_RANGE, interpolationTimeRange ) )
+ {
+ if( interpolationTimeRange < 0 )
+ {
+ interpolationTimeRange = 0;
+ }
+ mPanGestureInterpolationTimeRange = interpolationTimeRange;
+ }
+
+ int scalarOnlyPredictionEnabled( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_SCALAR_ONLY_PREDICTION_ENABLED, scalarOnlyPredictionEnabled ) )
+ {
+ mPanGestureScalarOnlyPredictionEnabled = scalarOnlyPredictionEnabled == 0 ? 0 : 1;
+ }
+
+ int twoPointPredictionEnabled( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_PREDICTION_ENABLED, twoPointPredictionEnabled ) )
+ {
+ mPanGestureTwoPointPredictionEnabled = twoPointPredictionEnabled == 0 ? 0 : 1;
+ }
+
+ int twoPointPastInterpolateTime( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_PAST_INTERPOLATE_TIME, twoPointPastInterpolateTime ) )
+ {
+ if( twoPointPastInterpolateTime < 0 )
+ {
+ twoPointPastInterpolateTime = 0;
+ }
+ mPanGestureTwoPointInterpolatePastTime = twoPointPastInterpolateTime;
+ }
+
+ float twoPointVelocityBias = -1.0f;
+ if( GetFloatEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_VELOCITY_BIAS, twoPointVelocityBias ) )
+ {
+ twoPointVelocityBias = Clamp( twoPointVelocityBias, 0.0f, 1.0f );
+ mPanGestureTwoPointVelocityBias = twoPointVelocityBias;
+ }
+
+ float twoPointAccelerationBias = -1.0f;
+ if( GetFloatEnvironmentVariable( DALI_ENV_PAN_TWO_POINT_ACCELERATION_BIAS, twoPointAccelerationBias ) )
+ {
+ twoPointAccelerationBias = Clamp( twoPointAccelerationBias, 0.0f, 1.0f );
+ mPanGestureTwoPointAccelerationBias = twoPointAccelerationBias;
+ }
+
+ int multitapSmoothingRange( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_PAN_MULTITAP_SMOOTHING_RANGE, multitapSmoothingRange ) )
+ {
+ if( multitapSmoothingRange < 0 )
+ {
+ multitapSmoothingRange = 0;
+ }
+ mPanGestureMultitapSmoothingRange = multitapSmoothingRange;
+ }
+
+ int minimumDistance(-1);
+ if ( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MINIMUM_DISTANCE, minimumDistance ))
+ {
+ mPanMinimumDistance = minimumDistance;
+ }
+
+ int minimumEvents(-1);
+ if ( GetIntegerEnvironmentVariable(DALI_ENV_PAN_MINIMUM_EVENTS, minimumEvents ))
+ {
+ mPanMinimumEvents = minimumEvents;
+ }
+
+ int glesCallTime(0);
+ if ( GetIntegerEnvironmentVariable(DALI_GLES_CALL_TIME, glesCallTime ))
+ {
+ mGlesCallTime = glesCallTime;
+ }
+
+ int glesCallAccumulate( 0 );
+ if ( GetIntegerEnvironmentVariable( DALI_GLES_CALL_ACCUMULATE, glesCallAccumulate ) )
+ {
+ mGlesCallAccumulate = glesCallAccumulate != 0;
+ }
+
+ int windowWidth(0), windowHeight(0);
+ if ( GetIntegerEnvironmentVariable( DALI_WINDOW_WIDTH, windowWidth ) && GetIntegerEnvironmentVariable( DALI_WINDOW_HEIGHT, windowHeight ) )
+ {
+ mWindowWidth = windowWidth;
+ mWindowHeight = windowHeight;
+ }
+
+ const char * windowName = GetCharEnvironmentVariable( DALI_WINDOW_NAME );
+ if ( windowName )
+ {
+ mWindowName = windowName;
+ }
+
+ const char * windowClassName = GetCharEnvironmentVariable( DALI_WINDOW_CLASS_NAME );
+ if ( windowClassName )
+ {
+ mWindowClassName = windowClassName;
+ }
+
+ int threadingMode(0);
+ if ( GetIntegerEnvironmentVariable( DALI_THREADING_MODE, threadingMode ) )
+ {
+ switch( threadingMode )
+ {
+ case ThreadingMode::COMBINED_UPDATE_RENDER:
+ {
+ mThreadingMode = static_cast< ThreadingMode::Type >( threadingMode );
+ break;
+ }
+ }
+ }
+
+ int renderRefreshRate(0);
+ if ( GetIntegerEnvironmentVariable( DALI_REFRESH_RATE, renderRefreshRate ) )
+ {
+ // Only change it if it's valid
+ if( renderRefreshRate > 1 )
+ {
+ mRenderRefreshRate = renderRefreshRate;
+ }
+ }
+
+ int multiSamplingLevel( 0 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_MULTI_SAMPLING_LEVEL, multiSamplingLevel ) )
+ {
+ mMultiSamplingLevel = multiSamplingLevel;
+ }
+
+ int maxTextureSize( 0 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_MAX_TEXTURE_SIZE, maxTextureSize ) )
+ {
+ if( maxTextureSize > 0 )
+ {
+ mMaxTextureSize = maxTextureSize;
+ }
+ }
+
+ int indicatorVisibleMode( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_INDICATOR_VISIBLE_MODE, indicatorVisibleMode ) )
+ {
+ if( indicatorVisibleMode > -1 )
+ {
+ mIndicatorVisibleMode = indicatorVisibleMode;
+ }
+ }
+
+ mRenderToFboInterval = GetIntegerEnvironmentVariable( DALI_RENDER_TO_FBO, 0u );
+
+
+ int depthBufferRequired( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_DISABLE_DEPTH_BUFFER, depthBufferRequired ) )
+ {
+ if( depthBufferRequired > 0 )
+ {
+ mDepthBufferRequired = false;
+ mStencilBufferRequired = false; // Disable stencil buffer as well
+ }
+ }
+
+ int stencilBufferRequired( -1 );
+ if( GetIntegerEnvironmentVariable( DALI_ENV_DISABLE_STENCIL_BUFFER, stencilBufferRequired ) )
+ {
+ if( stencilBufferRequired > 0 )
+ {
+ mStencilBufferRequired = false;
+ }
+ }
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+#ifndef DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
+#define DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/threading-mode.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * This class provides the environment options which define settings as well as
+ * the ability to install a log function.
+ *
+ */
+class EnvironmentOptions
+{
+public:
+
+ /**
+ * Constructor
+ */
+ EnvironmentOptions();
+
+ /**
+ * non-virtual destructor, not intended as a base class
+ */
+ ~EnvironmentOptions();
+
+ /**
+ * @param logFunction logging function
+ */
+ void SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction );
+
+ /**
+ * Install the log function for the current thread.
+ */
+ void InstallLogFunction() const;
+
+ /**
+ * Un-install the log function for the current thread.
+ */
+ void UnInstallLogFunction() const;
+
+ /**
+ * @return whether network control is enabled or not ( 0 = off, 1 = on )
+ */
+ unsigned int GetNetworkControlMode() const;
+
+ /**
+ * @return frequency of how often FPS is logged out (e.g. 0 = off, 2 = every 2 seconds).
+ */
+ unsigned int GetFrameRateLoggingFrequency() const;
+
+ /**
+ * @return frequency of how often Update Status is logged out (e.g. 0 = off, 60 = log every 60 frames = 1 second @ 60FPS).
+ */
+ unsigned int GetUpdateStatusLoggingFrequency() const;
+
+ /**
+ * @return object profiler status interval ( 0 == off )
+ */
+ unsigned int GetObjectProfilerInterval() const;
+
+ /**
+ * @return performance statistics log level ( 0 == off )
+ */
+ unsigned int GetPerformanceStatsLoggingOptions() const;
+
+ /**
+ * @return performance statistics log frequency in seconds
+ */
+ unsigned int GetPerformanceStatsLoggingFrequency() const;
+
+ /**
+ * @return performance time stamp output ( 0 == off)
+ */
+ unsigned int GetPerformanceTimeStampOutput() const;
+
+ /**
+ * @return pan-gesture logging level ( 0 == off )
+ */
+ unsigned int GetPanGestureLoggingLevel() const;
+
+ /**
+ * @return pan-gesture prediction mode ( -1 means not set so no prediction, 0 = no prediction )
+ */
+ int GetPanGesturePredictionMode() const;
+
+ /**
+ * @return pan-gesture prediction amount
+ */
+ int GetPanGesturePredictionAmount() const;
+
+ /**
+ * @return maximum pan-gesture prediction amount
+ */
+ int GetPanGestureMaximumPredictionAmount() const;
+
+ /**
+ * @return minimum pan-gesture prediction amount
+ */
+ int GetPanGestureMinimumPredictionAmount() const;
+
+ /**
+ * @brief Gets the prediction amount to adjust when the pan velocity is changed.
+ *
+ * If the pan velocity is accelerating, the prediction amount will be increased
+ * by the specified amount until it reaches the upper bound. If the pan velocity
+ * is decelerating, the prediction amount will be decreased by the specified
+ * amount until it reaches the lower bound.
+ *
+ * @return pan-gesture prediction amount adjustment
+ */
+ int GetPanGesturePredictionAmountAdjustment() const;
+
+ /**
+ * @return pan-gesture smoothing mode ( -1 means not set so no smoothing, 0 = no smoothing )
+ */
+ int GetPanGestureSmoothingMode() const;
+
+ /**
+ * @return pan-gesture smoothing amount
+ */
+ float GetPanGestureSmoothingAmount() const;
+
+ /**
+ * @return pan-gesture use actual times is true if real gesture and frame times are to be used.
+ */
+ int GetPanGestureUseActualTimes() const;
+
+ /**
+ * @return pan-gesture interpolation time range is the time range (ms) of past points to use (with weights) when interpolating.
+ */
+ int GetPanGestureInterpolationTimeRange() const;
+
+ /**
+ * @return pan-gesture scalar only prediction, when enabled, ignores acceleration.
+ */
+ int GetPanGestureScalarOnlyPredictionEnabled() const;
+
+ /**
+ * @return pan-gesture two point prediction combines two interpolated points to get more steady acceleration and velocity values.
+ */
+ int GetPanGestureTwoPointPredictionEnabled() const;
+
+ /**
+ * @return pan-gesture two point interpolate past time is the time delta (ms) in the past to interpolate the second point.
+ */
+ int GetPanGestureTwoPointInterpolatePastTime() const;
+
+ /**
+ * @return pan-gesture two point velocity bias is the ratio of first and second points to use for velocity.
+ * 0.0f = 100% of first point. 1.0f = 100% of second point.
+ */
+ float GetPanGestureTwoPointVelocityBias() const;
+
+ /**
+ * @return pan-gesture two point acceleration bias is the ratio of first and second points to use for acceleration.
+ * 0.0f = 100% of first point. 1.0f = 100% of second point.
+ */
+ float GetPanGestureTwoPointAccelerationBias() const;
+
+ /**
+ * @return pan-gesture multitap smoothing range is the range in time (ms) of points in the history to smooth the final output against.
+ */
+ int GetPanGestureMultitapSmoothingRange() const;
+
+ /**
+ * @return The minimum distance before a pan can be started (-1 means it's not set)
+ */
+ int GetMinimumPanDistance() const;
+
+ /**
+ * @return The minimum events before a pan can be started (-1 means it's not set)
+ */
+ int GetMinimumPanEvents() const;
+
+ /**
+ * @return The width of the window
+ */
+ unsigned int GetWindowWidth() const;
+
+ /**
+ * @return The height of the window
+ */
+ unsigned int GetWindowHeight() const;
+
+ /**
+ * @brief Get the graphics status time
+ */
+ int GetGlesCallTime() const;
+
+ /**
+ * @brief Get whether or not to accumulate gles call statistics
+ */
+ bool GetGlesCallAccumulate() const;
+
+ /**
+ * @return true if performance server is required
+ */
+ bool PerformanceServerRequired() const;
+
+ /**
+ * @return Gets the window name.
+ */
+ const std::string& GetWindowName() const;
+
+ /**
+ * @return Gets the window class.
+ */
+ const std::string& GetWindowClassName() const;
+
+ /**
+ * @return The thread mode that DALi should use.
+ */
+ ThreadingMode::Type GetThreadingMode() const;
+
+ /**
+ * @return The render refresh rate.
+ */
+ unsigned int GetRenderRefreshRate() const;
+
+ /**
+ * @return The number of samples required in multisample buffers
+ */
+ int GetMultiSamplingLevel() const;
+
+ /**
+ * @return The maximum texture size
+ */
+ unsigned int GetMaxTextureSize() const;
+
+ /**
+ * @return The maximum texture size
+ */
+ int GetIndicatorVisibleMode() const;
+
+ /**
+ * @brief Retrieves the interval of frames to be rendered into the Frame Buffer Object and the Frame Buffer.
+ *
+ * @return The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer.
+ */
+ unsigned int GetRenderToFboInterval() const;
+
+ /**
+ * @return Whether the depth buffer is required.
+ */
+ bool DepthBufferRequired() const;
+
+ /**
+ * @return Whether the stencil buffer is required.
+ */
+ bool StencilBufferRequired() const;
+
+ /// Deleted copy constructor.
+ EnvironmentOptions( const EnvironmentOptions& ) = delete;
+
+ /// Deleted move constructor.
+ EnvironmentOptions( const EnvironmentOptions&& ) = delete;
+
+ /// Deleted assignment operator.
+ EnvironmentOptions& operator=( const EnvironmentOptions& ) = delete;
+
+ /// Deleted move assignment operator.
+ EnvironmentOptions& operator=( const EnvironmentOptions&& ) = delete;
+
+private: // Internal
+
+ /**
+ * Parses the environment options.
+ * Called from the constructor
+ */
+ void ParseEnvironmentOptions();
+
+private: // Data
+
+ Dali::Integration::Log::LogFunction mLogFunction;
+
+ std::string mWindowName; ///< name of the window
+ std::string mWindowClassName; ///< name of the class the window belongs to
+ unsigned int mNetworkControl; ///< whether network control is enabled
+ unsigned int mFpsFrequency; ///< how often fps is logged out in seconds
+ unsigned int mUpdateStatusFrequency; ///< how often update status is logged out in frames
+ unsigned int mObjectProfilerInterval; ///< how often object counts are logged out in seconds
+ unsigned int mPerformanceStatsLevel; ///< performance statistics logging bitmask
+ unsigned int mPerformanceStatsFrequency; ///< performance statistics logging frequency (seconds)
+ unsigned int mPerformanceTimeStampOutput; ///< performance time stamp output ( bitmask)
+ unsigned int mPanGestureLoggingLevel; ///< pan-gesture log level
+ unsigned int mWindowWidth; ///< width of the window
+ unsigned int mWindowHeight; ///< height of the window
+ unsigned int mRenderRefreshRate; ///< render refresh rate
+ unsigned int mMaxTextureSize; ///< The maximum texture size that GL can handle
+ unsigned int mRenderToFboInterval; ///< The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer.
+ int mPanGesturePredictionMode; ///< prediction mode for pan gestures
+ int mPanGesturePredictionAmount; ///< prediction amount for pan gestures
+ int mPanGestureMaxPredictionAmount; ///< maximum prediction amount for pan gestures
+ int mPanGestureMinPredictionAmount; ///< minimum prediction amount for pan gestures
+ int mPanGesturePredictionAmountAdjustment; ///< adjustment of prediction amount for pan gestures
+ int mPanGestureSmoothingMode; ///< prediction mode for pan gestures
+ float mPanGestureSmoothingAmount; ///< prediction amount for pan gestures
+ int mPanGestureUseActualTimes; ///< Disable to optionally override actual times if they make results worse.
+ int mPanGestureInterpolationTimeRange; ///< Time into past history (ms) to use points to interpolate the first point.
+ int mPanGestureScalarOnlyPredictionEnabled; ///< If enabled, prediction is done using velocity alone (no integration or acceleration).
+ int mPanGestureTwoPointPredictionEnabled; ///< If enabled, a second interpolated point is predicted and combined with the first to get more stable values.
+ int mPanGestureTwoPointInterpolatePastTime; ///< The target time in the past to generate the second interpolated point.
+ float mPanGestureTwoPointVelocityBias; ///< The ratio of first and second interpolated points to use for velocity. 0.0f = 100% of first point. 1.0f = 100% of second point.
+ float mPanGestureTwoPointAccelerationBias; ///< The ratio of first and second interpolated points to use for acceleration. 0.0f = 100% of first point. 1.0f = 100% of second point.
+ int mPanGestureMultitapSmoothingRange; ///< The range in time (ms) of points in the history to smooth the final output against.
+ int mPanMinimumDistance; ///< minimum distance required before pan starts
+ int mPanMinimumEvents; ///< minimum events required before pan starts
+ int mGlesCallTime; ///< time in seconds between status updates
+ int mMultiSamplingLevel; ///< The number of samples required in multisample buffers
+ int mIndicatorVisibleMode; ///< Indicator visible mode
+ ThreadingMode::Type mThreadingMode; ///< threading mode
+ bool mGlesCallAccumulate; ///< Whether or not to accumulate gles call statistics
+ bool mDepthBufferRequired; ///< Whether the depth buffer is required
+ bool mStencilBufferRequired; ///< Whether the stencil buffer is required
+};
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif // DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/file-descriptor-monitor.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Using Impl to hide away EFL specific members
+ */
+struct FileDescriptorMonitor::Impl
+{
+ // Construction
+ Impl( int fileDescriptor, CallbackBase* callback, int eventsToMonitor)
+ : mFileDescriptor( fileDescriptor ),
+ mEventsToMonitor( eventsToMonitor ),
+ mCallback( callback ),
+ mHandler( NULL )
+ {
+ }
+
+ ~Impl()
+ {
+ delete mCallback;
+ }
+
+ // Data
+ int mFileDescriptor;
+ int mEventsToMonitor; ///< what file descriptor events to monitor
+ CallbackBase* mCallback;
+ Ecore_Fd_Handler* mHandler;
+
+ // Static Methods
+
+ /**
+ * Called when the file descriptor receives an event.
+ */
+ static Eina_Bool EventDispatch(void* data, Ecore_Fd_Handler *handler)
+ {
+ Impl* impl = reinterpret_cast<Impl*>(data);
+
+ // if we want read events, check to see if a read event is available
+ int type = FileDescriptorMonitor::FD_NO_EVENT;
+
+ if( ecore_main_fd_handler_active_get( handler, ECORE_FD_ERROR) )
+ {
+ CallbackBase::Execute( *impl->mCallback, FileDescriptorMonitor::FD_ERROR);
+ DALI_LOG_ERROR("ECORE_FD_ERROR occurred on %d\n", impl->mFileDescriptor);
+
+ return ECORE_CALLBACK_CANCEL;
+ }
+
+ if( impl->mEventsToMonitor & ECORE_FD_READ )
+ {
+ if (ecore_main_fd_handler_active_get( handler, ECORE_FD_READ))
+ {
+ type = FileDescriptorMonitor::FD_READABLE;
+ }
+ }
+ // check if we want write events
+ if( impl->mEventsToMonitor & ECORE_FD_WRITE )
+ {
+ if (ecore_main_fd_handler_active_get( handler, ECORE_FD_WRITE))
+ {
+ type |= FileDescriptorMonitor::FD_WRITABLE;
+ }
+ }
+
+ // if there is an event, execute the callback
+ if( type != FileDescriptorMonitor::FD_NO_EVENT )
+ {
+ CallbackBase::Execute( *impl->mCallback, static_cast< FileDescriptorMonitor::EventType >(type ) );
+ }
+
+ return ECORE_CALLBACK_RENEW;
+ }
+};
+
+FileDescriptorMonitor::FileDescriptorMonitor( int fileDescriptor, CallbackBase* callback, int eventBitmask)
+{
+ mImpl = new Impl(fileDescriptor, callback, eventBitmask);
+
+ if (fileDescriptor < 1)
+ {
+ DALI_ASSERT_ALWAYS( 0 && "Invalid File descriptor");
+ return;
+ }
+
+ int events = 0;
+ if( eventBitmask & FD_READABLE)
+ {
+ events = ECORE_FD_READ;
+ }
+ if( eventBitmask & FD_WRITABLE)
+ {
+ events |= ECORE_FD_WRITE;
+ }
+ mImpl->mEventsToMonitor = events;
+ mImpl->mHandler = ecore_main_fd_handler_add( fileDescriptor, static_cast<Ecore_Fd_Handler_Flags >( events ), &Impl::EventDispatch, mImpl, NULL, NULL );
+
+}
+
+FileDescriptorMonitor::~FileDescriptorMonitor()
+{
+ if (mImpl->mHandler)
+ {
+ ecore_main_fd_handler_del(mImpl->mHandler);
+ }
+
+ delete mImpl;
+ mImpl = NULL;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef DALI_INTERNAL_PORTABLE_FILE_READER_H
+#define DALI_INTERNAL_PORTABLE_FILE_READER_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/file-closer.h>
+
+// EXTERNAL INCLUDES
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Platform
+{
+
+class FileReader : public FileCloser
+{
+public:
+ FileReader( const std::string& filename )
+ : FileCloser( filename.c_str(), "rb" )
+ {
+ }
+
+ FileReader( Dali::Vector<uint8_t>& vector )
+ : FileCloser( &vector[0], vector.Size(), "rb" )
+ {
+ }
+
+ FileReader( Dali::Vector<uint8_t>& vector, size_t dataSize )
+ : FileCloser( &vector[0], dataSize, "rb" )
+ {
+ }
+
+ FileReader( uint8_t* data, size_t dataSize )
+ : FileCloser( data, dataSize, "rb" )
+ {
+ }
+};
+
+} /* namespace Platform */
+} /* namespace Internal */
+} /* namespace Dali */
+
+#endif // DALI_INTERNAL_PORTABLE_FILE_READER_H
--- /dev/null
+#ifndef DALI_INTERNAL_PORTABLE_FILE_WRITER_H
+#define DALI_INTERNAL_PORTABLE_FILE_WRITER_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/file-closer.h>
+
+// EXTERNAL INCLUDES
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Platform
+{
+
+class FileWriter : public FileCloser
+{
+public:
+ /**
+ * Opens a file pointer onto the memory for writing to.
+ * Note, in some implementations, the vector may be resized to be larger than dataSize.
+ * @param[in,out] vector The vector to write to
+ * @param[in] dataSize the amount of data to be written
+ */
+ FileWriter( Dali::Vector<uint8_t>& vector, size_t dataSize )
+ : FileCloser( vector, dataSize, "wb" )
+ {
+ }
+};
+
+} /* namespace Platform */
+} /* namespace Internal */
+} /* namespace Dali */
+
+#endif // DALI_INTERNAL_PORTABLE_FILE_WRITER_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/fps-tracker.h>
+
+// EXTERNAL INCLUDES
+#include <cstdio>
+#include <cmath>
+#include <sys/stat.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const char* DALI_TEMP_UPDATE_FPS_FILE( "/tmp/dalifps.txt" );
+} // unnamed namespace
+
+FpsTracker::FpsTracker( const EnvironmentOptions& environmentOptions )
+: mFpsTrackingSeconds( fabsf( environmentOptions.GetFrameRateLoggingFrequency() ) ),
+ mFrameCount( 0.0f ),
+ mElapsedTime( 0.0f )
+{
+}
+
+FpsTracker::~FpsTracker()
+{
+ if( mFpsTrackingSeconds > 0.f )
+ {
+ OutputFPSRecord();
+ }
+}
+
+void FpsTracker::Track( float secondsFromLastFrame )
+{
+ if( mFpsTrackingSeconds > 0.f )
+ {
+ if ( mElapsedTime < mFpsTrackingSeconds )
+ {
+ mElapsedTime += secondsFromLastFrame;
+ mFrameCount += 1.f;
+ }
+ else
+ {
+ OutputFPSRecord();
+ mFrameCount = 0.f;
+ mElapsedTime = 0.f;
+ }
+ }
+}
+
+bool FpsTracker::Enabled() const
+{
+ return mFpsTrackingSeconds > 0.0f;
+}
+
+void FpsTracker::OutputFPSRecord()
+{
+ float fps = mFrameCount / mElapsedTime;
+ DALI_LOG_FPS("Frame count %.0f, elapsed time %.1fs, FPS: %.2f\n", mFrameCount, mElapsedTime, fps );
+
+ struct stat fileStat;
+
+ // Check file path
+ if( lstat( DALI_TEMP_UPDATE_FPS_FILE, &fileStat ) != 0 )
+ {
+ return;
+ }
+
+ if( !S_ISREG( fileStat.st_mode ) )
+ {
+ return;
+ }
+
+ // Dumps out the frame rate.
+ FILE* outfile = fopen( DALI_TEMP_UPDATE_FPS_FILE, "w" );
+ if( outfile )
+ {
+ char fpsString[10];
+ snprintf(fpsString,sizeof(fpsString),"%.2f \n", fps );
+ fputs( fpsString, outfile ); // ignore the error on purpose
+ fclose( outfile );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/frame-time-stamp.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+FrameTimeStamp::FrameTimeStamp()
+: frame(0),
+ microseconds(0),
+ bufferIndex(0)
+{
+}
+
+FrameTimeStamp::FrameTimeStamp(unsigned int frame,
+ uint64_t microseconds,
+ unsigned int bufferIndex)
+: frame( frame ),
+ microseconds( microseconds ),
+ bufferIndex( bufferIndex )
+{
+}
+
+FrameTimeStamp::FrameTimeStamp( unsigned int bufferIndex )
+: frame( 0 ),
+ microseconds( 0 ),
+ bufferIndex( bufferIndex )
+{
+}
+
+unsigned int FrameTimeStamp::MicrosecondDiff( const FrameTimeStamp& start,const FrameTimeStamp& end )
+{
+ return end.microseconds - start.microseconds;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// STRUCT HEADER
+#include <dali/internal/system/common/frame-time-stats.h>
+
+// EXTERNAL INCLUDES
+#include <cmath>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const float EPSILON = 0.9f; // rolling average = (average * epsilon) + (current * epsilon)
+const float ONE_OVER_MICROSECONDS_TO_SECONDS = 1.f / 1000000.f; ///< microseconds per second
+}
+
+FrameTimeStats::FrameTimeStats()
+: mTotal( 0.f)
+{
+ mSamples.Reserve( 16 ); // Fill out a little to avoid early reallocations
+
+ Reset();
+}
+
+FrameTimeStats::~FrameTimeStats()
+{
+}
+
+void FrameTimeStats::StartTime( const FrameTimeStamp& timeStamp )
+{
+ // check to make sure we don't get 2 start times in a row
+ if( mTimeState != WAITING_FOR_START_TIME )
+ {
+ Reset();
+ }
+
+ mStart = timeStamp;
+ mTimeState = WAITING_FOR_END_TIME;
+}
+
+void FrameTimeStats::EndTime( const FrameTimeStamp& timeStamp )
+{
+ if( mTimeState != WAITING_FOR_END_TIME )
+ {
+ Reset();
+ return;
+ }
+
+ mTimeState = WAITING_FOR_START_TIME;
+ mRunCount++;
+
+ // frame time in seconds
+ unsigned int elapsedTime = FrameTimeStamp::MicrosecondDiff( mStart, timeStamp);
+
+ mSamples.PushBack( elapsedTime );
+
+ // if the min and max times haven't been set, do that now.
+ if( !mMinMaxTimeSet )
+ {
+ mMin = elapsedTime;
+ mMax = elapsedTime;
+ mMinMaxTimeSet = true;
+ }
+ else
+ {
+ if (elapsedTime < mMin)
+ {
+ mMin= elapsedTime;
+ }
+ else if (elapsedTime > mMax)
+ {
+ mMax = elapsedTime;
+ }
+ }
+
+ mTotal += elapsedTime;
+}
+
+void FrameTimeStats::Reset()
+{
+ mTimeState = WAITING_FOR_START_TIME;
+ mMinMaxTimeSet = false;
+ mMin = 0.f;
+ mMax = 0.f;
+ mRunCount = 0;
+ mSamples.Clear();
+}
+
+float FrameTimeStats::GetMaxTime() const
+{
+ return mMax * ONE_OVER_MICROSECONDS_TO_SECONDS;
+}
+
+float FrameTimeStats::GetMinTime() const
+{
+ return mMin * ONE_OVER_MICROSECONDS_TO_SECONDS;
+}
+
+float FrameTimeStats::GetTotalTime() const
+{
+ return mTotal * ONE_OVER_MICROSECONDS_TO_SECONDS;
+}
+
+unsigned int FrameTimeStats::GetRunCount() const
+{
+ return mRunCount;
+}
+
+void FrameTimeStats::CalculateMean( float& meanOut, float& standardDeviationOut ) const
+{
+ if( mSamples.Size() > 0 )
+ {
+ // Mean
+ unsigned int sum = 0;
+ for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it )
+ {
+ unsigned int value = *it;
+
+ sum += value;
+ }
+
+ meanOut = static_cast<float>(sum) / mSamples.Size();
+
+ // Variance
+ float variance = 0.0f;
+ for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it )
+ {
+ unsigned int value = *it;
+
+ float difference = static_cast<float>(value) - meanOut;
+
+ variance += difference * difference;
+ }
+
+ variance /= mSamples.Size();
+
+ // Standard deviation
+ standardDeviationOut = sqrtf( variance );
+
+ meanOut *= ONE_OVER_MICROSECONDS_TO_SECONDS;
+ standardDeviationOut *= ONE_OVER_MICROSECONDS_TO_SECONDS;
+ }
+ else
+ {
+ meanOut = 0.0f;
+ standardDeviationOut = 0.0f;
+ }
+}
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
+#define __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/frame-time-stamp.h>
+#include <dali/public-api/common/dali-vector.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Used to get statistics about time stamps over a period of time.
+ * E.g. the min, max, total and average time spent inside two markers,
+ * such as UPDATE_START and UPDATE_END
+ */
+struct FrameTimeStats
+{
+ /**
+ * Constructor
+ */
+ FrameTimeStats();
+
+ /**
+ * Destructor, not intended as a base class
+ */
+ ~FrameTimeStats();
+
+ /**
+ * Timer start time
+ * @param timeStamp time stamp
+ */
+ void StartTime( const FrameTimeStamp& timeStamp );
+
+ /**
+ * Timer end time
+ * @param timeStamp time stamp
+ */
+ void EndTime( const FrameTimeStamp& timeStamp );
+
+ /**
+ * Reset all internal counters / state except total time.
+ */
+ void Reset();
+
+ /**
+ * @return maximum time in seconds
+ */
+ float GetMaxTime() const;
+
+ /**
+ * @return minimum time in seconds
+ */
+ float GetMinTime() const;
+
+ /**
+ * @return total time in second
+ */
+ float GetTotalTime() const;
+
+ /**
+ * Get how many times the timer has been started /stopped
+ */
+ unsigned int GetRunCount() const;
+
+ /**
+ * Calculate the mean and standard deviation
+ *
+ * @param[out] mean The return mean value
+ * @param[out] standardDeviation The return standard deviation value
+ */
+ void CalculateMean( float& meanOut, float& standardDeviationOut ) const;
+
+private:
+
+ /**
+ * internal time state.
+ */
+ enum TimeState
+ {
+ WAITING_FOR_START_TIME, ///< waiting for start time marker
+ WAITING_FOR_END_TIME ///< waiting for end time marker
+ };
+
+ typedef Dali::Vector< unsigned int > Samples;
+ Samples mSamples;
+
+ unsigned int mMin; ///< current minimum value in microseconds
+ unsigned int mMax; ///< current maximum value in microseconds
+ unsigned int mTotal; ///< current total in in microseconds
+ unsigned int mRunCount; ///< how many times the timer has been start / stopped
+ FrameTimeStamp mStart; ///< start time stamp, to calculate the diff
+ TimeState mTimeState:1; ///< time state
+ bool mMinMaxTimeSet:1; ///< whether the min-max values have been configured
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H__
+
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/kernel-trace.h>
+
+// EXTERNAL HEADERS
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+
+// INTERNAL HEADERS
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const char* TRACE_MARKER_FILE = "/sys/kernel/debug/tracing/trace_marker";
+const char* SPI_PREFIX = "SPI_EV_DALI_"; ///< prefix to let the SPI tool know it should read the trace
+}// un-named name space
+
+KernelTrace::KernelTrace()
+: mFileDescriptor( 0 ),
+ mLoggedError( false )
+{
+}
+
+KernelTrace::~KernelTrace()
+{
+ if( mFileDescriptor )
+ {
+ close( mFileDescriptor );
+ }
+}
+
+// If this function doesn't appear to work, you can test manually on the device.
+// $ cd /sys/kernel/debug/tracing
+//
+// If the folder doesn't exist then the kernel needs to be re-built with ftrace enabled
+// If it does exist, then you can continue to test ftrace is working:
+//
+// $ echo 1 > tracing_enabled
+// $ echo "test" > trace_marker
+// $ cat trace
+// should print out test message
+// If the message did not get added to the trace, then check you have write permissions to the trace_marker file.
+//
+//
+void KernelTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage )
+{
+ // Open the trace_marker file
+ if( mFileDescriptor == 0 )
+ {
+ mFileDescriptor = open( TRACE_MARKER_FILE , O_WRONLY);
+ if( mFileDescriptor == -1 )
+ {
+ // we want to keep trying to open it, so it will start working if someone fixes
+ // the permissions on the trace marker
+ mFileDescriptor = 0;
+
+ // first time we fail to open the file, log an error
+ if( !mLoggedError )
+ {
+ mLoggedError = true;
+ DALI_LOG_ERROR("Failed to open /sys/kernel/debug/tracing/trace_marker for writing please check file permissions.\n");
+ }
+
+ }
+ }
+
+ if( mFileDescriptor > 0 )
+ {
+ std::string msg( SPI_PREFIX );
+ msg+=traceMessage;
+
+ int ret = write( mFileDescriptor, msg.c_str(), msg.length() );
+ // if it failed then close the file description and try again next time we trace
+ if( ret < 0 )
+ {
+ close( mFileDescriptor );
+ mFileDescriptor = 0;
+ }
+ }
+}
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
+#define __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/network/common/trace-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Concrete Kernel Tracing Interface.
+ * Used to log trace messages to the kernel using ftrace.
+ *
+ */
+class KernelTrace : public TraceInterface
+{
+public:
+
+ /**
+ * Constructor
+ */
+ KernelTrace();
+
+ /**
+ * Destructor
+ */
+ virtual ~KernelTrace();
+
+ /**
+ * @copydoc KernelTracerInterface::KernelTrace()
+ */
+ virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage );
+
+private:
+
+ int mFileDescriptor;
+ bool mLoggedError:1;
+
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/locale-utils.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace Locale
+{
+
+namespace
+{
+
+struct LocaleDirectionInfo
+{
+ const char * locale;
+ const char * name;
+ Locale::Direction direction;
+};
+
+const LocaleDirectionInfo LOCALE_DIRECTION_LOOKUP_TABLE[] =
+{
+ { "af", "Afrikaans", Locale::LeftToRight },
+ { "am", "Amharic", Locale::LeftToRight },
+ { "ar", "Arabic", Locale::RightToLeft },
+ { "as", "Assamese", Locale::LeftToRight },
+ { "az", "Azerbaijani", Locale::RightToLeft },
+ { "be", "Belarusian", Locale::LeftToRight },
+ { "bg", "Bulgarian", Locale::LeftToRight },
+ { "bn", "Bengali", Locale::LeftToRight },
+ { "bo", "Tibetan", Locale::LeftToRight },
+ { "bs", "Bosnian", Locale::LeftToRight },
+ { "ca", "Catalan", Locale::LeftToRight },
+ { "cs", "Czech", Locale::LeftToRight },
+ { "cy", "Welsh", Locale::LeftToRight },
+ { "da", "Danish", Locale::LeftToRight },
+ { "de", "German", Locale::LeftToRight },
+ { "dv", "Divehi", Locale::RightToLeft },
+ { "el", "Greek", Locale::LeftToRight },
+ { "en", "English", Locale::LeftToRight },
+ { "es", "Spanish", Locale::LeftToRight },
+ { "et", "Estonian", Locale::LeftToRight },
+ { "eu", "Basque", Locale::LeftToRight },
+ { "fa", "Farsi", Locale::RightToLeft },
+ { "fi", "Finnish", Locale::LeftToRight },
+ { "fo", "Faroese", Locale::LeftToRight },
+ { "fr", "French", Locale::LeftToRight },
+ { "gd", "Gaelic", Locale::LeftToRight },
+ { "gl", "Galician", Locale::LeftToRight },
+ { "gn", "Guarani", Locale::LeftToRight },
+ { "gu", "Gujarati", Locale::LeftToRight },
+ { "he", "Hebrew", Locale::RightToLeft },
+ { "hi", "Hindi", Locale::LeftToRight },
+ { "hr", "Croatian", Locale::LeftToRight },
+ { "hu", "Hungarian", Locale::LeftToRight },
+ { "hy", "Armenian", Locale::LeftToRight },
+ { "id", "Indonesian", Locale::LeftToRight },
+ { "is", "Icelandic", Locale::LeftToRight },
+ { "it", "Italian", Locale::LeftToRight },
+ { "ja", "Japanese", Locale::LeftToRight },
+ { "ka", "Georgian", Locale::LeftToRight },
+ { "kk", "Kazakh", Locale::RightToLeft },
+ { "km", "Khmer", Locale::LeftToRight },
+ { "kn", "Kannada", Locale::LeftToRight },
+ { "ko", "Korean", Locale::LeftToRight },
+ { "ks", "Kashmiri", Locale::RightToLeft },
+ { "la", "Latin", Locale::LeftToRight },
+ { "lo", "Lao", Locale::LeftToRight },
+ { "lt", "Lithuanian", Locale::LeftToRight },
+ { "lv", "Latvian", Locale::LeftToRight },
+ { "mi", "Maori", Locale::LeftToRight },
+ { "mk", "FYRO Macedonia", Locale::LeftToRight },
+ { "ml", "Malayalam", Locale::LeftToRight },
+ { "mn", "Mongolian", Locale::LeftToRight },
+ { "mr", "Marathi", Locale::LeftToRight },
+ { "ms", "Malay", Locale::LeftToRight },
+ { "mt", "Maltese", Locale::LeftToRight },
+ { "my", "Burmese", Locale::LeftToRight },
+ { "nb", "Norwegian: Bokml", Locale::LeftToRight },
+ { "ne", "Nepali", Locale::LeftToRight },
+ { "nl", "Dutch", Locale::LeftToRight },
+ { "nn", "Norwegian: Nynorsk", Locale::LeftToRight },
+ { "or", "Oriya", Locale::LeftToRight },
+ { "pa", "Punjabi", Locale::LeftToRight },
+ { "pl", "Polish", Locale::LeftToRight },
+ { "pt", "Portuguese", Locale::LeftToRight },
+ { "rm", "Raeto-Romance", Locale::LeftToRight },
+ { "ro", "Romanian", Locale::LeftToRight },
+ { "ru", "Russian", Locale::LeftToRight },
+ { "sa", "Sanskrit", Locale::LeftToRight },
+ { "sb", "Sorbian", Locale::LeftToRight },
+ { "sd", "Sindhi", Locale::LeftToRight },
+ { "si", "Sinhala", Locale::LeftToRight },
+ { "sk", "Slovak", Locale::LeftToRight },
+ { "sl", "Slovenian", Locale::LeftToRight },
+ { "so", "Somali", Locale::LeftToRight },
+ { "sq", "Albanian", Locale::LeftToRight },
+ { "sr", "Serbian", Locale::LeftToRight },
+ { "sv", "Swedish", Locale::LeftToRight },
+ { "sw", "Swahili", Locale::LeftToRight },
+ { "ta", "Tamil", Locale::LeftToRight },
+ { "te", "Telugu", Locale::LeftToRight },
+ { "tg", "Tajik", Locale::RightToLeft },
+ { "th", "Thai", Locale::LeftToRight },
+ { "tk", "Turkmen", Locale::LeftToRight },
+ { "tn", "Setsuana", Locale::LeftToRight },
+ { "tr", "Turkish", Locale::LeftToRight },
+ { "ts", "Tsonga", Locale::LeftToRight },
+ { "tt", "Tatar", Locale::LeftToRight },
+ { "uk", "Ukrainian", Locale::LeftToRight },
+ { "ur", "Urdu", Locale::RightToLeft },
+ { "uz", "Uzbek", Locale::LeftToRight },
+ { "vi", "Vietnamese", Locale::LeftToRight },
+ { "xh", "Xhosa", Locale::LeftToRight },
+ { "yi", "Yiddish", Locale::RightToLeft },
+ { "zh", "Chinese", Locale::LeftToRight },
+ { "zu", "Zulu", Locale::LeftToRight },
+
+ { NULL, NULL, Locale::LeftToRight }
+};
+
+} // unnamed namespace
+
+Locale::Direction GetDirection( const std::string& locale )
+{
+ Locale::Direction direction( Locale::LeftToRight );
+
+ if ( !locale.empty() && locale.size() > 2 )
+ {
+ for ( const LocaleDirectionInfo* iter = &LOCALE_DIRECTION_LOOKUP_TABLE[0]; iter->locale; ++iter )
+ {
+ if ( !locale.compare( 0, 2, iter->locale ) )
+ {
+ direction = iter->direction;
+ break;
+ }
+ }
+ }
+
+ return direction;
+}
+
+} // namespace Locale
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// FUNCTION HEADER
+#include <dali/internal/system/common/logging.h>
+
+// EXTERNAL INCLUDES
+#ifndef DALI_PROFILE_UBUNTU
+// Dlog uses C style casts internally
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <dlog.h>
+#else // DALI_PROFILE_UBUNTU
+#include <cstdio>
+#endif
+
+namespace Dali
+{
+
+namespace TizenPlatform
+{
+
+void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message)
+{
+ const char* DALI_TAG = "DALI";
+
+#ifndef DALI_PROFILE_UBUNTU
+ switch(level)
+ {
+ case Dali::Integration::Log::DebugInfo:
+ LOG(LOG_INFO, DALI_TAG, "%s", message.c_str());
+ break;
+ case Dali::Integration::Log::DebugWarning:
+ LOG(LOG_WARN, DALI_TAG, "%s", message.c_str());
+ break;
+ case Dali::Integration::Log::DebugError:
+ LOG(LOG_ERROR, DALI_TAG, "%s", message.c_str());
+ break;
+ default:
+ LOG(LOG_DEFAULT, DALI_TAG, "%s", message.c_str());
+ break;
+ }
+#pragma GCC diagnostic pop
+#else // DALI_PROFILE_UBUNTU
+ const char *format = NULL;
+ switch(level)
+ {
+ case Dali::Integration::Log::DebugInfo:
+ format = "\e[1;34mINFO:\e[21m %s: %s\e[0m";
+ break;
+ case Dali::Integration::Log::DebugWarning:
+ format = "\e[1;33mWARN:\e[21m %s: %s\e[0m";
+ break;
+ case Dali::Integration::Log::DebugError:
+ format = "\e[1;91mERROR:\e[21m %s: %s\e[0m";
+ break;
+ default:
+ format = ":\e[21m %s: %s\e[0m";
+ break;
+ }
+ printf(format, DALI_TAG, message.c_str());
+#endif // DALI_PROFILE_UBUNTU
+}
+
+} // namespace TizenPlatform
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/object-profiler.h>
+
+// EXTERNAL INCLUDES
+#include <stdlib.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/profiling.h>
+#include <dali/public-api/common/stage.h>
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/object/type-registry.h>
+
+using std::string;
+using namespace Dali::Integration::Profiling;
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+ObjectProfiler::ObjectProfiler( unsigned int timeInterval )
+{
+ // This class must be created after the Stage; this means it doesn't count the initial objects
+ // that are created by the stage (base layer, default camera actor)
+ mObjectRegistry = Dali::Stage::GetCurrent().GetObjectRegistry();
+
+ mTimer = Dali::Timer::New( timeInterval * 1000 );
+ mTimer.TickSignal().Connect( this, &ObjectProfiler::OnTimeout );
+ mTimer.Start();
+
+ mObjectRegistry.ObjectCreatedSignal().Connect( this, &ObjectProfiler::OnObjectCreated );
+ mObjectRegistry.ObjectDestroyedSignal().Connect( this, &ObjectProfiler::OnObjectDestroyed );
+}
+
+ObjectProfiler::~ObjectProfiler()
+{
+}
+
+void ObjectProfiler::DisplayInstanceCounts()
+{
+ for( auto&& element : mInstanceCountContainer )
+ {
+ int memorySize = GetMemorySize( element.first, element.second );
+ if( memorySize > 0 )
+ {
+ LogMessage( Debug::DebugInfo, "%-30s: % 4d Memory MemorySize: ~% 6.1f kB\n",
+ element.first.c_str(), element.second, memorySize / 1024.0f );
+ }
+ else
+ {
+ LogMessage( Debug::DebugInfo, "%-30s: % 4d\n",
+ element.first.c_str(), element.second );
+ }
+ }
+ LogMessage(Debug::DebugInfo, "\n");
+}
+
+bool ObjectProfiler::OnTimeout()
+{
+ DisplayInstanceCounts();
+ return true;
+}
+
+void ObjectProfiler::OnObjectCreated(BaseHandle handle)
+{
+ string theType = handle.GetTypeName();
+ if( theType.empty() )
+ {
+ DALI_LOG_ERROR("Object created from an unregistered type\n");
+ theType = "<Unregistered>";
+ }
+
+ mInstanceTypes.push_back(InstanceTypePair(&handle.GetBaseObject(), theType));
+
+ bool found = false;
+ for( auto&& element : mInstanceCountContainer )
+ {
+ if( element.first == theType )
+ {
+ element.second++;
+ found = true;
+ }
+ }
+ if( !found )
+ {
+ InstanceCountPair instanceCount( theType, 1 );
+ mInstanceCountContainer.emplace_back( instanceCount );
+ }
+}
+
+void ObjectProfiler::OnObjectDestroyed(const Dali::RefObject* object)
+{
+ const BaseObject* baseObject = static_cast<const BaseObject*>(object);
+
+ const auto end = mInstanceTypes.end();
+ for( auto iter = mInstanceTypes.begin(); iter != end; ++iter )
+ {
+ if( iter->first == baseObject )
+ {
+ const auto& theType = iter->second;
+ if( !theType.empty() )
+ {
+ auto&& countIter = std::find_if( mInstanceCountContainer.begin(),
+ mInstanceCountContainer.end(),
+ [theType] ( const InstanceCountPair& instance )
+ { return instance.first == theType; } );
+ if( countIter != mInstanceCountContainer.end() )
+ {
+ (*countIter).second--;
+ }
+ }
+ mInstanceTypes.erase( iter );
+ return;
+ }
+ }
+}
+
+int ObjectProfiler::GetMemorySize(const std::string& name, int count)
+{
+ struct MemoryMemorySize
+ {
+ std::string name;
+ int memorySize;
+ };
+ MemoryMemorySize memoryMemorySizes[] =
+ {
+ { "Animation", ANIMATION_MEMORY_SIZE },
+ { "Constraint", CONSTRAINT_MEMORY_SIZE },
+ { "Actor", ACTOR_MEMORY_SIZE },
+ { "Layer", LAYER_MEMORY_SIZE },
+ { "CameraActor", CAMERA_ACTOR_MEMORY_SIZE },
+ { "Image", IMAGE_MEMORY_SIZE },
+ { "Renderer", RENDERER_MEMORY_SIZE },
+ { "Geometry", GEOMETRY_MEMORY_SIZE },
+ { "PropertyBuffer", PROPERTY_BUFFER_MEMORY_SIZE },
+ { "TextureSet", TEXTURE_SET_MEMORY_SIZE },
+ { "Sampler", SAMPLER_MEMORY_SIZE },
+ { "Shader", SHADER_MEMORY_SIZE },
+ };
+
+ for( size_t i=0; i<sizeof(memoryMemorySizes)/sizeof(MemoryMemorySize); i++ )
+ {
+ if( memoryMemorySizes[i].name.compare(name) == 0 )
+ {
+ return count * memoryMemorySizes[i].memorySize;
+ }
+ }
+ return 0;
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+#ifndef __DALI_ADAPTOR_OBJECT_PROFILER_H__
+#define __DALI_ADAPTOR_OBJECT_PROFILER_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/object/object-registry.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/signals/connection-tracker.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/timer.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+/**
+ * Class to profile the number of instances of Objects in the system
+ */
+class ObjectProfiler : public ConnectionTracker
+{
+public:
+
+ /**
+ * Constructor
+ * @param timeInterval to specify the frequency of reporting
+ */
+ ObjectProfiler( unsigned int timeInterval );
+
+ /**
+ * Destructor
+ */
+ ~ObjectProfiler();
+
+ /**
+ * Display a list of types with the current number of instances in the system
+ */
+ void DisplayInstanceCounts();
+
+private:
+ /**
+ * If timer is running, display the instance counts
+ */
+ bool OnTimeout();
+
+ /**
+ * Callback used when objects are created. Increases instance count for that object type
+ * @param[in] handle of the created object
+ */
+ void OnObjectCreated(BaseHandle handle);
+
+ /**
+ * Callback used when objects are created. Decreases instance count for that object type
+ * @param[in] object The object being destroyed
+ */
+ void OnObjectDestroyed(const Dali::RefObject* object);
+
+ /**
+ * Get the memory size of the given object
+ */
+ int GetMemorySize(const std::string& name, int count);
+
+private:
+
+ using InstanceCountPair = std::pair< const std::string, int >;
+ using InstanceTypePair = std::pair< BaseObject*, std::string >;
+
+ Dali::ObjectRegistry mObjectRegistry;
+ Dali::Timer mTimer;
+ std::vector< InstanceCountPair > mInstanceCountContainer;
+ std::vector< InstanceTypePair > mInstanceTypes;
+};
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif // __DALI_ADAPTOR_OBJECT_PROFILER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/performance-interface-factory.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-server.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+PerformanceInterface* PerformanceInterfaceFactory::CreateInterface(
+ AdaptorInternalServices& adaptorServices,
+ const EnvironmentOptions& environmentOptions )
+{
+ return new PerformanceServer( adaptorServices, environmentOptions );
+}
+
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
+#define __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+#include <dali/internal/system/common/environment-options.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Performance interface factory class
+ *
+ */
+class PerformanceInterfaceFactory
+{
+public:
+
+ /**
+ * Create a new concrete implementation of the performance interface.
+ * @param adaptorServices adaptor internal services
+ * @param environmentOptions environment options
+ * @return pointer to a new performance interface
+ */
+ static PerformanceInterface* CreateInterface( AdaptorInternalServices& adaptorServices,
+ const EnvironmentOptions& environmentOptions );
+
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/performance-logger-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+PerformanceInterface* GetPerformanceInterface()
+{
+ if( Adaptor::IsAvailable() )
+ {
+ return Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetPerformanceInterface();
+ }
+
+ return NULL;
+}
+
+} // Anonymous namespace
+
+PerformanceLoggerPtr PerformanceLogger::New( const char* name )
+{
+ PerformanceLoggerPtr logger = new PerformanceLogger( name );
+ return logger;
+}
+
+PerformanceLogger::PerformanceLogger( const char* name )
+: mContext( 0 )
+{
+ PerformanceInterface* performance = GetPerformanceInterface();
+ if( performance )
+ {
+ mContext = performance->AddContext( name );
+ }
+}
+
+PerformanceLogger::~PerformanceLogger()
+{
+ PerformanceInterface* performance = GetPerformanceInterface();
+ if( performance )
+ {
+ performance->RemoveContext( mContext );
+ }
+}
+
+void PerformanceLogger::AddMarker( Dali::PerformanceLogger::Marker markerType )
+{
+ PerformanceInterface* performance = GetPerformanceInterface();
+ if( performance )
+ {
+ PerformanceInterface::MarkerType newMarkerType = PerformanceInterface::START;
+ switch( markerType )
+ {
+ case Dali::PerformanceLogger::START_EVENT:
+ {
+ newMarkerType = PerformanceInterface::START;
+ break;
+ }
+ case Dali::PerformanceLogger::END_EVENT:
+ {
+ newMarkerType = PerformanceInterface::END;
+ break;
+ }
+ }
+
+ performance->AddMarker( newMarkerType, mContext );
+ }
+}
+
+void PerformanceLogger::SetLoggingFrequency( unsigned int logFrequency)
+{
+ PerformanceInterface* performance = GetPerformanceInterface();
+ if( performance )
+ {
+ performance->SetLoggingFrequency( logFrequency, mContext );
+ }
+}
+
+void PerformanceLogger::EnableLogging( bool enable )
+{
+ PerformanceInterface* performance = GetPerformanceInterface();
+ if( performance )
+ {
+ performance->EnableLogging( enable, mContext );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
+#define __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-interface.h>
+#include <dali/devel-api/adaptor-framework/performance-logger.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class PerformanceLogger;
+
+typedef IntrusivePtr<PerformanceLogger> PerformanceLoggerPtr;
+
+/**
+ * @brief Interface for the performance logger
+ */
+class PerformanceLogger : public BaseObject
+{
+public:
+
+ /**
+ * @brief Create a new logger
+ *
+ * @param[in] name The name of the logger. This needs to be a compile-time literal and alive for the whole lifetime of the performance logger.
+ * @return a new logger
+ */
+ static PerformanceLoggerPtr New( const char* name );
+
+ /**
+ * Constructor
+ * @param[in] name The name to assing to the logger
+ */
+ PerformanceLogger( const char* name );
+
+ /**
+ * Destructor.
+ */
+ virtual ~PerformanceLogger();
+
+ /**
+ * Add a performance marker
+ *
+ * @param markerType Performance marker type
+ */
+ void AddMarker( Dali::PerformanceLogger::Marker markerType );
+
+ /**
+ * Set the logging frequency
+ *
+ * @param logFrequency how often to log out in seconds
+ */
+ void SetLoggingFrequency( unsigned int logFrequency);
+
+ /**
+ * Set logging on or off for this logger
+ *
+ * @param[in] enable Enable logging or not
+ */
+ void EnableLogging( bool enable );
+
+private: // Implementation
+
+ // not implemented
+ PerformanceLogger( const PerformanceLogger& );
+ PerformanceLogger& operator=( const PerformanceLogger& );
+
+private:
+
+ PerformanceInterface::ContextId mContext; ///< Context of this logger
+
+};
+
+// Helpers for public-api forwarding methods
+
+inline static Internal::Adaptor::PerformanceLogger& GetImplementation( Dali::PerformanceLogger& logger )
+{
+ DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" );
+
+ BaseObject& handle = logger.GetBaseObject();
+
+ return static_cast< Internal::Adaptor::PerformanceLogger& >( handle );
+}
+
+inline static const Internal::Adaptor::PerformanceLogger& GetImplementation( const Dali::PerformanceLogger& logger )
+{
+ DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" );
+
+ const BaseObject& handle = logger.GetBaseObject();
+
+ return static_cast< const Internal::Adaptor::PerformanceLogger& >( handle );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_PERFORMANCE_LOGGER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/performance-marker.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+
+struct NamePair
+{
+ PerformanceInterface::MarkerType type;
+ const char* const name;
+ PerformanceMarker::MarkerFilter group;
+ PerformanceMarker::MarkerEventType eventType;
+};
+
+const NamePair MARKER_LOOKUP[] =
+{
+ // timed event names must be postfixed with with _START and _END
+ // this is to allow tracers to extract the event name by removing the _START, _END strings
+ //
+ { PerformanceInterface::VSYNC , "V_SYNC" , PerformanceMarker::V_SYNC_EVENTS, PerformanceMarker::SINGLE_EVENT },
+ { PerformanceInterface::UPDATE_START , "UPDATE_START" , PerformanceMarker::UPDATE, PerformanceMarker::START_TIMED_EVENT },
+ { PerformanceInterface::UPDATE_END , "UPDATE_END" , PerformanceMarker::UPDATE, PerformanceMarker::END_TIMED_EVENT },
+ { PerformanceInterface::RENDER_START , "RENDER_START" , PerformanceMarker::RENDER, PerformanceMarker::START_TIMED_EVENT },
+ { PerformanceInterface::RENDER_END , "RENDER_END" , PerformanceMarker::RENDER, PerformanceMarker::END_TIMED_EVENT },
+ { PerformanceInterface::SWAP_START , "SWAP_START" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::START_TIMED_EVENT },
+ { PerformanceInterface::SWAP_END , "SWAP_END" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::END_TIMED_EVENT },
+ { PerformanceInterface::PROCESS_EVENTS_START, "PROCESS_EVENT_START" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::START_TIMED_EVENT },
+ { PerformanceInterface::PROCESS_EVENTS_END, "PROCESS_EVENT_END" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::END_TIMED_EVENT },
+ { PerformanceInterface::PAUSED , "PAUSED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT },
+ { PerformanceInterface::RESUME , "RESUMED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT },
+ { PerformanceInterface::START , "START" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::START_TIMED_EVENT },
+ { PerformanceInterface::END , "END" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::END_TIMED_EVENT }
+};
+} // un-named namespace
+
+
+
+PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type )
+:mType(type)
+{
+}
+
+PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp frameInfo )
+:mType(type),
+ mTimeStamp(frameInfo)
+{
+}
+
+const char* PerformanceMarker::GetName( ) const
+{
+ return MARKER_LOOKUP[ mType ].name;
+}
+
+PerformanceMarker::MarkerEventType PerformanceMarker::GetEventType() const
+{
+ return MARKER_LOOKUP[ mType ].eventType;
+}
+
+PerformanceMarker::MarkerFilter PerformanceMarker::GetFilterType() const
+{
+ return MARKER_LOOKUP[ mType ].group;
+}
+
+unsigned int PerformanceMarker::MicrosecondDiff( const PerformanceMarker& start,const PerformanceMarker& end )
+{
+ return FrameTimeStamp::MicrosecondDiff( start.mTimeStamp, end.mTimeStamp );
+}
+
+bool PerformanceMarker::IsFilterEnabled( MarkerFilter filter ) const
+{
+ return (filter & MARKER_LOOKUP[ mType ].group);
+}
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
+#define __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-interface.h>
+#include <dali/internal/system/common/frame-time-stamp.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Marker used to record an event with a time stamp in Dali
+ */
+class PerformanceMarker
+{
+public:
+
+
+ /**
+ * Bitmask used to filter different types of markers based
+ * on what group they belong to.
+ */
+ enum MarkerFilter
+ {
+ FILTERING_DISABLED = 0, ///< disabled
+ V_SYNC_EVENTS = 1 << 0, ///< v-sync
+ UPDATE = 1 << 1, ///< update start / end
+ RENDER = 1 << 2, ///< render start / end
+ EVENT_PROCESS = 1 << 3, ///< process events start / end
+ SWAP_BUFFERS = 1 << 4, ///< swap buffers start / end
+ LIFE_CYCLE_EVENTS = 1 << 5, ///< pause / resume
+ RESOURCE_EVENTS = 1 << 6, ///< resource events
+ CUSTOM_EVENTS = 1 << 7
+ };
+
+ /**
+ * Marker event type
+ */
+ enum MarkerEventType
+ {
+ SINGLE_EVENT, ///< event is something that has no duration associated with it
+ START_TIMED_EVENT, ///< start of a timed event
+ END_TIMED_EVENT ///< end of a timed event
+
+ };
+
+
+ /**
+ * @brief Constructor
+ * @param[in] type marker type
+ */
+ PerformanceMarker( PerformanceInterface::MarkerType type );
+
+ /**
+ * @brief Constructor
+ * @param[in] type marker type
+ * @param[in] time time stamp
+ */
+ PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp time );
+
+ /**
+ * @return the time stamp
+ */
+ const FrameTimeStamp& GetTimeStamp() const
+ {
+ return mTimeStamp;
+ }
+
+ /**
+ * @return the type of marker
+ */
+ PerformanceInterface::MarkerType GetType() const
+ {
+ return mType;
+ }
+
+ /**
+ * @return the event type of marker
+ */
+ MarkerEventType GetEventType() const;
+
+ /**
+ * @return the filter type of marker
+ */
+ MarkerFilter GetFilterType() const;
+
+
+ /**
+ * @return marker name
+ */
+ const char* GetName( ) const;
+
+ /**
+ * @param start the start marker
+ * @param end the end marker
+ * @return difference in microseconds between two markers
+ */
+ static unsigned int MicrosecondDiff( const PerformanceMarker& start, const PerformanceMarker& end );
+
+ /**
+ * @return if a marker is enabled as part of a group
+ */
+ bool IsFilterEnabled( MarkerFilter filter ) const;
+private:
+
+ PerformanceInterface::MarkerType mType; ///< marker type
+ FrameTimeStamp mTimeStamp; ///< frame time stamp
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/performance-server.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/platform-abstraction.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+#include <dali/internal/system/common/time-service.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const unsigned int NANOSECONDS_PER_MICROSECOND = 1000u;
+const float MICROSECONDS_TO_SECOND = 1e-6;
+} // unnamed namespace
+
+PerformanceServer::PerformanceServer( AdaptorInternalServices& adaptorServices,
+ const EnvironmentOptions& environmentOptions)
+: mEnvironmentOptions( environmentOptions ),
+ mKernelTrace( adaptorServices.GetKernelTraceInterface() ),
+ mSystemTrace( adaptorServices.GetSystemTraceInterface() ),
+ mLogMutex(),
+#if defined(NETWORK_LOGGING_ENABLED)
+ mNetworkServer( adaptorServices, environmentOptions ),
+ mNetworkControlEnabled( mEnvironmentOptions.GetNetworkControlMode()),
+#endif
+ mStatContextManager( *this ),
+ mStatisticsLogBitmask( 0 ),
+ mPerformanceOutputBitmask( 0 ),
+ mLoggingEnabled( false ),
+ mLogFunctionInstalled( false )
+{
+ SetLogging( mEnvironmentOptions.GetPerformanceStatsLoggingOptions(),
+ mEnvironmentOptions.GetPerformanceTimeStampOutput(),
+ mEnvironmentOptions.GetPerformanceStatsLoggingFrequency());
+
+#if defined(NETWORK_LOGGING_ENABLED)
+ if( mNetworkControlEnabled )
+ {
+ mLoggingEnabled = true;
+ mNetworkServer.Start();
+ }
+#endif
+}
+
+PerformanceServer::~PerformanceServer()
+{
+#if defined(NETWORK_LOGGING_ENABLED)
+ if( mNetworkControlEnabled )
+ {
+ mNetworkServer.Stop();
+ }
+#endif
+
+ if( mLogFunctionInstalled )
+ {
+ mEnvironmentOptions.UnInstallLogFunction();
+ }
+}
+
+void PerformanceServer::SetLogging( unsigned int statisticsLogOptions,
+ unsigned int timeStampOutput,
+ unsigned int logFrequency )
+{
+ mStatisticsLogBitmask = statisticsLogOptions;
+ mPerformanceOutputBitmask = timeStampOutput;
+
+ mStatContextManager.SetLoggingLevel( mStatisticsLogBitmask, logFrequency);
+
+ if( ( mStatisticsLogBitmask == 0) && ( mPerformanceOutputBitmask == 0 ))
+ {
+ mLoggingEnabled = false;
+ }
+ else
+ {
+ mLoggingEnabled = true;
+ }
+}
+
+void PerformanceServer::SetLoggingFrequency( unsigned int logFrequency, ContextId contextId )
+{
+ mStatContextManager.SetLoggingFrequency( logFrequency, contextId );
+}
+
+void PerformanceServer::EnableLogging( bool enable, ContextId contextId )
+{
+ mStatContextManager.EnableLogging( enable, contextId );
+}
+
+PerformanceInterface::ContextId PerformanceServer::AddContext( const char* name )
+{
+ // for adding custom contexts
+ return mStatContextManager.AddContext( name, PerformanceMarker::CUSTOM_EVENTS );
+}
+
+void PerformanceServer::RemoveContext( ContextId contextId )
+{
+ mStatContextManager.RemoveContext( contextId );
+}
+
+void PerformanceServer::AddMarker( MarkerType markerType, ContextId contextId )
+{
+ // called only for custom markers
+
+ if( !mLoggingEnabled )
+ {
+ return;
+ }
+
+ // Get the time stamp
+ uint64_t timeStamp = 0;
+ TimeService::GetNanoseconds( timeStamp );
+ timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds
+
+ // Create a marker
+ PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) );
+
+ // get the marker description for this context, e.g SIZE_NEGOTIATION_START
+ const char* const description = mStatContextManager.GetMarkerDescription( markerType, contextId );
+
+ // log it
+ LogMarker( marker, description );
+
+ // Add custom marker to statistics context manager
+ mStatContextManager.AddCustomMarker( marker, contextId );
+}
+
+void PerformanceServer::AddMarker( MarkerType markerType )
+{
+ // called only for internal markers
+
+ if( !mLoggingEnabled )
+ {
+ return;
+ }
+
+ if( markerType == VSYNC )
+ {
+ // make sure log function is installed, note this will be called only from v-sync thread
+ // if the v-sync thread has already installed one, it won't make any difference.
+ if( ! mLogFunctionInstalled )
+ {
+ mEnvironmentOptions.InstallLogFunction();
+ mLogFunctionInstalled = true;
+ }
+ }
+
+ // Get the time
+ uint64_t timeStamp = 0;
+ TimeService::GetNanoseconds( timeStamp );
+ timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds
+
+ // Create a marker
+ PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) );
+
+ // log it
+ LogMarker(marker, marker.GetName() );
+
+ // Add internal marker to statistics context manager
+ mStatContextManager.AddInternalMarker( marker );
+
+}
+
+void PerformanceServer::LogContextStatistics( const char* const text )
+{
+ Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, text );
+}
+
+void PerformanceServer::LogMarker( const PerformanceMarker& marker, const char* const description )
+{
+#if defined(NETWORK_LOGGING_ENABLED)
+ // log to the network ( this is thread safe )
+ if( mNetworkControlEnabled )
+ {
+ mNetworkServer.TransmitMarker( marker, description );
+ }
+#endif
+
+ // log to kernel trace
+ if( mPerformanceOutputBitmask & OUTPUT_KERNEL_TRACE )
+ {
+ // Kernel tracing implementation may not be thread safe
+ Mutex::ScopedLock lock( mLogMutex );
+ // description will be something like UPDATE_START or UPDATE_END
+ mKernelTrace.Trace( marker, description );
+ }
+
+ // log to system trace
+ if( mPerformanceOutputBitmask & OUTPUT_SYSTEM_TRACE )
+ {
+ // System tracing implementation may not be thread safe
+ Mutex::ScopedLock lock( mLogMutex );
+
+ mSystemTrace.Trace( marker, description );
+ }
+
+ // log to Dali log ( this is thread safe )
+ if ( mPerformanceOutputBitmask & OUTPUT_DALI_LOG )
+ {
+ Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo,
+ "%.6f (seconds), %s\n",
+ float( marker.GetTimeStamp().microseconds ) * MICROSECONDS_TO_SECOND,
+ description );
+
+ }
+}
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H__
+#define __DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLDUES
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/devel-api/threading/mutex.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/frame-time-stats.h>
+#include <dali/internal/network/common/network-performance-server.h>
+#include <dali/internal/adaptor/common/adaptor-internal-services.h>
+#include <dali/internal/system/common/performance-marker.h>
+#include <dali/internal/system/common/stat-context-manager.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class EnvironmentOptions;
+class StatContext;
+/**
+ * Concrete implementation of performance interface.
+ * Adaptor classes should never include this file, they
+ * just need to include the abstract class performance-interface.h
+ */
+class PerformanceServer : public PerformanceInterface, public StatContextLogInterface
+{
+public:
+
+ /**
+ * @brief Constructor
+ * @param[in] adaptorServices adaptor internal services
+ * @param[in] environmentOptions environment options
+ */
+ PerformanceServer( AdaptorInternalServices& adaptorServices,
+ const EnvironmentOptions& environmentOptions );
+
+ /**
+ * Destructor
+ */
+ virtual ~PerformanceServer();
+
+ /**
+ * @copydoc PerformanceLogger::AddContext()
+ */
+ virtual ContextId AddContext( const char* name );
+
+ /**
+ * @copydoc PerformanceLogger::RemoveContext()
+ */
+ virtual void RemoveContext( ContextId contextId );
+
+ /**
+ * @copydoc PerformanceInterface::AddMarker( MarkerType markerType )
+ */
+ virtual void AddMarker( MarkerType markerType );
+
+ /**
+ * @copydoc PerformanceLogger::AddMarker( MarkerType markerType, ContextId contextId )
+ */
+ virtual void AddMarker( MarkerType markerType, ContextId contextId );
+
+ /**
+ * @copydoc PerformanceInterface::SetLogging()
+ */
+ virtual void SetLogging( unsigned int statisticsLogOptions,
+ unsigned int timeStampOutput,
+ unsigned int logFrequency );
+
+ /**
+ * @copydoc PerformanceLogger::SetLoggingFrequency()
+ */
+ virtual void SetLoggingFrequency( unsigned int logFrequency, ContextId contextId );
+
+ /**
+ * @copydoc PerformanceLogger::EnableLogging()
+ */
+ virtual void EnableLogging( bool enable, ContextId contextId );
+
+public: //StatLogInterface
+
+ /**
+ * @copydoc StatLogInterface::LogContextStatistics()
+ */
+ virtual void LogContextStatistics( const char* const text );
+
+private:
+
+ /**
+ * @brief log the marker out to kernel/ DALi log
+ * @param[in] marker performance marker
+ * @param[in] description marker description
+ */
+ void LogMarker( const PerformanceMarker& marker, const char* const description );
+
+private:
+
+ const EnvironmentOptions& mEnvironmentOptions; ///< environment options
+ TraceInterface& mKernelTrace; ///< kernel trace interface
+ TraceInterface& mSystemTrace; ///< system trace interface
+ Dali::Mutex mLogMutex; ///< mutex
+
+#if defined(NETWORK_LOGGING_ENABLED)
+ NetworkPerformanceServer mNetworkServer; ///< network server
+ bool mNetworkControlEnabled; ///< Whether network control is enabled
+#endif
+
+ StatContextManager mStatContextManager; ///< Stat context manager
+ unsigned int mStatisticsLogBitmask; ///< statistics log level
+ unsigned int mPerformanceOutputBitmask; ///< performance marker output
+
+ bool mLoggingEnabled:1; ///< whether logging update / render to a log is enabled
+ bool mLogFunctionInstalled:1; ///< whether the log function is installed
+};
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/shared-file.h>
+
+// EXTERNAL INCLUDES
+#include <sys/types.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/file.h>
+#include <sys/mman.h>
+
+#include <cstring>
+
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+SharedFile* SharedFile::New(const char* filename, int size, bool isSystem)
+{
+ SharedFile *sf = NULL;
+
+ sf = new SharedFile;
+
+ bool opened = sf->OpenFile( filename, size, isSystem );
+ if( !opened )
+ {
+ delete sf;
+ sf = NULL;
+ }
+ return sf;
+}
+
+SharedFile::SharedFile()
+: mFileDescriptor(-1),
+ mSize(0),
+ mAddress(NULL),
+ mFilename()
+{
+}
+
+SharedFile::~SharedFile()
+{
+ Close();
+}
+
+void SharedFile::Close()
+{
+ if( mAddress != NULL )
+ {
+ munmap( mAddress, mSize );
+ mAddress = NULL;
+ }
+
+ if( mFileDescriptor >= 0 )
+ {
+ close( mFileDescriptor );
+ mFileDescriptor = -1;
+ }
+}
+
+unsigned char* SharedFile::GetAddress()
+{
+ return static_cast<unsigned char *>( mAddress );
+}
+
+bool SharedFile::OpenFile(const char* filename, int size, bool isSystem)
+{
+ bool opened = false;
+ mode_t mode;
+
+ mode = S_IRUSR | S_IWUSR;
+ if( isSystem )
+ {
+ mode |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
+ }
+
+ mFileDescriptor = shm_open( filename, O_RDONLY, mode );
+
+ if( mFileDescriptor >= 0 )
+ {
+ mFilename = filename;
+
+ mSize = size;
+ mAddress = mmap( NULL, mSize, PROT_READ, MAP_SHARED, mFileDescriptor, 0 );
+
+// MAP_FAILED is a macro with C cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ if( mAddress != MAP_FAILED )
+ {
+ opened = true;
+ }
+#pragma GCC diagnostic pop
+ }
+ return opened;
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#if defined(DEBUG_ENABLED)
+#include <dali/internal/system/common/logging.h>
+Debug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_SINGLETON_SERVICE" );
+
+// Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction
+#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message) \
+ if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string ); }
+
+#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )
+
+#else
+
+#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)
+#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)
+
+#endif
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+thread_local SingletonService * gSingletonService = 0;
+} // unnamed namespace
+
+Dali::SingletonService SingletonService::New()
+{
+ Dali::SingletonService singletonService( new SingletonService );
+ return singletonService;
+}
+
+Dali::SingletonService SingletonService::Get()
+{
+ Dali::SingletonService singletonService;
+ if ( gSingletonService )
+ {
+ singletonService = Dali::SingletonService( gSingletonService );
+ }
+ return singletonService;
+}
+
+void SingletonService::Register( const std::type_info& info, BaseHandle singleton )
+{
+ if( singleton )
+ {
+ DALI_LOG_SINGLETON_SERVICE( Debug::General, "Singleton Added: %s\n", info.name() );
+ mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );
+ }
+}
+
+void SingletonService::UnregisterAll( )
+{
+ mSingletonContainer.clear();
+}
+
+BaseHandle SingletonService::GetSingleton( const std::type_info& info ) const
+{
+ BaseHandle object;
+
+ const SingletonContainer::const_iterator end = mSingletonContainer.end();
+ for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )
+ {
+ // comparing the addresses as these are allocated statically per library
+ if( ( *iter ).first == info.name() )
+ {
+ object = ( *iter ).second;
+ }
+ }
+
+ return object;
+}
+
+SingletonService::SingletonService()
+: mSingletonContainer()
+{
+ // Can only have one instance of SingletonService
+ DALI_ASSERT_ALWAYS( !gSingletonService && "Only one instance of SingletonService is allowed");
+
+ gSingletonService = this;
+
+ DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Created\n" );
+}
+
+SingletonService::~SingletonService()
+{
+ gSingletonService = 0;
+
+ DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, "SingletonService Destroyed\n" );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
--- /dev/null
+#ifndef __DALI_INTERNAL_SINGLETON_SERVICE_H__
+#define __DALI_INTERNAL_SINGLETON_SERVICE_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/common/vector-wrapper.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/singleton-service.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class SingletonService : public Dali::BaseObject
+{
+public:
+
+ /**
+ * Create a SingletonService.
+ * This should only be called once by the Application class.
+ * @return A newly created SingletonService.
+ */
+ static Dali::SingletonService New();
+
+ /**
+ * @copydoc Dali::SingletonService::Get()
+ */
+ static Dali::SingletonService Get();
+
+ /**
+ * @copydoc Dali::SingletonService::Register()
+ */
+ void Register( const std::type_info& info, BaseHandle singleton );
+
+ /**
+ * @copydoc Dali::SingletonService::UnregisterAll()
+ */
+ void UnregisterAll();
+
+ /**
+ * @copydoc Dali::SingletonService::GetSingleton()
+ */
+ BaseHandle GetSingleton( const std::type_info& info ) const;
+
+private:
+
+ /**
+ * Private Constructor
+ * @see SingletonService::New()
+ */
+ SingletonService();
+
+ /**
+ * Virtual Destructor
+ */
+ virtual ~SingletonService();
+
+ // Undefined
+ SingletonService( const SingletonService& );
+ SingletonService& operator=( SingletonService& );
+
+private:
+
+ // using the address of the type name string as compiler will allocate these once per library
+ // and we don't support un/re-loading of dali libraries while singleton service is alive
+ typedef std::pair< const char*, BaseHandle> SingletonPair;
+ typedef std::vector< SingletonPair > SingletonContainer;
+ typedef SingletonContainer::const_iterator SingletonConstIter;
+
+ SingletonContainer mSingletonContainer; ///< The container to look up singleton by its type name
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::SingletonService& GetImplementation(Dali::SingletonService& player)
+{
+ DALI_ASSERT_ALWAYS( player && "SingletonService handle is empty" );
+
+ BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::SingletonService&>(handle);
+}
+
+inline const Internal::Adaptor::SingletonService& GetImplementation(const Dali::SingletonService& player)
+{
+ DALI_ASSERT_ALWAYS( player && "SingletonService handle is empty" );
+
+ const BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::SingletonService&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_SINGLETON_SERVICE_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/sound-player-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+const char* const SIGNAL_SOUND_PLAY_FINISHED = "soundPlayFinished";
+
+// Type Registration
+Dali::BaseHandle GetInstance()
+{
+ return SoundPlayer::Get();
+}
+
+Dali::TypeRegistration SOUND_PLAYER_TYPE( typeid(Dali::SoundPlayer), typeid(Dali::BaseHandle), GetInstance );
+
+Dali::SignalConnectorType SIGNAL_CONNECTOR_1( SOUND_PLAYER_TYPE, SIGNAL_SOUND_PLAY_FINISHED, Dali::Internal::Adaptor::SoundPlayer::DoConnectSignal );
+
+} // unnamed namespace
+
+Dali::SoundPlayer SoundPlayer::New()
+{
+ Dali::SoundPlayer player = Dali::SoundPlayer( new SoundPlayer() );
+ return player;
+}
+
+Dali::SoundPlayer SoundPlayer::Get()
+{
+ Dali::SoundPlayer player;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::SoundPlayer ) );
+ if ( handle )
+ {
+ // If so, downcast the handle
+ player = Dali::SoundPlayer( dynamic_cast< SoundPlayer* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ player = Dali::SoundPlayer( New() );
+ service.Register( typeid( player ), player );
+ }
+ }
+
+ return player;
+}
+
+int SoundPlayer::PlaySound( const std::string fileName )
+{
+ return mPlugin.PlaySound( fileName );
+}
+
+void SoundPlayer::Stop( int handle )
+{
+ mPlugin.StopSound( handle );
+}
+
+SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal()
+{
+ return mSoundPlayFinishedSignal;
+}
+
+bool SoundPlayer::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+{
+ bool connected( true );
+ SoundPlayer* player = dynamic_cast<SoundPlayer*>( object );
+
+ if( player && ( SIGNAL_SOUND_PLAY_FINISHED == signalName ) )
+ {
+ player->SoundPlayFinishedSignal().Connect( tracker, functor );
+ }
+ else
+ {
+ // signalName does not match any signal
+ connected = false;
+ }
+
+ return connected;
+}
+
+SoundPlayer::SoundPlayer()
+: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME )
+{
+}
+
+SoundPlayer::~SoundPlayer()
+{
+}
+
+void SoundPlayer::EmitSoundPlayFinishedSignal()
+{
+ // Emit SoundPlayFinished signal
+
+ if ( !mSoundPlayFinishedSignal.Empty() )
+ {
+ Dali::SoundPlayer handle( this );
+ mSoundPlayFinishedSignal.Emit( handle );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_SOUND_PLAYER_H__
+#define __DALI_INTERNAL_SOUND_PLAYER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/sound-player.h>
+#include <dali/internal/haptics/common/feedback-plugin-proxy.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Plays haptic effects.
+ */
+class SoundPlayer : public Dali::BaseObject
+{
+
+public:
+
+ typedef Dali::SoundPlayer::SoundPlayFinishedSignalType SoundPlayFinishedSignalType;
+
+ /**
+ * Create a SoundPlayer.
+ * @return A newly created SoundPlayer.
+ */
+ static Dali::SoundPlayer New();
+
+ /**
+ * Retrieve a handle to the SoundPlayer. This creates an instance if none has been created.
+ * @return A handle to the SoundPlayer.
+ */
+ static Dali::SoundPlayer Get();
+
+ /**
+ * @copydoc Dali::SoundPlayer::PlaySound()
+ */
+ int PlaySound(const std::string fileName);
+
+ /**
+ * @copydoc Dali::SoundPlayer::Stop()
+ */
+ void Stop(int handle);
+
+ /**
+ * @copydoc Dali::SoundPlayer::SoundPlayFinishedSignal()
+ */
+ SoundPlayFinishedSignalType& SoundPlayFinishedSignal();
+
+ /**
+ * Connects a callback function with the object's signals.
+ * @param[in] object The object providing the signal.
+ * @param[in] tracker Used to disconnect the signal.
+ * @param[in] signalName The signal to connect to.
+ * @param[in] functor A newly allocated FunctorDelegate.
+ * @return True if the signal was connected.
+ * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
+ */
+ static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
+
+private:
+
+ /**
+ * Private Constructor; see also soundPlayer::New()
+ * @param[in] soundPlayer The public sound player class
+ */
+ SoundPlayer();
+
+ /**
+ * Destructor
+ */
+ virtual ~SoundPlayer();
+
+ /**
+ * Emits the SoundPlayFinished signal.
+ */
+ void EmitSoundPlayFinishedSignal();
+
+ // Undefined
+ SoundPlayer(const SoundPlayer&);
+
+ // Undefined
+ SoundPlayer& operator=(SoundPlayer&);
+
+private:
+
+ FeedbackPluginProxy mPlugin;
+ SoundPlayFinishedSignalType mSoundPlayFinishedSignal;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::SoundPlayer& GetImplementation(Dali::SoundPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" );
+
+ BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::SoundPlayer&>(handle);
+}
+
+inline const Internal::Adaptor::SoundPlayer& GetImplementation(const Dali::SoundPlayer& player)
+{
+ DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" );
+
+ const BaseObject& handle = player.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::SoundPlayer&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_SOUND_PLAYER_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/stat-context-manager.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace
+{
+const char* const UPDATE_CONTEXT_NAME = "Update";
+const char* const RENDER_CONTEXT_NAME = "Render";
+const char* const EVENT_CONTEXT_NAME = "Event";
+const unsigned int DEFAULT_LOG_FREQUENCY = 2;
+}
+
+StatContextManager::StatContextManager( StatContextLogInterface& logInterface )
+: mLogInterface( logInterface ),
+ mNextContextId( 0 ),
+ mStatisticsLogBitmask(0),
+ mLogFrequency( DEFAULT_LOG_FREQUENCY )
+{
+
+ mStatContexts.Reserve(4); // intially reserve enough for 3 internal + 1 custom
+
+ // Add defaults
+ mUpdateStats = AddContext( UPDATE_CONTEXT_NAME, PerformanceMarker::UPDATE );
+ mRenderStats = AddContext( RENDER_CONTEXT_NAME, PerformanceMarker::RENDER );
+ mEventStats = AddContext( EVENT_CONTEXT_NAME, PerformanceMarker::EVENT_PROCESS );
+
+}
+
+StatContextManager::~StatContextManager()
+{
+ for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
+ {
+ StatContext* context = *it;
+ delete context;
+ }
+ mStatContexts.Clear();
+}
+PerformanceInterface::ContextId StatContextManager::AddContext( const char* const name,
+ PerformanceMarker::MarkerFilter type )
+{
+ unsigned int contextId = mNextContextId++;
+
+ DALI_ASSERT_DEBUG( NULL == GetContext( contextId ) );
+
+ // logging enabled by default
+ StatContext* statContext = new StatContext( contextId, name, type, mLogFrequency , mLogInterface );
+
+ // check to see if custom markers are enabled
+ if( ! ( mStatisticsLogBitmask & PerformanceInterface::LOG_CUSTOM_MARKERS ) )
+ {
+ statContext->EnableLogging( false );
+ }
+
+ mStatContexts.PushBack( statContext );
+
+ return contextId;
+}
+
+void StatContextManager::AddInternalMarker( const PerformanceMarker& marker )
+{
+ // log to the stat contexts, can be called from multiple threads so we
+ // protect the data
+ Mutex::ScopedLock lock( mDataMutex );
+ for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
+ {
+ StatContext* context = *it;
+ context->ProcessInternalMarker( marker );
+ }
+}
+
+void StatContextManager::AddCustomMarker( const PerformanceMarker& marker, PerformanceInterface::ContextId contextId )
+{
+ // log to the stat contexts, can be called from multiple threads so we
+ // protect the data
+ Mutex::ScopedLock lock( mDataMutex );
+ StatContext* context = GetContext( contextId );
+ if( context )
+ {
+ context->ProcessCustomMarker( marker );
+ }
+}
+
+void StatContextManager::RemoveContext(PerformanceInterface::ContextId contextId )
+{
+ for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
+ {
+ StatContext* context = *it;
+
+ if( context->GetId() == contextId )
+ {
+ delete context;
+ mStatContexts.Erase( it );
+ return;
+ }
+ }
+}
+
+
+void StatContextManager::EnableLogging( bool enable, PerformanceInterface::ContextId contextId )
+{
+ StatContext* context = GetContext( contextId );
+ if( context )
+ {
+ context->EnableLogging( enable );
+ }
+}
+
+void StatContextManager::SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency)
+{
+ mStatisticsLogBitmask = statisticsLogOptions;
+
+ if( mStatisticsLogBitmask == PerformanceInterface::LOG_EVERYTHING )
+ {
+ mStatisticsLogBitmask = 0xFFFFFFFF; // enable everything
+ }
+
+ mLogFrequency = logFrequency;
+
+ // currently uses DALI_LOG_PERFORMANCE_STATS_FREQ environment variable to determine to log frequency
+ // if it's not set it will be zero
+ if( mLogFrequency == 0 )
+ {
+ mLogFrequency = DEFAULT_LOG_FREQUENCY;
+ }
+ EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mUpdateStats );
+ EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mRenderStats );
+ EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_EVENT_PROCESS, mEventStats );
+
+ for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
+ {
+ StatContext* context = *it;
+ context->SetLogFrequency( mLogFrequency );
+ }
+}
+
+void StatContextManager::SetLoggingFrequency( unsigned int logFrequency,
+ PerformanceInterface::ContextId contextId )
+{
+ StatContext* context = GetContext( contextId );
+ if( context )
+ {
+ if( logFrequency == 0 )
+ {
+ logFrequency = DEFAULT_LOG_FREQUENCY;
+ }
+ context->SetLogFrequency( logFrequency );
+ }
+}
+const char* StatContextManager::GetContextName(PerformanceInterface::ContextId contextId) const
+{
+ StatContext* context = GetContext(contextId);
+ if( context )
+ {
+ return context->GetName();
+ }
+ return "context not found";
+}
+
+const char* StatContextManager::GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const
+{
+ StatContext* context = GetContext(contextId);
+ if( context )
+ {
+ return context->GetMarkerDescription( type );
+ }
+ return "context not found";
+}
+
+
+StatContext* StatContextManager::GetContext( PerformanceInterface::ContextId contextId ) const
+{
+ for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it )
+ {
+ StatContext* context = *it;
+
+ if( context->GetId() == contextId )
+ {
+ return context;
+ }
+ }
+
+ return NULL;
+}
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
+#define __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/devel-api/threading/mutex.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-marker.h>
+#include <dali/internal/system/common/stat-context.h>
+#include <dali/internal/system/common/performance-interface.h>
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Class to manage StatContext objects.
+ *
+ * Contains 3 built in contexts for event, update, render.
+ * The application developer can add more using the PerformanceLogger public API
+ *
+ * Example output of 4 contexts ( event, update, render and a custom one):
+ *
+ * Event, min 0.04 ms, max 5.27 ms, total (0.1 secs), avg 0.28 ms, std dev 0.73 ms
+ * Update, min 0.29 ms, max 0.91 ms, total (0.5 secs), avg 0.68 ms, std dev 0.15 ms
+ * Render, min 0.33 ms, max 0.97 ms, total (0.6 secs), avg 0.73 ms, std dev 0.17 ms
+ * MyAppTask, min 76.55 ms, max 76.55 ms, total (0.1 secs), avg 76.55 ms, std dev 0.00 ms (CUSTOM CONTEXT)
+ *
+ */
+class StatContextManager
+{
+
+public:
+
+ /**
+ * @brief Constructor
+ * @param[in] logInterface interface to log statistics to
+ */
+ StatContextManager( StatContextLogInterface& logInterface );
+
+ /**
+ * @brief destructor, not intended as a bass class
+ */
+ ~StatContextManager();
+
+ /**
+ * @brief Add a context
+ * @param[in] name Name of the context to print in console
+ * @param[in] type the type of events to filter ( e.g. event, update, render or custom)
+ * @return The ID to give the context
+ */
+ PerformanceInterface::ContextId AddContext( const char* const name, PerformanceMarker::MarkerFilter type );
+
+ /**
+ * @brief Remove a context
+ * @param[in] contextId id of the context to remove
+ */
+ void RemoveContext(PerformanceInterface::ContextId contextId );
+
+ /**
+ * @brief Add an internal marker (e.g. v-sync, update, render markers)
+ * @param[in] marker the marker to add
+ */
+ void AddInternalMarker( const PerformanceMarker& marker );
+
+ /**
+ * @brief Add a custom marker defined by the application
+ * @param[in] marker the marker to add
+ * @param[in] contextId the context the custom marker is designed for
+ */
+ void AddCustomMarker( const PerformanceMarker& marker , PerformanceInterface::ContextId contextId );
+
+ /**
+ * @brief Get the nane of a context
+ * @param[in] contextId id of the context to get the name
+ * @return context name
+ */
+ const char* GetContextName( PerformanceInterface::ContextId contextId ) const;
+
+ /**
+ * @brief Get the full description of a marker for this context
+ * @param[in] type marker type, for a customer marker this will be either START or END
+ * @param[in] contextId id of the context to get the name
+ * @return marker description in relation to this context
+ */
+ const char* GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const;
+
+
+ /**
+ * @brief enable / disable logging for a context
+ * @param[in] enable whether to enable logging
+ * @param[in] contextId the context to configure
+ */
+ void EnableLogging( bool enable, PerformanceInterface::ContextId contextId );
+
+ /**
+ * @brief set global logging level and frequency.
+ * @param[in] statisticsLogOptions log options
+ * @param[in] logFrequency frequency in seconds
+ */
+ void SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency);
+
+ /**
+ * @brief Set the frequency of logging for an individual context
+ * @param[in] logFrequency log frequency in seconds
+ * @param[in] contextId the context to configure
+ */
+ void SetLoggingFrequency( unsigned int logFrequency, PerformanceInterface::ContextId contextId );
+
+ private:
+
+ StatContextManager( const StatContextManager& ); ///< Undefined
+ StatContextManager& operator=( const StatContextManager& ); ///< Undefined
+
+ typedef Dali::Vector< StatContext* > StatContexts;
+
+ /**
+ * @brief helper
+ * @param[in] contextId the context to get
+ * @return context
+ */
+ StatContext* GetContext( PerformanceInterface::ContextId contextId ) const;
+
+ Dali::Mutex mDataMutex; ///< mutex
+ StatContexts mStatContexts; ///< The list of stat contexts
+ StatContextLogInterface& mLogInterface; ///< Log interface
+
+ PerformanceInterface::ContextId mNextContextId; ///< The next valid context ID
+
+ // Some defaults contexts
+ PerformanceInterface::ContextId mUpdateStats; ///< update time statistics
+ PerformanceInterface::ContextId mRenderStats; ///< render time statistics
+ PerformanceInterface::ContextId mEventStats; ///< event time statistics
+
+ unsigned int mStatisticsLogBitmask; ///< statistics log bitmask
+ unsigned int mLogFrequency; ///< log frequency
+};
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H__
+
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+// CLASS HEADER
+#include <dali/internal/system/common/stat-context.h>
+
+// EXTERNAL INCLUDES
+#include <cstdio>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/platform-abstraction.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#define TIME_FMT "%0.2f ms" // 2 decimal places, e.g. 5.34 ms
+#define TOTAL_TIME_FMT "%0.1f secs" // 1 decimal place, e.g. 4.5 seconds
+
+namespace
+{
+const unsigned int MILLISECONDS_PER_SECOND = 1000; ///< 1000 milliseconds per second
+const char* const UNKNOWN_CONTEXT_NAME = "UNKNOWN_CONTEXT_NAME";
+const unsigned int MICROSECONDS_PER_SECOND = 1000000; ///< 1000000 microseconds per second
+const unsigned int CONTEXT_LOG_SIZE = 120;
+
+}
+
+StatContext::StatContext( unsigned int id,
+ const char* const contextName,
+ PerformanceMarker::MarkerFilter contextType,
+ unsigned int logFrequencySeconds,
+ StatContextLogInterface& logInterface )
+: mInitialMarker(PerformanceInterface::VSYNC),
+ mName( contextName ),
+ mLogInterface( logInterface ),
+ mNamePlusStart( std::string(contextName) + "_START" ),
+ mNamePlusEnd( std::string(contextName) + "_END" ),
+ mId( id ),
+ mLogFrequencyMicroseconds( logFrequencySeconds * MICROSECONDS_PER_SECOND ),
+ mFilterType( contextType ),
+ mLoggingEnabled( true ),
+ mInitialMarkerSet( false )
+{
+ mTempLogBuffer = new char[ CONTEXT_LOG_SIZE ];
+}
+
+StatContext::~StatContext()
+{
+ delete []mTempLogBuffer;
+}
+unsigned int StatContext::GetId() const
+{
+ return mId;
+}
+
+const char* StatContext::GetName() const
+{
+ return mName;
+}
+
+const char* StatContext::GetMarkerDescription( PerformanceInterface::MarkerType type ) const
+{
+ if( type == PerformanceInterface::START )
+ {
+ return mNamePlusStart.c_str();
+ }
+ else if( type == PerformanceInterface::END )
+ {
+ return mNamePlusEnd.c_str();
+ }
+ return UNKNOWN_CONTEXT_NAME;
+}
+void StatContext::SetLogFrequency( unsigned int logFrequencySeconds )
+{
+ mLogFrequencyMicroseconds = logFrequencySeconds * MICROSECONDS_PER_SECOND;
+}
+
+void StatContext::EnableLogging( bool enableLogging )
+{
+ mLoggingEnabled = enableLogging;
+}
+
+void StatContext::ProcessCustomMarker( const PerformanceMarker& marker )
+{
+ // this marker has come from the application PerformanceLogger API
+ RecordMarker( marker);
+}
+
+void StatContext::ProcessInternalMarker( const PerformanceMarker& marker )
+{
+ // this marker has come from DALi internal not the application
+ // see if this context is for update, render or event
+ if( marker.IsFilterEnabled( mFilterType ))
+ {
+ RecordMarker( marker );
+ }
+ // V_SYNC is always processed
+ if( marker.GetType() == PerformanceInterface::VSYNC )
+ {
+ FrameTick( marker );
+ }
+}
+
+void StatContext::RecordMarker( const PerformanceMarker& marker )
+{
+ if( marker.GetEventType() == PerformanceMarker::START_TIMED_EVENT )
+ {
+ mStats.StartTime( marker.GetTimeStamp() );
+ }
+ else if( marker.GetEventType() == PerformanceMarker::END_TIMED_EVENT )
+ {
+ mStats.EndTime( marker.GetTimeStamp() );
+ }
+}
+
+void StatContext::FrameTick( const PerformanceMarker& marker )
+{
+ // wait until we've got some data
+ if( ! mInitialMarkerSet )
+ {
+ mInitialMarker = marker;
+ mInitialMarkerSet = true;
+ return;
+ }
+ // log out every mLogFrequency.
+ // check difference between first and last frame
+ unsigned int microseconds = PerformanceMarker::MicrosecondDiff( mInitialMarker, marker );
+
+ if( microseconds < mLogFrequencyMicroseconds )
+ {
+ return;
+ }
+
+ if( mLoggingEnabled )
+ {
+ LogMarker();
+ }
+ mStats.Reset(); // reset data for statistics
+ mInitialMarkerSet = false; // need to restart the timer
+
+}
+
+void StatContext::LogMarker()
+{
+ float mean, standardDeviation;
+ mStats.CalculateMean( mean, standardDeviation );
+
+ snprintf( mTempLogBuffer, CONTEXT_LOG_SIZE, "%s, min " TIME_FMT ", max " TIME_FMT ", total (" TOTAL_TIME_FMT "), avg " TIME_FMT ", std dev " TIME_FMT "\n",
+ mName ? mName : UNKNOWN_CONTEXT_NAME,
+ mStats.GetMinTime() * MILLISECONDS_PER_SECOND,
+ mStats.GetMaxTime() * MILLISECONDS_PER_SECOND,
+ mStats.GetTotalTime(),
+ mean * MILLISECONDS_PER_SECOND,
+ standardDeviation * MILLISECONDS_PER_SECOND );
+
+ mLogInterface.LogContextStatistics( mTempLogBuffer );
+
+}
+
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H__
+#define __DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/performance-marker.h>
+#include <dali/internal/system/common/frame-time-stats.h>
+#include <dali/internal/system/common/performance-interface.h>
+#include <dali/internal/system/common/stat-context-log-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Stores and prints statistics for a particular logging context.
+ *
+ */
+class StatContext
+{
+
+public:
+
+ /**
+ * @brief Constructor
+ *
+ * @param[in] id The ID to give the context
+ * @param[in] contextName Name of the context to print in console
+ * @param[in] contextType the type of events to filter ( e.g. event, update, render or custom)
+ * @param[in] logFrequencySeconds frequency to log in seconds
+ * @param[in] logInterface interface to log out to
+ *
+ */
+ StatContext( unsigned int id,
+ const char* const contextName,
+ PerformanceMarker::MarkerFilter contextType,
+ unsigned int logFrequencySeconds,
+ StatContextLogInterface& logInterface );
+
+
+ /**
+ * @brief Non-virtual destructor, not intended as a base class
+ */
+ ~StatContext();
+
+ /**
+ * @return Return the context ID
+ */
+ unsigned int GetId() const;
+
+ /**
+ * @return the context name
+ */
+ const char* GetName() const;
+
+ /**
+ *
+ * For logging we want to output the name of the context with either
+ * START / END appended to the end. E.g. MY_MARKER_START
+ * @param[in] type marker type, for a customer marker this will be either START or END
+ * @return the full description for a marker
+ */
+ const char* GetMarkerDescription( PerformanceInterface::MarkerType type ) const;
+
+ /**
+ * @brief Set the frequency for logging
+ *
+ * @param[in] logFrequencySeconds The log frequency to set in seconds
+ */
+ void SetLogFrequency( unsigned int logFrequencySeconds );
+
+ /**
+ * @brief enable/disable logging
+ *
+ * @param[in] enableLogging Flag to spePerformancecify enabling/disabling
+ */
+ void EnableLogging( bool enableLogging );
+
+ /**
+ * @brief Process a custom marker from the application
+ *
+ * @param[in] marker The marker to log
+ */
+ void ProcessCustomMarker( const PerformanceMarker& marker );
+
+ /**
+ * @brief Process a internal marker from DALi (V_SYNC/ UPDATE /RENDER/ EVENT )
+ *
+ * @param[in] marker The marker to log
+ */
+ void ProcessInternalMarker( const PerformanceMarker& marker );
+
+ private:
+
+ /**
+ * @brief Record marker
+ *
+ * @param[in] marker to record
+ */
+ void RecordMarker( const PerformanceMarker& marker );
+
+ /**
+ * @brief Called when V-SYNC occurs to indicate a frame tick
+ * @param[in] marker the marker containing a v-sync
+ */
+ void FrameTick( const PerformanceMarker& marker );
+
+ /**
+ * @brief Helper to print to console
+ */
+ void LogMarker();
+
+
+ private:
+
+ StatContext(); ///< undefined default constructor
+
+ StatContext( const StatContext& ); ///< undefined copy constructor
+
+ StatContext& operator=( const StatContext& ); ///< undefined assignment operator
+
+ private:
+
+ PerformanceMarker mInitialMarker; ///< Used to store initial time
+ FrameTimeStats mStats; ///< Frame time stats to accumulate
+ const char* const mName; ///< Name of the context
+ char* mTempLogBuffer; ///< Temporary log buffer
+ StatContextLogInterface& mLogInterface; ///< Log interface
+ const std::string mNamePlusStart; ///< Name of the context + _START
+ const std::string mNamePlusEnd; ///< Name of the context + _END
+ unsigned int mId; ///< The ID of the context
+ unsigned int mLogFrequencyMicroseconds; ///< if logging is enabled, what frequency to log out at in micro-seconds
+ PerformanceMarker::MarkerFilter mFilterType; ///< type of events the context is filtering
+ bool mLoggingEnabled:1; ///< Whether to print the log for this context or not
+ bool mInitialMarkerSet:1; ///< Whether the initial marker has been set
+
+};
+
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/system-trace.h>
+
+// EXTERNAL HEADERS
+#include <string>
+#include <dali/devel-api/common/hash.h>
+
+// INTERNAL HEADERS
+#include <dali/integration-api/debug.h>
+
+#ifdef ENABLE_TTRACE
+#include <ttrace.h>
+#else
+
+// Emulate trace calls if ttrace isn't available
+namespace
+{
+const int TTRACE_TAG_GRAPHICS = 1;
+
+void traceAsyncBegin(int tag, int cookie, const char *name, ...)
+{
+ Debug::LogMessage(Debug::DebugInfo, "AsyncBegin: %s : cookie %d\n", name, cookie );
+}
+void traceAsyncEnd(int tag, int cookie, const char *name, ...)
+{
+ Debug::LogMessage(Debug::DebugInfo, "AsyncEnd: %s : cookie %d\n", name, cookie );
+}
+void traceMark(int tag, const char *name, ...)
+{
+ Debug::LogMessage(Debug::DebugInfo, "Marker: %s \n", name);
+}
+} // un-named namespace
+#endif
+
+namespace
+{
+
+int GetCookie( const std::string& description, std::string& markerName )
+{
+ // description holds the marker name and postfix of _START or _END
+ std::size_t pos = description.find("_START");
+ if( pos == std::string::npos )
+ {
+ pos = description.find("_END");
+ }
+ if( !pos )
+ {
+ // if this asserts then check the postfix strings in StatContext.cpp for
+ // custom markers and performance-marker.cpp for built-in markers
+ DALI_ASSERT_DEBUG(0);
+ }
+ markerName = description.substr( 0, pos );
+
+ std::size_t hash = Dali::CalculateHash( markerName.c_str() );
+ return static_cast<int>( hash );
+}
+}
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+SystemTrace::SystemTrace()
+{
+}
+SystemTrace::~SystemTrace()
+{
+}
+
+void SystemTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage )
+{
+ PerformanceMarker::MarkerEventType eventType = marker.GetEventType();
+
+ if( eventType == PerformanceMarker::SINGLE_EVENT )
+ {
+ traceMark( TTRACE_TAG_GRAPHICS, traceMessage.c_str() );
+ return;
+ }
+
+ // DALi is multi-threaded so timed events will occur asynchronously
+ std::string markerName;
+
+ int cookie = GetCookie(traceMessage, markerName );
+
+ if( eventType == PerformanceMarker::START_TIMED_EVENT )
+ {
+ traceAsyncBegin( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() );
+ }
+ else
+ {
+ traceAsyncEnd( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() );
+ }
+}
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
--- /dev/null
+#ifndef __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
+#define __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/network/common/trace-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Concrete System Tracing Interface.
+ * Used to log trace messages to the system using ttrace
+ *
+ */
+class SystemTrace : public TraceInterface
+{
+public:
+
+ /**
+ * Constructor
+ */
+ SystemTrace();
+
+ /**
+ * Destructor
+ */
+ virtual ~SystemTrace();
+
+ /**
+ * @copydoc KernelTracerInterface::KernelTrace()
+ */
+ virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage );
+
+};
+
+} // namespace Internal
+
+} // namespace Adaptor
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/thread-controller.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+#include <dali/internal/adaptor/common/thread-controller-interface.h>
+#include <dali/internal/adaptor/common/combined-update-render-controller.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+ThreadController::ThreadController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions )
+: mThreadControllerInterface( NULL )
+{
+ switch( environmentOptions.GetThreadingMode() )
+ {
+ case ThreadingMode::COMBINED_UPDATE_RENDER:
+ {
+ mThreadControllerInterface = new CombinedUpdateRenderController( adaptorInterfaces, environmentOptions );
+ break;
+ }
+ }
+}
+
+ThreadController::~ThreadController()
+{
+ delete mThreadControllerInterface;
+}
+
+void ThreadController::Initialize()
+{
+ mThreadControllerInterface->Initialize();
+}
+
+void ThreadController::Start()
+{
+ mThreadControllerInterface->Start();
+}
+
+void ThreadController::Pause()
+{
+ mThreadControllerInterface->Pause();
+}
+
+void ThreadController::Resume()
+{
+ mThreadControllerInterface->Resume();
+}
+
+void ThreadController::Stop()
+{
+ mThreadControllerInterface->Stop();
+}
+
+void ThreadController::RequestUpdate()
+{
+ mThreadControllerInterface->RequestUpdate();
+}
+
+void ThreadController::RequestUpdateOnce()
+{
+ mThreadControllerInterface->RequestUpdateOnce();
+}
+
+void ThreadController::ReplaceSurface( RenderSurface* newSurface )
+{
+ mThreadControllerInterface->ReplaceSurface( newSurface );
+}
+
+void ThreadController::ResizeSurface()
+{
+ mThreadControllerInterface->ResizeSurface();
+}
+
+void ThreadController::SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender )
+{
+ mThreadControllerInterface->SetRenderRefreshRate( numberOfVSyncsPerRender );
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// HEADER
+#include <dali/internal/system/common/time-service.h>
+
+// EXTERNAL INCLUDES
+#include <ctime>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace TimeService
+{
+
+namespace
+{
+const uint64_t NANOSECONDS_PER_SECOND = 1e+9;
+}
+
+void GetNanoseconds( uint64_t& timeInNanoseconds )
+{
+ timespec timeSpec;
+ clock_gettime( CLOCK_MONOTONIC, &timeSpec );
+
+ // Convert all values to uint64_t to match our return type
+ timeInNanoseconds = ( static_cast< uint64_t >( timeSpec.tv_sec ) * NANOSECONDS_PER_SECOND ) + static_cast< uint64_t >( timeSpec.tv_nsec );
+}
+
+void SleepUntil( uint64_t timeInNanoseconds )
+{
+ timespec timeSpec;
+ timeSpec.tv_sec = timeInNanoseconds / NANOSECONDS_PER_SECOND;
+ timeSpec.tv_nsec = timeInNanoseconds % NANOSECONDS_PER_SECOND;
+
+ // clock_nanosleep returns 0 if it sleeps for the period specified, otherwise it returns an error value
+ // If an error value is returned, just sleep again till the absolute time specified
+ while( clock_nanosleep( CLOCK_MONOTONIC, TIMER_ABSTIME, &timeSpec, NULL ) )
+ {
+ }
+}
+
+} // namespace TimeService
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/timer-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+// LOCAL STUFF
+namespace
+{
+Eina_Bool TimerSourceFunc (void *data)
+{
+ Timer* timer = static_cast<Timer*>(data);
+
+ bool keepRunning = timer->Tick();
+
+ return keepRunning ? EINA_TRUE : EINA_FALSE;
+}
+} // unnamed namespace
+
+/**
+ * Struct to hide away Ecore implementation details
+ */
+struct Timer::Impl
+{
+ Impl( unsigned int milliSec )
+ : mId(NULL),
+ mInterval(milliSec)
+ {
+ }
+
+ Ecore_Timer * mId;
+ unsigned int mInterval;
+};
+
+TimerPtr Timer::New( unsigned int milliSec )
+{
+ TimerPtr timer( new Timer( milliSec ) );
+ return timer;
+}
+
+Timer::Timer( unsigned int milliSec )
+: mImpl(new Impl(milliSec))
+{
+}
+
+Timer::~Timer()
+{
+ ResetTimerData();
+ delete mImpl;
+}
+
+void Timer::Start()
+{
+ // Timer should be used in the event thread
+ DALI_ASSERT_DEBUG( Adaptor::IsAvailable() );
+
+ if(mImpl->mId != NULL)
+ {
+ Stop();
+ }
+ mImpl->mId = ecore_timer_add( (double)mImpl->mInterval/1000.0f, (Ecore_Task_Cb)TimerSourceFunc, this );
+}
+
+void Timer::Stop()
+{
+ // Timer should be used in the event thread
+ DALI_ASSERT_DEBUG( Adaptor::IsAvailable() );
+
+ ResetTimerData();
+}
+
+void Timer::SetInterval( unsigned int interval )
+{
+ // stop existing timer
+ Stop();
+ mImpl->mInterval = interval;
+ // start new tick
+ Start();
+}
+
+unsigned int Timer::GetInterval() const
+{
+ return mImpl->mInterval;
+}
+
+bool Timer::Tick()
+{
+ // Guard against destruction during signal emission
+ Dali::Timer handle( this );
+
+ bool retVal( false );
+
+ // Override with new signal if used
+ if( !mTickSignal.Empty() )
+ {
+ retVal = mTickSignal.Emit();
+
+ // Timer stops if return value is false
+ if (retVal == false)
+ {
+ Stop();
+ }
+ else
+ {
+ retVal = true; // continue emission
+ }
+ }
+ else // no callbacks registered
+ {
+ // periodic timer is started but nobody listens, continue
+ retVal = true;
+ }
+
+ return retVal;
+}
+
+Dali::Timer::TimerSignalType& Timer::TickSignal()
+{
+ return mTickSignal;
+}
+
+void Timer::ResetTimerData()
+{
+ if (mImpl->mId != NULL)
+ {
+ ecore_timer_del(mImpl->mId);
+ mImpl->mId = NULL;
+ }
+}
+
+bool Timer::IsRunning() const
+{
+ return mImpl->mId != NULL;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_INTERNAL_TIMER_H__
+#define __DALI_INTERNAL_TIMER_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/timer-interface.h>
+#include <dali/public-api/adaptor-framework/timer.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class Timer;
+
+typedef IntrusivePtr<Timer> TimerPtr;
+
+/**
+ * Implementation of the timer
+ */
+class Timer : public BaseObject, public TimerInterface
+{
+public:
+ static TimerPtr New( unsigned int milliSec );
+
+ /**
+ * Constructor
+ * @param[in] milliSec Interval in milliseconds.
+ */
+ Timer( unsigned int milliSec );
+
+ /**
+ * Destructor.
+ */
+ virtual ~Timer();
+
+public:
+
+ /**
+ * @copydoc Dali::Timer::Start()
+ */
+ virtual void Start();
+
+ /**
+ * @copydoc Dali::Timer::Stop()
+ */
+ virtual void Stop();
+
+ /**
+ * @copydoc Dali::Timer::SetInterval()
+ */
+ virtual void SetInterval( unsigned int interval );
+
+ /**
+ * @copydoc Dali::Timer::GetInterval()
+ */
+ virtual unsigned int GetInterval() const;
+
+ /**
+ * @copydoc Dali::Timer::IsRunning()
+ */
+ virtual bool IsRunning() const;
+
+ /**
+ * Tick
+ */
+ bool Tick();
+
+public: // Signals
+
+ Dali::Timer::TimerSignalType& TickSignal();
+
+private: // Implementation
+
+ // not implemented
+ Timer( const Timer& );
+ Timer& operator=( const Timer& );
+
+ /**
+ * Resets any stored timer data.
+ */
+ void ResetTimerData();
+
+private: // Data
+
+ Dali::Timer::TimerSignalType mTickSignal;
+
+ // To hide away implementation details
+ struct Impl;
+ Impl* mImpl;
+};
+
+inline Timer& GetImplementation(Dali::Timer& timer)
+{
+ DALI_ASSERT_ALWAYS(timer && "Timer handle is empty");
+
+ BaseObject& handle = timer.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::Timer&>(handle);
+}
+
+inline const Timer& GetImplementation(const Dali::Timer& timer)
+{
+ DALI_ASSERT_ALWAYS(timer && "Timer handle is empty");
+
+ const BaseObject& handle = timer.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::Timer&>(handle);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_TIMER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/trigger-event-factory.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/trigger-event.h>
+
+namespace Dali
+{
+
+TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options )
+{
+ return new Internal::Adaptor::TriggerEvent( callback, options );
+}
+
+void TriggerEventFactory::DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface )
+{
+ Internal::Adaptor::TriggerEvent* triggerEvent( static_cast<Internal::Adaptor::TriggerEvent *>(triggerEventInterface) );
+ delete triggerEvent;
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/trigger-event.h>
+
+// EXTERNAL INCLUDES
+#include <sys/eventfd.h>
+#include <unistd.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+
+#include <dali/internal/system/common/file-descriptor-monitor.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+TriggerEvent::TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options )
+: mFileDescriptorMonitor( NULL ),
+ mCallback( callback ),
+ mFileDescriptor( -1 ),
+ mOptions( options )
+{
+ // Create accompanying file descriptor.
+ mFileDescriptor = eventfd(0, EFD_NONBLOCK);
+ if (mFileDescriptor >= 0)
+ {
+ // Now Monitor the created event file descriptor
+ mFileDescriptorMonitor = new FileDescriptorMonitor( mFileDescriptor, MakeCallback( this, &TriggerEvent::Triggered ), FileDescriptorMonitor::FD_READABLE );
+ }
+ else
+ {
+ DALI_LOG_ERROR("Unable to create TriggerEvent File descriptor\n");
+ }
+}
+
+TriggerEvent::~TriggerEvent()
+{
+ delete mFileDescriptorMonitor;
+ delete mCallback;
+
+ if (mFileDescriptor >= 0)
+ {
+ close(mFileDescriptor);
+ mFileDescriptor = 0;
+ }
+}
+
+void TriggerEvent::Trigger()
+{
+ if (mFileDescriptor >= 0)
+ {
+ // Increment event counter by 1.
+ // Writing to the file descriptor triggers the Dispatch() method in the other thread
+ // (if in multi-threaded environment).
+
+ uint64_t data = 1;
+ int size = write(mFileDescriptor, &data, sizeof(uint64_t));
+
+ if (size != sizeof(uint64_t))
+ {
+ DALI_LOG_ERROR("Unable to write to UpdateEvent File descriptor\n");
+ }
+ }
+ else
+ {
+ DALI_LOG_WARNING("Attempting to write to an invalid file descriptor\n");
+ }
+}
+
+void TriggerEvent::Triggered( FileDescriptorMonitor::EventType eventBitMask )
+{
+ if( !( eventBitMask & FileDescriptorMonitor::FD_READABLE ) )
+ {
+ DALI_ASSERT_ALWAYS( 0 && "Trigger event file descriptor error");
+ return;
+ }
+
+ // Reading from the file descriptor resets the event counter, we can ignore the count.
+ uint64_t receivedData;
+ size_t size;
+ size = read(mFileDescriptor, &receivedData, sizeof(uint64_t));
+ if (size != sizeof(uint64_t))
+ {
+ DALI_LOG_WARNING("Unable to read to UpdateEvent File descriptor\n");
+ }
+
+ // Call the connected callback
+ CallbackBase::Execute( *mCallback );
+
+ //check if we should delete ourselves after the trigger
+ if( mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER )
+ {
+ delete this;
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_TRIGGER_EVENT_H__
+#define __DALI_INTERNAL_TRIGGER_EVENT_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/signals/callback.h>
+#include <dali/internal/system/common/file-descriptor-monitor.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/trigger-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+
+/**
+ * The TriggerEvent class is used to send events between threads. For example, this can be used
+ * to wake up one thread from another thread.
+ *
+ * Typically, these should be created in the application thread.
+ *
+ * The observer will be informed whenever the event is triggered.
+ *
+ * The implementation of TriggerEvent uses an event file descriptor.
+ */
+class TriggerEvent : public TriggerEventInterface
+{
+public:
+
+ /**
+ * Constructor
+ * Creates an event file descriptor and starts a GSource which reads from the file
+ * descriptor when there is data.
+ *
+ * @param[in] callback The callback to call
+ * @param[in] options Trigger event options.
+ * @note The ownership of callback is taken by this class.
+ */
+ TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options );
+
+ /**
+ * Destructor
+ */
+ ~TriggerEvent();
+
+public:
+
+ /**
+ * Triggers the event.
+ *
+ * This can be called from one thread in order to wake up another thread.
+ */
+ void Trigger();
+
+private:
+
+ /**
+ * @brief Called when our event file descriptor has been written to.
+ * @param[in] eventBitMask bit mask of events that occured on the file descriptor
+ */
+ void Triggered( FileDescriptorMonitor::EventType eventBitMask );
+
+private:
+
+ struct Source;
+
+private:
+
+ FileDescriptorMonitor* mFileDescriptorMonitor;
+ CallbackBase* mCallback;
+ int mFileDescriptor;
+ TriggerEventInterface::Options mOptions;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_TRIGGER_EVENT_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/update-status-logger.h>
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/integration-api/core.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/environment-options.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+UpdateStatusLogger::UpdateStatusLogger( const EnvironmentOptions& environmentOptions )
+: mStatusLogInterval( environmentOptions.GetUpdateStatusLoggingFrequency() ),
+ mStatusLogCount( 0u )
+{
+}
+
+UpdateStatusLogger::~UpdateStatusLogger()
+{
+}
+
+void UpdateStatusLogger::Log( unsigned int keepUpdatingStatus )
+{
+ if ( mStatusLogInterval )
+ {
+ std::string oss;
+
+ if ( !(++mStatusLogCount % mStatusLogInterval) )
+ {
+ oss = "UpdateStatusLogging keepUpdating: ";
+ oss += (keepUpdatingStatus ? "true":"false");
+
+ if ( keepUpdatingStatus )
+ {
+ oss += " because: ";
+ }
+
+ if ( keepUpdatingStatus & Integration::KeepUpdating::STAGE_KEEP_RENDERING )
+ {
+ oss += "<Stage::KeepRendering() used> ";
+ }
+
+ if ( keepUpdatingStatus & Integration::KeepUpdating::ANIMATIONS_RUNNING )
+ {
+ oss += "<Animations running> ";
+ }
+
+ if ( keepUpdatingStatus & Integration::KeepUpdating::MONITORING_PERFORMANCE )
+ {
+ oss += "<Monitoring performance> ";
+ }
+
+ if ( keepUpdatingStatus & Integration::KeepUpdating::RENDER_TASK_SYNC )
+ {
+ oss += "<Render task waiting for completion> ";
+ }
+
+ DALI_LOG_UPDATE_STATUS( "%s\n", oss.c_str());
+ }
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/common/widget-application-impl.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+// factory function, must be implemented
+namespace WidgetApplicationFactory
+{
+/**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet );
+
+} // namespace Factory
+
+WidgetApplicationPtr WidgetApplication::New(
+ int* argc,
+ char **argv[],
+ const std::string& stylesheet)
+{
+ //WidgetApplicationPtr //widgetApplication( new WidgetApplication (argc, argv, stylesheet ) );
+ return WidgetApplicationFactory::Create( argc, argv, stylesheet );
+}
+
+WidgetApplication::WidgetApplication( int* argc, char** argv[], const std::string& stylesheet )
+: Application(argc, argv, stylesheet, Dali::WidgetApplication::OPAQUE, PositionSize(), Framework::NORMAL)
+{
+ DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n");
+}
+
+WidgetApplication::~WidgetApplication()
+{
+}
+
+void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WIDGET_APPLICATION_IMPL_H
+#define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_H
+
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/application-impl.h>
+#include <dali/public-api/adaptor-framework/widget-application.h>
+
+#include <memory>
+
+namespace Dali
+{
+class Widget;
+
+namespace Internal
+{
+namespace Adaptor
+{
+
+typedef IntrusivePtr<WidgetApplication> WidgetApplicationPtr;
+
+/**
+ * Implementation of the WidgetApplication class.
+ */
+class WidgetApplication : public Application
+{
+public:
+
+ typedef std::pair<const std::string, Dali::WidgetApplication::CreateWidgetFunction > CreateWidgetFunctionPair;
+ typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer;
+
+ /**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet );
+
+public:
+
+ /**
+ * @copydoc Dali::WidgetApplication::RegisterWidgetCreator()
+ */
+ virtual void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction );
+
+protected:
+
+ /**
+ * Private Constructor
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ WidgetApplication( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * Destructor
+ */
+ virtual ~WidgetApplication();
+
+ // Undefined
+ WidgetApplication(const Application&) = delete;
+ WidgetApplication& operator=(Application&) = delete;
+};
+
+inline WidgetApplication& GetImplementation(Dali::WidgetApplication& widgetApplication)
+{
+ DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
+
+ BaseObject& handle = widgetApplication.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::WidgetApplication&>(handle);
+}
+
+inline const WidgetApplication& GetImplementation(const Dali::WidgetApplication& widgetApplication)
+{
+ DALI_ASSERT_ALWAYS(widgetApplication && "widget application handle is empty");
+
+ const BaseObject& handle = widgetApplication.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::WidgetApplication&>(handle);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WIDGET_APPLICATION_IMPL_H
--- /dev/null
+#ifndef DALI_WIDGET_CONTROLLER_H
+#define DALI_WIDGET_CONTROLLER_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/connection-tracker.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/widget-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+/**
+ * @brief Holds the Implementation for the internal WidgetImpl class
+ */
+class Widget::Impl : public Dali::ConnectionTracker
+{
+public:
+
+ /**
+ * Set content information to widget framework
+ */
+ virtual void SetContentInfo( const std::string& contentInfo ) = 0;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_WIDGET_CONTROLLER_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include "widget-impl.h"
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/window.h>
+#include <dali/internal/system/common/widget-controller.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+WidgetPtr Widget::New()
+{
+ return new Widget();
+}
+
+Widget::Widget()
+: mImpl( nullptr )
+{
+}
+
+Widget::~Widget()
+{
+ if( mImpl != nullptr )
+ {
+ delete mImpl;
+ }
+}
+
+void Widget::OnCreate( const std::string& contentInfo, Dali::Window window )
+{
+}
+
+void Widget::OnTerminate( const std::string& contentInfo, Dali::Widget::Termination type )
+{
+}
+
+void Widget::OnPause()
+{
+}
+
+void Widget::OnResume()
+{
+}
+
+void Widget::OnResize( Dali::Window window )
+{
+}
+
+void Widget::OnUpdate( const std::string& contentInfo, int force )
+{
+}
+
+void Widget::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
+{
+ mImpl->SignalConnected( slotObserver, callback );
+}
+
+void Widget::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
+{
+ mImpl->SignalDisconnected( slotObserver, callback );
+}
+
+void Widget::SetContentInfo( const std::string& contentInfo )
+{
+ if( mImpl != nullptr )
+ {
+ mImpl->SetContentInfo( contentInfo );
+ }
+}
+
+void Widget::SetImpl( Impl* impl )
+{
+ mImpl = impl;
+}
+
+Internal::Adaptor::Widget& GetImplementation(Dali::Widget& widget)
+{
+ DALI_ASSERT_ALWAYS(widget && "widget handle is empty");
+
+ BaseObject& handle = widget.GetBaseObject();
+
+ return static_cast<Internal::Adaptor::Widget&>(handle);
+}
+
+const Internal::Adaptor::Widget& GetImplementation(const Dali::Widget& widget)
+{
+ const BaseObject& handle = widget.GetBaseObject();
+
+ return static_cast<const Internal::Adaptor::Widget&>(handle);
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WIDGET_H
+#define DALI_INTERNAL_WIDGET_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+#include <dali/public-api/signals/connection-tracker-interface.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/widget.h>
+
+namespace Dali
+{
+class Window;
+
+/**
+ * @addtogroup dali_adaptor_framework
+ * @{
+ */
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class Widget;
+typedef IntrusivePtr<Widget> WidgetPtr;
+
+/**
+ * @brief This is the internal base class of custom widget.
+ *
+ * It will provides several widget instance lifecycle virtual functions
+ * which the user can override.
+ *
+ * User should override OnCreate function and create scene for custom widget.
+ *
+ * Plus, Implements ConnectionTrackerInterface so that signals (typically connected to member functions) will
+ * be disconnected automatically when the control is destroyed.
+ *
+ * @SINCE_1_3_5
+ */
+class DALI_IMPORT_API Widget : public BaseObject, public ConnectionTrackerInterface
+{
+public:
+
+ /**
+ * @brief Creates a new WidgetImpl instance.
+ *
+ * @SINCE_1_3_5
+ * @return A handle to the WidgetImpl instance
+ */
+ static WidgetPtr New();
+
+ /**
+ * @brief The user should override this function to determine when they create widget.
+ *
+ * @SINCE_1_3_5
+ * @param[in] contentInfo Information from WidgetView for creating. It contains previous status of widget which is sent by SetContentInfo before.
+ * @param[in] window Window handle for widget
+ */
+ virtual void OnCreate( const std::string& contentInfo, Dali::Window window );
+
+ /**
+ * @brief The user should override this function to determine when they terminate widget.
+ *
+ * @SINCE_1_3_5
+ * @param[in] contentInfo Data from WidgetView for deleting
+ * @param[in] type Termination type. When user delete widget view, termination type is PERMANENT.
+ */
+ virtual void OnTerminate( const std::string& contentInfo, Dali::Widget::Termination type );
+
+ /**
+ * @brief The user should override this function to determine when they pause widget.
+ * @SINCE_1_3_5
+ */
+ virtual void OnPause();
+
+ /**
+ * @brief The user should override this function to determine when they resume widget.
+ * @SINCE_1_3_5
+ */
+ virtual void OnResume();
+
+ /**
+ * @brief The user should override this function to determine when they resize widget.
+ *
+ * @SINCE_1_3_5
+ * @param[in] window Window handle for widget
+ */
+ virtual void OnResize( Dali::Window window );
+
+ /**
+ * @brief The user should override this function to determine when they update widget.
+ *
+ * @SINCE_1_3_5
+ * @param[in] contentInfo Data from WidgetView for updating
+ * @param[in] force Although the widget is paused, if it is true, the widget can be updated
+ */
+ virtual void OnUpdate( const std::string& contentInfo, int force );
+
+ // From ConnectionTrackerInterface
+
+ /**
+ * @copydoc ConnectionTrackerInterface::SignalConnected
+ */
+ virtual void SignalConnected( SlotObserver* slotObserver, CallbackBase* callback );
+
+ /**
+ * @copydoc ConnectionTrackerInterface::SignalDisconnected
+ */
+ virtual void SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback );
+
+ /**
+ * @brief Set content info to WidgetView.
+ *
+ * @SINCE_1_3_5
+ * @param[in] contentInfo Content info is kind of context information which contains current status of widget.
+ */
+ void SetContentInfo( const std::string& contentInfo );
+
+protected:
+
+ /**
+ * @brief WidgetImpl constructor
+ */
+ Widget();
+
+ /**
+ * @brief Virtual destructor
+ */
+ virtual ~Widget();
+
+ /// @cond internal
+public:
+ class Impl; // Class declaration is public so we can internally add devel API's to the WidgetImpl
+
+ /*
+ * Set pointer of WidgetImpl Internal.
+ * @SINCE_1_3_5
+ */
+ void SetImpl( Impl* impl );
+
+private:
+ Impl* mImpl;
+
+ // Undefined
+ DALI_INTERNAL Widget(const Widget&);
+ DALI_INTERNAL Widget& operator=(Widget&);
+ /// @endcond
+
+};
+
+/**
+ * @brief Gets implementation from the handle.
+ *
+ * @SINCE_1_3_5
+ * @param handle
+ * @return Implementation
+ * @pre handle is initialized and points to a widget
+ */
+DALI_IMPORT_API Internal::Adaptor::Widget& GetImplementation( Dali::Widget& widget );
+
+/**
+ * @brief Gets implementation from the handle.
+ *
+ * @SINCE_1_3_5
+ * @param handle
+ * @return Implementation
+ * @pre Handle is initialized and points to a widget.
+ */
+DALI_IMPORT_API const Internal::Adaptor::Widget& GetImplementation( const Dali::Widget& widget );
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+/**
+ * @}
+ */
+
+} // namespace Dali
+#endif // DALI_INTERNAL_WIDGET_H
--- /dev/null
+
+
+# module: system, backend: common
+adaptor_system_common_src_files=\
+ ${adaptor_system_dir}/common/abort-handler.cpp \
+ ${adaptor_system_dir}/common/command-line-options.cpp \
+ ${adaptor_system_dir}/common/environment-options.cpp \
+ ${adaptor_system_dir}/common/fps-tracker.cpp \
+ ${adaptor_system_dir}/common/frame-time-stamp.cpp \
+ ${adaptor_system_dir}/common/frame-time-stats.cpp \
+ ${adaptor_system_dir}/common/kernel-trace.cpp \
+ ${adaptor_system_dir}/common/locale-utils.cpp \
+ ${adaptor_system_dir}/common/object-profiler.cpp \
+ ${adaptor_system_dir}/common/performance-interface-factory.cpp \
+ ${adaptor_system_dir}/common/performance-logger-impl.cpp \
+ ${adaptor_system_dir}/common/performance-marker.cpp \
+ ${adaptor_system_dir}/common/performance-server.cpp \
+ ${adaptor_system_dir}/common/shared-file.cpp \
+ ${adaptor_system_dir}/common/singleton-service-impl.cpp \
+ ${adaptor_system_dir}/common/sound-player-impl.cpp \
+ ${adaptor_system_dir}/common/stat-context.cpp \
+ ${adaptor_system_dir}/common/stat-context-manager.cpp \
+ ${adaptor_system_dir}/common/system-trace.cpp \
+ ${adaptor_system_dir}/common/thread-controller.cpp \
+ ${adaptor_system_dir}/common/time-service.cpp \
+ ${adaptor_system_dir}/common/trigger-event.cpp \
+ ${adaptor_system_dir}/common/trigger-event-factory.cpp \
+ ${adaptor_system_dir}/common/update-status-logger.cpp \
+ ${adaptor_system_dir}/common/widget-impl.cpp \
+ ${adaptor_system_dir}/common/widget-application-impl.cpp \
+ ${adaptor_system_dir}/common/logging.cpp \
+ ${adaptor_system_dir}/common/callback-manager-ecore.cpp \
+ ${adaptor_system_dir}/common/file-descriptor-monitor-ecore.cpp \
+ ${adaptor_system_dir}/common/timer-impl-ecore.cpp
+
+# module: system, backend: generic
+adaptor_system_generic_src_files=\
+ ${adaptor_system_dir}/generic/color-controller-impl.cpp \
+ ${adaptor_system_dir}/generic/system-settings.cpp \
+ ${adaptor_system_dir}/tizen/widget-application-impl-tizen.cpp \
+ ${adaptor_system_dir}/tizen/widget-controller-tizen.cpp
+
+# module: system, backend: tizen-ivi
+adaptor_system_tizen_ivi_src_files=\
+ ${adaptor_system_dir}/tizen-ivi/color-controller-impl-ivi.cpp \
+ ${adaptor_system_dir}/tizen-ivi/system-settings-ivi.cpp \
+ ${adaptor_system_dir}/tizen/widget-application-impl-tizen.cpp \
+ ${adaptor_system_dir}/tizen/widget-controller-tizen.cpp
+
+# module: system, backend: tizen-mobile
+adaptor_system_tizen_mobile_src_files=\
+ ${adaptor_system_dir}/tizen-mobile/color-controller-impl-mobile.cpp \
+ ${adaptor_system_dir}/tizen-mobile/system-settings-mobile.cpp \
+ ${adaptor_system_dir}/tizen/widget-application-impl-tizen.cpp \
+ ${adaptor_system_dir}/tizen/widget-controller-tizen.cpp
+
+# module: system, backend: tizen-tv
+adaptor_system_tizen_tv_src_files=\
+ ${adaptor_system_dir}/tizen-tv/color-controller-impl-tv.cpp \
+ ${adaptor_system_dir}/tizen-tv/system-settings-tv.cpp \
+ ${adaptor_system_dir}/tizen/widget-application-impl-tizen.cpp \
+ ${adaptor_system_dir}/tizen/widget-controller-tizen.cpp
+
+# module: system, backend: tizen-wearable
+adaptor_system_tizen_wearable_src_files=\
+ ${adaptor_system_dir}/tizen-wearable/color-controller-impl-wearable.cpp \
+ ${adaptor_system_dir}/tizen-wearable/system-settings-wearable.cpp \
+ ${adaptor_system_dir}/tizen-wearable/watch-time.cpp \
+ ${adaptor_system_dir}/tizen/widget-application-impl-tizen.cpp \
+ ${adaptor_system_dir}/tizen/widget-controller-tizen.cpp
+
+
+# module: system, backend: ubuntu
+adaptor_system_ubuntu_src_files=\
+ ${adaptor_system_dir}/ubuntu/color-controller-impl-ubuntu.cpp \
+ ${adaptor_system_dir}/ubuntu/system-settings-ubuntu.cpp \
+ ${adaptor_system_dir}/ubuntu/widget-application-impl-ubuntu.cpp \
+ ${adaptor_system_dir}/ubuntu/widget-controller-ubuntu.cpp
+
+# module: system, backend: ubuntu-x11
+adaptor_system_ubuntu_x11_src_files=\
+ ${adaptor_system_dir}/ubuntu-x11/system-settings-x.cpp
+
+
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ return Dali::ColorController( new ColorController() );
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_COLOR_CONTROLLER_H__
+#define __DALI_INTERNAL_COLOR_CONTROLLER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/color-controller.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of ColorController
+ */
+class ColorController : public BaseObject
+{
+public:
+
+ /**
+ * Constructor.
+ */
+ ColorController();
+
+ /**
+ * @copydoc Dali::ColorController::Get()
+ */
+ static Dali::ColorController Get();
+
+ /**
+ * @copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&)
+ */
+ bool RetrieveColor( const std::string& colorCode, Vector4& colorValue );
+
+ /**
+ *copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&, Vector4&, Vector4&)
+ */
+ bool RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor);
+
+protected:
+ /**
+ * Destructor.
+ */
+ virtual ~ColorController();
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+// Additional Helpers for public-api forwarding methods
+inline Internal::Adaptor::ColorController& GetImplementation(Dali::ColorController& controller)
+{
+ DALI_ASSERT_ALWAYS(controller && "ColorController handle is empty");
+ BaseObject& handle = controller.GetBaseObject();
+ return static_cast<Internal::Adaptor::ColorController&>(handle);
+}
+
+inline const Internal::Adaptor::ColorController& GetImplementation(const Dali::ColorController& controller)
+{
+ DALI_ASSERT_ALWAYS(controller && "ColorController handle is empty");
+ const BaseObject& handle = controller.GetBaseObject();
+ return static_cast<const Internal::Adaptor::ColorController&>(handle);
+}
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_COLOR_CONTROLLER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetLongPressTime( int defaultTime )
+{
+ return defaultTime;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ Dali::ColorController colorController;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ColorController ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ colorController = Dali::ColorController( dynamic_cast< ColorController* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ colorController = Dali::ColorController( new ColorController( ) );
+ service.Register( typeid( colorController ), colorController );
+ }
+ }
+
+ return colorController;
+
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <system_settings.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetLongPressTime( int defaultTime )
+{
+ return defaultTime;
+}
+
+int GetElmAccessActionOver()
+{
+ return 0;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ Dali::ColorController colorController;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ColorController ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ colorController = Dali::ColorController( dynamic_cast< ColorController* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ colorController = Dali::ColorController( new ColorController( ) );
+ service.Register( typeid( colorController ), colorController );
+ }
+ }
+
+ return colorController;
+
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <system_settings.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetLongPressTime( int defaultTime )
+{
+ return defaultTime;
+}
+
+int GetElmAccessActionOver()
+{
+ return 0;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ Dali::ColorController colorController;
+ return colorController;
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ Dali::ColorController colorController;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ColorController ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ colorController = Dali::ColorController( dynamic_cast< ColorController* >( handle.GetObjectPtr() ) );
+ }
+ else
+ {
+ colorController = Dali::ColorController( new ColorController( ) );
+ service.Register( typeid( colorController ), colorController );
+ }
+ }
+
+ return colorController;
+
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <system_settings.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetLongPressTime( int defaultTime )
+{
+ return defaultTime;
+}
+
+int GetElmAccessActionOver()
+{
+ return 0;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/watch/watch-time.h>
+
+// EXTERNAL INCLUDES
+#ifdef APPCORE_WATCH_AVAILABLE
+#include <watch_app.h>
+#include <watch_app_extension.h>
+#endif
+
+namespace Dali
+{
+
+struct WatchTime::Impl
+{
+ Impl(void *time_handle)
+ : mTimeHandle(time_handle)
+ {
+ }
+
+ void *mTimeHandle;
+};
+
+WatchTime::WatchTime(void *time_handle)
+{
+ mImpl = new Impl(time_handle);
+}
+
+WatchTime::~WatchTime()
+{
+ if( mImpl )
+ {
+ delete mImpl;
+ mImpl = NULL;
+ }
+}
+
+#ifdef APPCORE_WATCH_AVAILABLE
+
+WatchTime::WatchTime()
+{
+ watch_time_h watch_time = {0,};
+
+ watch_time_get_current_time(&watch_time);
+ mImpl = new Impl(watch_time);
+}
+
+int WatchTime::GetHour() const
+{
+ int hour;
+
+ watch_time_get_hour(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &hour);
+ return hour;
+}
+
+int WatchTime::GetHour24() const
+{
+ int hour24;
+
+ watch_time_get_hour24(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &hour24);
+ return hour24;
+}
+
+int WatchTime::GetMinute() const
+{
+ int minute;
+
+ watch_time_get_minute(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &minute);
+ return minute;
+}
+
+int WatchTime::GetSecond() const
+{
+ int second;
+
+ watch_time_get_second(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &second);
+ return second;
+}
+
+int WatchTime::GetMillisecond() const
+{
+ int millisecond;
+
+ watch_time_get_millisecond(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &millisecond);
+ return millisecond;
+}
+
+int WatchTime::GetYear() const
+{
+ int year;
+
+ watch_time_get_year(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &year);
+ return year;
+}
+
+int WatchTime::GetMonth() const
+{
+ int month;
+
+ watch_time_get_month(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &month);
+ return month;
+}
+
+int WatchTime::GetDay() const
+{
+ int day;
+
+ watch_time_get_day(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &day);
+ return day;
+}
+
+int WatchTime::GetDayOfWeek() const
+{
+ int dayOfWeek;
+
+ watch_time_get_day_of_week(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &dayOfWeek);
+ return dayOfWeek;
+}
+
+struct tm WatchTime::GetUtcTime() const
+{
+ struct tm UtcTime;
+
+ watch_time_get_utc_time(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &UtcTime);
+ return UtcTime;
+}
+
+time_t WatchTime::GetUtcTimeStamp() const
+{
+ time_t UtcTimeStamp;
+
+ watch_time_get_utc_timestamp(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &UtcTimeStamp);
+ return UtcTimeStamp;
+}
+
+const char* WatchTime::GetTimeZone() const
+{
+ char* timeZone;
+
+ watch_time_get_time_zone(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &timeZone);
+ return timeZone;
+}
+
+bool WatchTime::GetDaylightSavingTimeStatus() const
+{
+ bool daylight;
+
+ watch_time_get_daylight_time_status(reinterpret_cast<watch_time_h>(mImpl->mTimeHandle), &daylight);
+ return daylight;
+}
+
+#else
+WatchTime::WatchTime()
+ :mImpl(NULL)
+{
+}
+
+int WatchTime::GetHour() const
+{
+ return 0;
+}
+
+int WatchTime::GetHour24() const
+{
+ return 0;
+}
+
+int WatchTime::GetMinute() const
+{
+ return 0;
+}
+
+int WatchTime::GetSecond() const
+{
+ return 0;
+}
+
+int WatchTime::GetMillisecond() const
+{
+ return 0;
+}
+
+int WatchTime::GetYear() const
+{
+ return 0;
+}
+
+int WatchTime::GetMonth() const
+{
+ return 0;
+}
+
+int WatchTime::GetDay() const
+{
+ return 0;
+}
+
+int WatchTime::GetDayOfWeek() const
+{
+ return 0;
+}
+
+struct tm WatchTime::GetUtcTime() const
+{
+ time_t zero = time(0);
+ return *localtime(&zero);
+}
+
+time_t WatchTime::GetUtcTimeStamp() const
+{
+ return 0;
+}
+
+const char* WatchTime::GetTimeZone() const
+{
+ return 0;
+}
+
+bool WatchTime::GetDaylightSavingTimeStatus() const
+{
+ return 0;
+}
+
+#endif
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/tizen/widget-application-impl-tizen.h>
+
+// INTERNAL INCLUDE
+#include <dali/public-api/adaptor-framework/widget.h>
+#include <dali/internal/system/common/widget-impl.h>
+#include <dali/internal/system/tizen/widget-controller-tizen.h>
+
+#ifdef WIDGET_SUPPOERTED
+#include <bundle.h>
+#include <widget_base.h>
+#endif
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+#ifdef WIDGET_SUPPOERTED
+namespace
+{
+
+int OnInstanceInit(widget_base_instance_h instanceHandle, bundle *content, int w, int h, void *classData)
+{
+ char *id;
+ widget_base_context_get_id(instanceHandle, &id);
+
+ widget_base_class_on_create(instanceHandle, content, w, h);
+
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // After DALi can support multi window, this part should be changed.
+ Dali::Window window = application->GetWindow();
+ window.ShowIndicator(Dali::Window::INVISIBLE);
+ Any nativeHandle = window.GetNativeHandle();
+ Ecore_Wl_Window * wlWindow = AnyCast<Ecore_Wl_Window*>( nativeHandle );
+ widget_base_context_window_bind( instanceHandle, id, wlWindow );
+ window.SetSize( Dali::Window::WindowSize( w, h ) );
+
+ Dali::Internal::Adaptor::WidgetApplication::CreateWidgetFunctionPair pair = application->GetWidgetCreatingFunctionPair(std::string(id));
+ Dali::WidgetApplication::CreateWidgetFunction createFunction = pair.second;
+
+ Dali::Widget widgetInstance = createFunction( pair.first );
+ application->AddWidget( instanceHandle, widgetInstance );
+
+ Dali::Internal::Adaptor::Widget::Impl *widgetImpl = new Dali::Internal::Adaptor::WidgetImplTizen(instanceHandle);
+ Internal::Adaptor::GetImplementation(widgetInstance).SetImpl( widgetImpl );
+
+ std::string encodedContentString = "";
+
+ if( bundle_get_count( content ) )
+ {
+ bundle_raw *bundleRaw;
+ int len;
+ bundle_encode(content, &bundleRaw, &len);
+ char* encodedContent = reinterpret_cast< char* >( bundleRaw );
+ encodedContentString = std::string( encodedContent );
+ free(bundleRaw);
+ }
+
+ Internal::Adaptor::GetImplementation(widgetInstance).OnCreate( encodedContentString, window );
+
+ return 0;
+}
+
+int OnInstanceDestroy(widget_base_instance_h instanceHandle, widget_base_destroy_type_e reason, bundle *content, void *classData)
+{
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // Get Dali::Widget instance.
+ Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
+
+ Dali::Widget::Termination destroyReason = Dali::Widget::Termination::TEMPORARY;
+
+ if(reason == WIDGET_BASE_DESTROY_TYPE_PERMANENT)
+ {
+ destroyReason = Dali::Widget::Termination::PERMANENT;
+ }
+
+ std::string encodedContentString = "";
+
+ if( bundle_get_count( content ) )
+ {
+ bundle_raw *bundleRaw;
+ int len;
+ bundle_encode(content, &bundleRaw, &len);
+ char* encodedContent = reinterpret_cast< char* >( bundleRaw );
+ encodedContentString = std::string(encodedContent);
+ free(bundleRaw);
+ }
+
+ Internal::Adaptor::GetImplementation(widgetInstance).OnTerminate( encodedContentString, destroyReason );
+
+ widget_base_class_on_destroy(instanceHandle, reason, content);
+
+ application->DeleteWidget( instanceHandle );
+
+ return 0;
+}
+
+int OnInstancePause(widget_base_instance_h instanceHandle, void *classData)
+{
+ widget_base_class_on_pause(instanceHandle);
+
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // Get Dali::Widget instance.
+ Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
+
+ Internal::Adaptor::GetImplementation(widgetInstance).OnPause();
+
+ return 0;
+}
+
+int OnInstanceResume(widget_base_instance_h instanceHandle, void *classData)
+{
+ widget_base_class_on_resume(instanceHandle);
+
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // Get Dali::Widget instance.
+ Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
+
+ Internal::Adaptor::GetImplementation(widgetInstance).OnResume();
+
+ return 0;
+}
+
+int OnInstanceResize(widget_base_instance_h instanceHandle, int w, int h, void *classData)
+{
+ widget_base_class_on_resize(instanceHandle, w, h);
+
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // Get Dali::Widget instance.
+ Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
+
+ Dali::Window window = application->GetWindow();
+ window.SetSize( Dali::Window::WindowSize(w, h) );
+ Internal::Adaptor::GetImplementation(widgetInstance).OnResize(window);
+
+ return 0;
+}
+
+int OnInstanceUpdate(widget_base_instance_h instanceHandle, bundle *content, int force, void *classData)
+{
+ widget_base_class_on_update(instanceHandle, content, force);
+
+ Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast<Dali::Internal::Adaptor::WidgetApplicationTizen*>(classData);
+
+ // Get Dali::Widget instance.
+ Dali::Widget widgetInstance = application->GetWidget( instanceHandle );
+
+ std::string encodedContentString = "";
+
+ if( bundle_get_count( content ) )
+ {
+ bundle_raw *bundleRaw;
+ int len;
+ bundle_encode(content, &bundleRaw, &len);
+ char* encodedContent = reinterpret_cast< char* >( bundleRaw );
+ encodedContentString = std::string(encodedContent);
+ free(bundleRaw);
+ }
+
+ Internal::Adaptor::GetImplementation(widgetInstance).OnUpdate( encodedContentString, force );
+
+ return 0;
+}
+
+} // anonymous namespace
+
+#endif
+
+namespace Adaptor
+{
+
+#ifdef WIDGET_SUPPOERTED
+
+WidgetApplicationPtr WidgetApplicationTizen::New(
+ int* argc,
+ char **argv[],
+ const std::string& stylesheet)
+{
+ return new WidgetApplicationTizen(argc, argv, stylesheet );
+}
+
+WidgetApplicationTizen::WidgetApplicationTizen( int* argc, char** argv[], const std::string& stylesheet )
+:WidgetApplication(argc, argv, stylesheet)
+{
+}
+
+WidgetApplicationTizen::~WidgetApplicationTizen()
+{
+}
+
+
+void WidgetApplicationTizen::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
+{
+ AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair(widgetName, createFunction) );
+
+ // Register widget class to widget framework
+ widget_base_class cls = widget_base_class_get_default();
+ cls.ops.create = OnInstanceInit;
+ cls.ops.destroy = OnInstanceDestroy;
+ cls.ops.pause = OnInstancePause;
+ cls.ops.resume = OnInstanceResume;
+ cls.ops.resize = OnInstanceResize;
+ cls.ops.update = OnInstanceUpdate;
+
+ widget_base_class_add(cls, widgetName.c_str(), this);
+}
+
+void WidgetApplicationTizen::AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair )
+{
+ mCreateWidgetFunctionContainer.push_back( pair );
+}
+
+WidgetApplicationTizen::CreateWidgetFunctionPair WidgetApplicationTizen::GetWidgetCreatingFunctionPair( const std::string& widgetName )
+{
+ for( CreateWidgetFunctionContainer::const_iterator iter = mCreateWidgetFunctionContainer.begin(); iter != mCreateWidgetFunctionContainer.end(); ++iter )
+ {
+ if( widgetName.find((*iter).first) != std::string::npos )
+ {
+ return *iter;
+ }
+ }
+
+ return CreateWidgetFunctionPair( "", NULL );
+}
+
+void WidgetApplicationTizen::AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget )
+{
+ mWidgetInstanceContainer.push_back( WidgetInstancePair(widgetBaseInstance, widget) );
+}
+
+Dali::Widget WidgetApplicationTizen::GetWidget( widget_base_instance_h widgetBaseInstance )
+{
+ for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
+ {
+ if( (*iter).first == widgetBaseInstance )
+ {
+ return (*iter).second;
+ }
+ }
+ return Dali::Widget();
+}
+
+void WidgetApplicationTizen::DeleteWidget( widget_base_instance_h widgetBaseInstance )
+{
+ for( WidgetInstanceContainer::const_iterator iter = mWidgetInstanceContainer.begin(); iter != mWidgetInstanceContainer.end(); ++iter )
+ {
+ if( (*iter).first == widgetBaseInstance )
+ {
+ mWidgetInstanceContainer.erase(iter);
+ break;
+ }
+ }
+}
+
+#endif
+
+// factory function, must be implemented
+namespace WidgetApplicationFactory
+{
+/**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+Dali::Internal::Adaptor::WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet )
+{
+#ifdef WIDGET_SUPPOERTED
+ return WidgetApplicationTizen::New( argc, argv, stylesheet );
+#else
+ return nullptr;
+#endif
+}
+
+} // namespace Factory
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
--- /dev/null
+#ifndef DALI_INTERNAL_WIDGET_APPLICATION_TIZEN_H
+#define DALI_INTERNAL_WIDGET_APPLICATION_TIZEN_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#ifdef WIDGET_SUPPOERTED
+#include <widget_base.h>
+#endif
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/application-impl.h>
+#include <dali/internal/system/common/widget-application-impl.h>
+
+#ifndef WIDGET_SUPPOERTED
+typedef void* widget_base_instance_h;
+#endif
+
+namespace Dali
+{
+class Widget;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class WidgetApplication;
+typedef IntrusivePtr<WidgetApplication> WidgetApplicationPtr;
+
+/**
+ * Implementation of the WidgetApplication class.
+ */
+class WidgetApplicationTizen : public WidgetApplication
+{
+public:
+
+ typedef std::pair<const std::string, Dali::WidgetApplication::CreateWidgetFunction > CreateWidgetFunctionPair;
+ typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer;
+
+ /**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet );
+
+public:
+
+ /**
+ * @copydoc Dali::WidgetApplication::RegisterWidgetCreator()
+ */
+ void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override;
+
+ /**
+ * Add widget name - CreateWidgetFunction pair to container.
+ */
+ void AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair );
+
+ /**
+ * Find and get CreateWidgetFunctionPair in container by widget name.
+ */
+ CreateWidgetFunctionPair GetWidgetCreatingFunctionPair( const std::string& widgetName );
+
+ /**
+ * Add widget_base_instance_h - Widget instance pair to container.
+ */
+ void AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget );
+
+ /**
+ * Find and get Widget instance in container by widget_base_instance_h.
+ */
+ Dali::Widget GetWidget( widget_base_instance_h widgetBaseInstance );
+
+ /**
+ * Delete widget_base_instance_h - Widget instance pair in container.
+ */
+ void DeleteWidget( widget_base_instance_h widgetBaseInstance );
+
+protected:
+
+ /**
+ * Private Constructor
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ WidgetApplicationTizen( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * Destructor
+ */
+ virtual ~WidgetApplicationTizen();
+
+ WidgetApplicationTizen(const Application&) = delete;
+ WidgetApplicationTizen& operator=(Application&) = delete;
+
+private:
+
+ typedef std::pair< widget_base_instance_h, Dali::Widget > WidgetInstancePair;
+ typedef std::vector< WidgetInstancePair > WidgetInstanceContainer;
+
+ CreateWidgetFunctionContainer mCreateWidgetFunctionContainer;
+ WidgetInstanceContainer mWidgetInstanceContainer;
+
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WIDGET_APPLICATION_TIZEN_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/tizen/widget-controller-tizen.h>
+
+// EXTERNAL INCLUDES
+#include <bundle.h>
+#include <widget_base.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+WidgetImplTizen::WidgetImplTizen( widget_base_instance_h instanceHandle )
+: Widget::Impl(), mInstanceHandle( instanceHandle )
+{
+}
+
+WidgetImplTizen::~WidgetImplTizen()
+{
+}
+
+void WidgetImplTizen::SetContentInfo( const std::string& contentInfo )
+{
+ bundle *contentBundle;
+ bundle_raw *contentBundleRaw = reinterpret_cast< bundle_raw* >( const_cast<char*>(contentInfo.c_str()) );
+ int len = contentInfo.length();
+ contentBundle = bundle_decode(contentBundleRaw, len);
+
+ widget_base_context_set_content_info( mInstanceHandle, contentBundle );
+
+ bundle_free( contentBundle );
+}
+
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_WIDGET_CONTROLLER_TIZEN_H
+#define DALI_WIDGET_CONTROLLER_TIZEN_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/connection-tracker.h>
+
+// INTERNAL INCLUDES
+#ifdef WIDGET_SUPPOERTED
+#include <widget_base.h>
+#endif
+#include <dali/internal/system/common/widget-impl.h>
+#include <dali/internal/system/common/widget-controller.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * @brief Holds the Implementation for the internal WidgetImpl class
+ */
+class WidgetImplTizen : public Widget::Impl
+{
+public:
+
+#ifndef WIDGET_SUPPOERTED
+ typedef void* widget_base_instance_h;
+#endif
+
+ /**
+ * Constructor
+ */
+ WidgetImplTizen( widget_base_instance_h instanceHandle );
+
+ /**
+ * Destructor
+ */
+ ~WidgetImplTizen() override;
+
+public:
+
+ /**
+ * Set content information to widget framework
+ */
+ void SetContentInfo( const std::string& contentInfo ) override;
+
+private:
+
+ widget_base_instance_h mInstanceHandle;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_WIDGET_CONTROLLER_TIZEN_H
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#ifndef DALI_PROFILE_UBUNTU
+#include <system_settings.h>
+#endif // DALI_PROFILE_UBUNTU
+#include <Elementary.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetElmAccessActionOver()
+{
+#ifndef DALI_PROFILE_UBUNTU
+ // ELM_ACCESS_ACTION_OVER not available in common profile
+ return ELM_ACCESS_ACTION_LAST;
+#else // DALI_PROFILE_UBUNTU
+ return 0;
+#endif // DALI_PROFILE_UBUNTU
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/generic/color-controller-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+Dali::ColorController ColorController::Get()
+{
+ return Dali::ColorController( new ColorController() );
+}
+
+ColorController::ColorController()
+{
+}
+
+ColorController::~ColorController()
+{
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
+{
+ return false;
+}
+
+bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
+{
+ return false;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/generic/system-settings.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+int GetLongPressTime( int defaultTime )
+{
+ return defaultTime;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/ubuntu/widget-application-impl-ubuntu.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+WidgetApplicationPtr WidgetApplicationUbuntu::New(
+ int* argc,
+ char **argv[],
+ const std::string& stylesheet)
+{
+ return new WidgetApplicationUbuntu(argc, argv, stylesheet );
+}
+
+WidgetApplicationUbuntu::WidgetApplicationUbuntu( int* argc, char** argv[], const std::string& stylesheet )
+: WidgetApplication(argc, argv, stylesheet)
+{
+ DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n");
+}
+
+WidgetApplicationUbuntu::~WidgetApplicationUbuntu()
+{
+}
+
+
+void WidgetApplicationUbuntu::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction )
+{
+}
+
+// factory function, must be implemented
+namespace WidgetApplicationFactory
+{
+/**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet )
+{
+ return WidgetApplicationUbuntu::New( argc, argv, stylesheet );
+}
+
+} // namespace Factory
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WIDGET_APPLICATION_IMPL_UBUNTU_H
+#define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_UBUNTU_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/application-impl.h>
+#include <dali/internal/system/common//widget-application-impl.h>
+#include <dali/public-api/adaptor-framework/widget-application.h>
+
+namespace Dali
+{
+class Widget;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * Implementation of the WidgetApplicationUbuntu class.
+ */
+class WidgetApplicationUbuntu : public WidgetApplication
+{
+public:
+
+ typedef std::pair<const std::string, Dali::WidgetApplication::CreateWidgetFunction > CreateWidgetFunctionPair;
+ typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer;
+
+ /**
+ * Create a new widget application
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet );
+
+public:
+
+ /**
+ * @copydoc Dali::WidgetApplication::RegisterWidgetCreator()
+ */
+ void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override;
+
+protected:
+
+ /**
+ * Private Constructor
+ * @param[in] argc A pointer to the number of arguments
+ * @param[in] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ */
+ WidgetApplicationUbuntu( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * Destructor
+ */
+ virtual ~WidgetApplicationUbuntu();
+
+ WidgetApplicationUbuntu(const Application&) = delete;
+ WidgetApplicationUbuntu& operator=(Application&) = delete;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WIDGET_APPLICATION_IMPL_UBUNTU_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/system/ubuntu/widget-controller-ubuntu.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+WidgetImplUbuntu::WidgetImplUbuntu()
+{
+}
+
+WidgetImplUbuntu::~WidgetImplUbuntu()
+{
+}
+
+void WidgetImplUbuntu::SetContentInfo( const std::string& contentInfo )
+{
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_WIDGET_CONTROLLER_UBUNTU_H
+#define DALI_WIDGET_CONTROLLER_UBUNTU_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/signals/connection-tracker.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/widget-controller.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+/**
+ * @brief Holds the Implementation for the internal WidgetImpl class
+ */
+class WidgetImplUbuntu : public Widget::Impl
+{
+public:
+
+ /**
+ * Constructor
+ */
+ WidgetImplUbuntu();
+
+ /**
+ * Destructor
+ */
+ ~WidgetImplUbuntu() override;
+
+public:
+
+ /**
+ * Set content information to widget framework
+ */
+ void SetContentInfo( const std::string& contentInfo ) override;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_WIDGET_CONTROLLER_UBUNTU_H
--- /dev/null
+
+
+# module: text, backend: common
+adaptor_text_common_src_files=\
+ ${adaptor_text_dir}/text-abstraction/bidirectional-support-impl.cpp \
+ ${adaptor_text_dir}/text-abstraction/font-client-helper.cpp \
+ ${adaptor_text_dir}/text-abstraction/font-client-impl.cpp \
+ ${adaptor_text_dir}/text-abstraction/font-client-plugin-impl.cpp \
+ ${adaptor_text_dir}/text-abstraction/segmentation-impl.cpp \
+ ${adaptor_text_dir}/text-abstraction/shaping-impl.cpp
+
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/bidirectional-support-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+// EXTERNAL INCLUDES
+#include <memory.h>
+#include <fribidi/fribidi.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+namespace
+{
+ typedef unsigned char BidiDirection;
+
+ // Internal charcter's direction.
+ const BidiDirection LEFT_TO_RIGHT = 0u;
+ const BidiDirection NEUTRAL = 1u;
+ const BidiDirection RIGHT_TO_LEFT = 2u;
+
+ /**
+ * @param[in] paragraphDirection The FriBiDi paragraph's direction.
+ *
+ * @return Whether the paragraph is right to left.
+ */
+ bool GetBidiParagraphDirection( FriBidiParType paragraphDirection )
+ {
+ switch( paragraphDirection )
+ {
+ case FRIBIDI_PAR_RTL: // Right-To-Left paragraph.
+ case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph.
+ {
+ return true;
+ }
+ case FRIBIDI_PAR_LTR: // Left-To-Right paragraph.
+ case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph.
+ case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph.
+ {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection )
+ {
+ switch( characterDirection )
+ {
+ case FRIBIDI_TYPE_LTR: // Left-To-Right letter.
+ case FRIBIDI_TYPE_EN: // European Numeral.
+ case FRIBIDI_TYPE_AN: // Arabic Numeral.
+ case FRIBIDI_TYPE_ES: // European number Separator.
+ case FRIBIDI_TYPE_ET: // European number Terminator.
+ {
+ return LEFT_TO_RIGHT;
+ }
+ case FRIBIDI_TYPE_RTL: // Right-To-Left letter.
+ case FRIBIDI_TYPE_AL: // Arabic Letter.
+ {
+ return RIGHT_TO_LEFT;
+ }
+ }
+
+ return NEUTRAL;
+ }
+}
+
+struct BidirectionalSupport::Plugin
+{
+ /**
+ * Stores bidirectional info per paragraph.
+ */
+ struct BidirectionalInfo
+ {
+ FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...)
+ FriBidiLevel* embeddedLevels; ///< Embedded levels.
+ FriBidiParType paragraphDirection; ///< The paragraph's direction.
+ };
+
+ Plugin()
+ : mParagraphBidirectionalInfo(),
+ mFreeIndices()
+ {}
+
+ ~Plugin()
+ {
+ // free all resources.
+ for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(),
+ endIt = mParagraphBidirectionalInfo.End();
+ it != endIt;
+ ++it )
+ {
+ BidirectionalInfo* info = *it;
+
+ free( info->embeddedLevels );
+ free( info->characterTypes );
+ delete info;
+ }
+ }
+
+ BidiInfoIndex CreateInfo( const Character* const paragraph,
+ Length numberOfCharacters )
+ {
+ // Reserve memory for the paragraph's bidirectional info.
+ BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo();
+
+ bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) );
+ if( !bidirectionalInfo->characterTypes )
+ {
+ delete bidirectionalInfo;
+ return 0;
+ }
+
+ bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) );
+ if( !bidirectionalInfo->embeddedLevels )
+ {
+ free( bidirectionalInfo->characterTypes );
+ delete bidirectionalInfo;
+ return 0;
+ }
+
+ // Retrieve the type of each character..
+ fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes );
+
+ // Retrieve the paragraph's direction.
+ bidirectionalInfo->paragraphDirection = fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters );
+
+ // Retrieve the embedding levels.
+ fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels );
+
+ // Store the bidirectional info and return the index.
+ BidiInfoIndex index = 0u;
+ if( 0u != mFreeIndices.Count() )
+ {
+ Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u;
+
+ index = *it;
+
+ mFreeIndices.Remove( it );
+
+ *( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo;
+ }
+ else
+ {
+ index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() );
+
+ mParagraphBidirectionalInfo.PushBack( bidirectionalInfo );
+ }
+
+ return index;
+ }
+
+ void DestroyInfo( BidiInfoIndex bidiInfoIndex )
+ {
+ if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() )
+ {
+ return;
+ }
+
+ // Retrieve the paragraph's bidirectional info.
+ Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex;
+ BidirectionalInfo* bidirectionalInfo = *it;
+
+ if( NULL != bidirectionalInfo )
+ {
+ // Free resources and destroy the container.
+ free( bidirectionalInfo->embeddedLevels );
+ free( bidirectionalInfo->characterTypes );
+ delete bidirectionalInfo;
+
+ *it = NULL;
+ }
+
+ // Add the index to the free indices vector.
+ mFreeIndices.PushBack( bidiInfoIndex );
+ }
+
+ void Reorder( BidiInfoIndex bidiInfoIndex,
+ CharacterIndex firstCharacterIndex,
+ Length numberOfCharacters,
+ CharacterIndex* visualToLogicalMap )
+ {
+ const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC;
+
+ // Retrieve the paragraph's bidirectional info.
+ const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
+
+ // Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table.
+ for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
+ {
+ visualToLogicalMap[ index ] = index;
+ }
+
+ // Copy embedded levels as fribidi_reorder_line() may change them.
+ const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel );
+ FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) );
+ if( embeddedLevels )
+ {
+ memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize );
+
+ // Reorder the line.
+ fribidi_reorder_line( flags,
+ bidirectionalInfo->characterTypes + firstCharacterIndex,
+ numberOfCharacters,
+ 0u,
+ bidirectionalInfo->paragraphDirection,
+ embeddedLevels,
+ NULL,
+ reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) );
+
+ // Free resources.
+ free( embeddedLevels );
+ }
+ }
+
+ bool GetMirroredText( Character* text,
+ CharacterDirection* directions,
+ Length numberOfCharacters ) const
+ {
+ bool updated = false;
+
+ for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
+ {
+ // Get a reference to the character inside the text.
+ Character& character = *( text + index );
+
+ // Retrieve the mirrored character.
+ FriBidiChar mirroredCharacter = character;
+ bool mirrored = false;
+ if( *( directions + index ) )
+ {
+ mirrored = fribidi_get_mirror_char( character, &mirroredCharacter );
+ }
+ updated = updated || mirrored;
+
+ // Update the character inside the text.
+ character = mirroredCharacter;
+ }
+
+ return updated;
+ }
+
+ bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
+ {
+ // Retrieve the paragraph's bidirectional info.
+ const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
+
+ return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
+ }
+
+ void GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
+ CharacterDirection* directions,
+ Length numberOfCharacters )
+ {
+ const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
+
+ const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
+ CharacterDirection previousDirection = paragraphDirection;
+
+ for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
+ {
+ CharacterDirection& characterDirection = *( directions + index );
+ characterDirection = false;
+
+ // Get the bidi direction.
+ const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) );
+
+ if( RIGHT_TO_LEFT == bidiDirection )
+ {
+ characterDirection = true;
+ }
+ else if( NEUTRAL == bidiDirection )
+ {
+ // For neutral characters it check's the next and previous directions.
+ // If they are equals set that direction. If they are not, sets the paragraph's direction.
+ // If there is no next, sets the paragraph's direction.
+
+ CharacterDirection nextDirection = paragraphDirection;
+
+ // Look for the next non-neutral character.
+ Length nextIndex = index + 1u;
+ for( ; nextIndex < numberOfCharacters; ++nextIndex )
+ {
+ BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) );
+ if( nextBidiDirection != NEUTRAL )
+ {
+ nextDirection = RIGHT_TO_LEFT == nextBidiDirection;
+ break;
+ }
+ }
+
+ // Calculate the direction for all the neutral characters.
+ characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection;
+
+ // Set the direction to all the neutral characters.
+ ++index;
+ for( ; index < nextIndex; ++index )
+ {
+ CharacterDirection& nextCharacterDirection = *( directions + index );
+ nextCharacterDirection = characterDirection;
+ }
+
+ // Set the direction of the next non-neutral character.
+ if( nextIndex < numberOfCharacters )
+ {
+ *( directions + nextIndex ) = nextDirection;
+ }
+ }
+
+ previousDirection = characterDirection;
+ }
+ }
+
+ Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph.
+ Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector.
+};
+
+BidirectionalSupport::BidirectionalSupport()
+: mPlugin( NULL )
+{
+}
+
+BidirectionalSupport::~BidirectionalSupport()
+{
+ delete mPlugin;
+}
+
+TextAbstraction::BidirectionalSupport BidirectionalSupport::Get()
+{
+ TextAbstraction::BidirectionalSupport bidirectionalSupportHandle;
+
+ SingletonService service( SingletonService::Get() );
+ if( service )
+ {
+ // Check whether the singleton is already created
+ BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() );
+ bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl );
+ }
+ else // create and register the object
+ {
+ bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport );
+ service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle );
+ }
+ }
+
+ return bidirectionalSupportHandle;
+}
+
+BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
+ Length numberOfCharacters )
+{
+ CreatePlugin();
+
+ return mPlugin->CreateInfo( paragraph,
+ numberOfCharacters );
+}
+
+void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
+{
+ CreatePlugin();
+
+ mPlugin->DestroyInfo( bidiInfoIndex );
+}
+
+void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
+ CharacterIndex firstCharacterIndex,
+ Length numberOfCharacters,
+ CharacterIndex* visualToLogicalMap )
+{
+ CreatePlugin();
+
+ mPlugin->Reorder( bidiInfoIndex,
+ firstCharacterIndex,
+ numberOfCharacters,
+ visualToLogicalMap );
+}
+
+bool BidirectionalSupport::GetMirroredText( Character* text,
+ CharacterDirection* directions,
+ Length numberOfCharacters )
+{
+ CreatePlugin();
+
+ return mPlugin->GetMirroredText( text, directions, numberOfCharacters );
+}
+
+bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
+{
+ if( !mPlugin )
+ {
+ return false;
+ }
+
+ return mPlugin->GetParagraphDirection( bidiInfoIndex );
+}
+
+void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
+ CharacterDirection* directions,
+ Length numberOfCharacters )
+{
+ CreatePlugin();
+
+ mPlugin->GetCharactersDirection( bidiInfoIndex,
+ directions,
+ numberOfCharacters );
+}
+
+void BidirectionalSupport::CreatePlugin()
+{
+ if( !mPlugin )
+ {
+ mPlugin = new Plugin();
+ }
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/font-client-helper.h>
+
+// INTERNAL INCLUDES
+
+#include <dali/integration-api/debug.h>
+
+namespace
+{
+#if defined(DEBUG_ENABLED)
+Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT_VALUE_TO_INDEX");
+#endif
+}
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+int ValueToIndex( int value, const int* const table, unsigned int maxIndex )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->FontClient::Plugin::ValueToIndex value(%d)\n", value);
+
+ if( NULL == table )
+ {
+ // Return an invalid index if there is no table.
+ return -1;
+ }
+
+ if( value <= table[0] )
+ {
+ return 0;
+ }
+
+ if( value >= table[maxIndex] )
+ {
+ return maxIndex;
+ }
+
+ for( unsigned int index = 0u; index < maxIndex; ++index )
+ {
+ const int v1 = table[index];
+ const unsigned int indexPlus = index + 1u;
+ const int v2 = table[indexPlus];
+ if( ( v1 < value ) && ( value <= v2 ) )
+ {
+ const int result = ( ( v1 > 0 ) && ( ( value - v1 ) < ( v2 - value ) ) ) ? index : indexPlus;
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex result(%d)\n", result );
+ return result;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex exit 0 <-- \n");
+
+ return 0;
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/font-client-impl.h>
+
+// EXTERNAL INCLUDES
+#ifndef DALI_PROFILE_UBUNTU
+#include <vconf.h>
+#endif
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/singleton-service.h>
+#include <dali/internal/text/text-abstraction/font-client-plugin-impl.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+FontClient::FontClient()
+: mPlugin( NULL ),
+ mDpiHorizontal( 0 ),
+ mDpiVertical( 0 )
+{
+}
+
+FontClient::~FontClient()
+{
+ delete mPlugin;
+}
+
+Dali::TextAbstraction::FontClient FontClient::Get()
+{
+ Dali::TextAbstraction::FontClient fontClientHandle;
+
+ Dali::SingletonService service( SingletonService::Get() );
+ if ( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::TextAbstraction::FontClient ) );
+ if(handle)
+ {
+ // If so, downcast the handle
+ FontClient* impl = dynamic_cast< Dali::TextAbstraction::Internal::FontClient* >( handle.GetObjectPtr() );
+ fontClientHandle = Dali::TextAbstraction::FontClient( impl );
+ }
+ else // create and register the object
+ {
+ fontClientHandle = Dali::TextAbstraction::FontClient( new FontClient );
+ service.Register( typeid( fontClientHandle ), fontClientHandle );
+ }
+ }
+
+ return fontClientHandle;
+}
+
+void FontClient::SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi )
+{
+ mDpiHorizontal = horizontalDpi;
+ mDpiVertical = verticalDpi;
+
+ // Allow DPI to be set without loading plugin
+ if( mPlugin )
+ {
+ mPlugin->SetDpi( horizontalDpi, verticalDpi );
+ }
+}
+
+void FontClient::GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi )
+{
+ horizontalDpi = mDpiHorizontal;
+ verticalDpi = mDpiVertical;
+}
+
+int FontClient::GetDefaultFontSize()
+{
+ int fontSize( -1 );
+
+#ifndef DALI_PROFILE_UBUNTU
+ vconf_get_int( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, &fontSize );
+#endif // DALI_PROFILE_UBUNTU
+
+ return fontSize;
+}
+
+void FontClient::ResetSystemDefaults()
+{
+ CreatePlugin();
+
+ mPlugin->ResetSystemDefaults();
+}
+
+void FontClient::GetDefaultFonts( FontList& defaultFonts )
+{
+ CreatePlugin();
+
+ mPlugin->GetDefaultFonts( defaultFonts );
+}
+
+void FontClient::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
+{
+ CreatePlugin();
+
+ mPlugin->GetDefaultPlatformFontDescription( fontDescription );
+}
+
+void FontClient::GetDescription( FontId id, FontDescription& fontDescription )
+{
+ CreatePlugin();
+
+ mPlugin->GetDescription( id, fontDescription );
+}
+
+PointSize26Dot6 FontClient::GetPointSize( FontId id )
+{
+ CreatePlugin();
+
+ return mPlugin->GetPointSize( id );
+}
+
+bool FontClient::IsCharacterSupportedByFont( FontId fontId, Character character )
+{
+ CreatePlugin();
+
+ return mPlugin->IsCharacterSupportedByFont( fontId, character );
+}
+
+void FontClient::GetSystemFonts( FontList& systemFonts )
+{
+ CreatePlugin();
+
+ mPlugin->GetSystemFonts( systemFonts );
+}
+
+FontId FontClient::FindDefaultFont( Character charcode,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ CreatePlugin();
+
+ return mPlugin->FindDefaultFont( charcode,
+ requestedPointSize,
+ preferColor );
+}
+
+FontId FontClient::FindFallbackFont( Character charcode,
+ const FontDescription& preferredFontDescription,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ CreatePlugin();
+
+ return mPlugin->FindFallbackFont( charcode,
+ preferredFontDescription,
+ requestedPointSize,
+ preferColor );
+}
+
+bool FontClient::IsScalable( const FontPath& path )
+{
+ CreatePlugin();
+
+ return mPlugin->IsScalable( path );
+}
+
+bool FontClient::IsScalable( const FontDescription& fontDescription )
+{
+ CreatePlugin();
+
+ return mPlugin->IsScalable( fontDescription );
+}
+
+void FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes )
+{
+ CreatePlugin();
+
+ mPlugin->GetFixedSizes( path, sizes );
+}
+
+void FontClient::GetFixedSizes( const FontDescription& fontDescription,
+ Dali::Vector< PointSize26Dot6 >& sizes )
+{
+ CreatePlugin();
+
+ mPlugin->GetFixedSizes( fontDescription, sizes );
+}
+
+FontId FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
+{
+ CreatePlugin();
+
+ return mPlugin->GetFontId( path,
+ requestedPointSize,
+ faceIndex,
+ true );
+}
+
+FontId FontClient::GetFontId( const FontDescription& fontDescription,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex )
+{
+ CreatePlugin();
+
+ return mPlugin->GetFontId( fontDescription,
+ requestedPointSize,
+ faceIndex );
+}
+
+void FontClient::GetFontMetrics( FontId fontId, FontMetrics& metrics )
+{
+ CreatePlugin();
+
+ return mPlugin->GetFontMetrics( fontId, metrics );
+}
+
+GlyphIndex FontClient::GetGlyphIndex( FontId fontId, Character charcode )
+{
+ CreatePlugin();
+
+ return mPlugin->GetGlyphIndex( fontId, charcode );
+}
+
+bool FontClient::GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal )
+{
+ CreatePlugin();
+
+ return mPlugin->GetGlyphMetrics( array, size, type, horizontal );
+}
+
+void FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
+{
+ CreatePlugin();
+
+ mPlugin->CreateBitmap( fontId, glyphIndex, data, outlineWidth );
+}
+
+PixelData FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
+{
+ CreatePlugin();
+
+ return mPlugin->CreateBitmap( fontId, glyphIndex, outlineWidth );
+}
+
+void FontClient::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
+{
+ CreatePlugin();
+
+ return mPlugin->CreateVectorBlob( fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
+}
+
+const GlyphInfo& FontClient::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
+{
+ CreatePlugin();
+
+ return mPlugin->GetEllipsisGlyph( requestedPointSize );
+}
+
+bool FontClient::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
+{
+ CreatePlugin();
+
+ return mPlugin->IsColorGlyph( fontId, glyphIndex );
+}
+
+void FontClient::CreatePlugin()
+{
+ if( !mPlugin )
+ {
+ mPlugin = new Plugin( mDpiHorizontal, mDpiVertical );
+ }
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/font-client-plugin-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/text-abstraction/font-list.h>
+#include <dali/public-api/common/dali-vector.h>
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/platform-abstraction.h>
+#include <dali/internal/text/text-abstraction/font-client-helper.h>
+#include <dali/internal/imaging/common/image-operations.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+// EXTERNAL INCLUDES
+#include <fontconfig/fontconfig.h>
+
+namespace
+{
+
+#if defined(DEBUG_ENABLED)
+Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT");
+#endif
+
+/**
+ * Conversion from Fractional26.6 to float
+ */
+const float FROM_266 = 1.0f / 64.0f;
+const float POINTS_PER_INCH = 72.f;
+
+const std::string FONT_FORMAT( "TrueType" );
+const std::string DEFAULT_FONT_FAMILY_NAME( "Tizen" );
+const int DEFAULT_FONT_WIDTH = 100; // normal
+const int DEFAULT_FONT_WEIGHT = 80; // normal
+const int DEFAULT_FONT_SLANT = 0; // normal
+
+const uint32_t ELLIPSIS_CHARACTER = 0x2026;
+
+// http://www.freedesktop.org/software/fontconfig/fontconfig-user.html
+
+// NONE -1 --> DEFAULT_FONT_WIDTH (NORMAL) will be used.
+// ULTRA_CONDENSED 50
+// EXTRA_CONDENSED 63
+// CONDENSED 75
+// SEMI_CONDENSED 87
+// NORMAL 100
+// SEMI_EXPANDED 113
+// EXPANDED 125
+// EXTRA_EXPANDED 150
+// ULTRA_EXPANDED 200
+const int FONT_WIDTH_TYPE_TO_INT[] = { -1, 50, 63, 75, 87, 100, 113, 125, 150, 200 };
+const unsigned int NUM_FONT_WIDTH_TYPE = sizeof( FONT_WIDTH_TYPE_TO_INT ) / sizeof( int );
+
+// NONE -1 --> DEFAULT_FONT_WEIGHT (NORMAL) will be used.
+// THIN 0
+// ULTRA_LIGHT, EXTRA_LIGHT 40
+// LIGHT 50
+// DEMI_LIGHT, SEMI_LIGHT 55
+// BOOK 75
+// NORMAL, REGULAR 80
+// MEDIUM 100
+// DEMI_BOLD, SEMI_BOLD 180
+// BOLD 200
+// ULTRA_BOLD, EXTRA_BOLD 205
+// BLACK, HEAVY, EXTRA_BLACK 210
+const int FONT_WEIGHT_TYPE_TO_INT[] = { -1, 0, 40, 50, 55, 75, 80, 100, 180, 200, 205, 210 };
+const unsigned int NUM_FONT_WEIGHT_TYPE = sizeof( FONT_WEIGHT_TYPE_TO_INT ) / sizeof( int );
+
+// NONE -1 --> DEFAULT_FONT_SLANT (NORMAL) will be used.
+// NORMAL, ROMAN 0
+// ITALIC 100
+// OBLIQUE 110
+const int FONT_SLANT_TYPE_TO_INT[] = { -1, 0, 100, 110 };
+const unsigned int NUM_FONT_SLANT_TYPE = sizeof( FONT_SLANT_TYPE_TO_INT ) / sizeof( int );
+
+} // namespace
+
+using Dali::Vector;
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+/**
+ * @brief Returns the FontWidth's enum index for the given width value.
+ *
+ * @param[in] width The width value.
+ *
+ * @return The FontWidth's enum index.
+ */
+FontWidth::Type IntToWidthType( int width )
+{
+ return static_cast<FontWidth::Type>( ValueToIndex( width, FONT_WIDTH_TYPE_TO_INT, NUM_FONT_WIDTH_TYPE - 1u ) );
+}
+
+/**
+ * @brief Returns the FontWeight's enum index for the given weight value.
+ *
+ * @param[in] weight The weight value.
+ *
+ * @return The FontWeight's enum index.
+ */
+FontWeight::Type IntToWeightType( int weight )
+{
+ return static_cast<FontWeight::Type>( ValueToIndex( weight, FONT_WEIGHT_TYPE_TO_INT, NUM_FONT_WEIGHT_TYPE - 1u ) );
+}
+
+/**
+ * @brief Returns the FontSlant's enum index for the given slant value.
+ *
+ * @param[in] slant The slant value.
+ *
+ * @return The FontSlant's enum index.
+ */
+FontSlant::Type IntToSlantType( int slant )
+{
+ return static_cast<FontSlant::Type>( ValueToIndex( slant, FONT_SLANT_TYPE_TO_INT, NUM_FONT_SLANT_TYPE - 1u ) );
+}
+
+ FontClient::Plugin::FallbackCacheItem::FallbackCacheItem( const FontDescription& font, FontList* fallbackFonts, CharacterSetList* characterSets )
+: fontDescription( font ),
+ fallbackFonts( fallbackFonts ),
+ characterSets( characterSets )
+{
+}
+
+FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem( const FontDescription& fontDescription,
+ FontDescriptionId index )
+: fontDescription( fontDescription ),
+ index( index )
+{
+}
+
+FontClient::Plugin::FontIdCacheItem::FontIdCacheItem( FontDescriptionId validatedFontId,
+ PointSize26Dot6 requestedPointSize,
+ FontId fontId )
+: validatedFontId( validatedFontId ),
+ requestedPointSize( requestedPointSize ),
+ fontId( fontId )
+{
+}
+
+FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace,
+ const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex face,
+ const FontMetrics& metrics )
+: mFreeTypeFace( ftFace ),
+ mPath( path ),
+ mRequestedPointSize( requestedPointSize ),
+ mFaceIndex( face ),
+ mMetrics( metrics ),
+ mCharacterSet( NULL ),
+ mFixedWidthPixels( 0.0f ),
+ mFixedHeightPixels( 0.0f ),
+ mVectorFontId( 0 ),
+ mIsFixedSizeBitmap( false ),
+ mHasColorTables( false )
+{
+}
+
+FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace,
+ const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex face,
+ const FontMetrics& metrics,
+ float fixedWidth,
+ float fixedHeight,
+ bool hasColorTables )
+: mFreeTypeFace( ftFace ),
+ mPath( path ),
+ mRequestedPointSize( requestedPointSize ),
+ mFaceIndex( face ),
+ mMetrics( metrics ),
+ mCharacterSet( NULL ),
+ mFixedWidthPixels( fixedWidth ),
+ mFixedHeightPixels( fixedHeight ),
+ mVectorFontId( 0 ),
+ mIsFixedSizeBitmap( true ),
+ mHasColorTables( hasColorTables )
+{
+}
+
+FontClient::Plugin::Plugin( unsigned int horizontalDpi,
+ unsigned int verticalDpi )
+: mFreeTypeLibrary( NULL ),
+ mDpiHorizontal( horizontalDpi ),
+ mDpiVertical( verticalDpi ),
+ mDefaultFontDescription(),
+ mSystemFonts(),
+ mDefaultFonts(),
+ mFontCache(),
+ mValidatedFontCache(),
+ mFontDescriptionCache( 1u ),
+ mCharacterSetCache(),
+ mFontIdCache(),
+ mVectorFontCache( NULL ),
+ mEllipsisCache(),
+ mDefaultFontDescriptionCached( false )
+{
+ mCharacterSetCache.Resize( 1u );
+
+ int error = FT_Init_FreeType( &mFreeTypeLibrary );
+ if( FT_Err_Ok != error )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Init error: %d\n", error );
+ }
+
+#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
+ mVectorFontCache = new VectorFontCache( mFreeTypeLibrary );
+#endif
+}
+
+FontClient::Plugin::~Plugin()
+{
+ for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end();
+ it != endIt;
+ ++it )
+ {
+ FallbackCacheItem& item = *it;
+
+ if( item.fallbackFonts )
+ {
+ delete item.fallbackFonts;
+ delete item.characterSets;
+ item.fallbackFonts = NULL;
+ item.characterSets = NULL;
+ }
+ }
+
+#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
+ delete mVectorFontCache;
+#endif
+
+ FT_Done_FreeType( mFreeTypeLibrary );
+}
+
+void FontClient::Plugin::SetDpi( unsigned int horizontalDpi,
+ unsigned int verticalDpi )
+{
+ mDpiHorizontal = horizontalDpi;
+ mDpiVertical = verticalDpi;
+}
+
+void FontClient::Plugin::ResetSystemDefaults()
+{
+ mDefaultFontDescriptionCached = false;
+}
+
+void FontClient::Plugin::SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::SetFontList\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+
+ fontList.clear();
+
+ FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
+
+ FcResult result = FcResultMatch;
+
+ // Match the pattern.
+ FcFontSet* fontSet = FcFontSort( NULL /* use default configure */,
+ fontFamilyPattern,
+ false /* don't trim */,
+ NULL,
+ &result );
+
+ if( NULL != fontSet )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts found : [%d]\n", fontSet->nfont );
+ // Reserve some space to avoid reallocations.
+ fontList.reserve( fontSet->nfont );
+
+ for( int i = 0u; i < fontSet->nfont; ++i )
+ {
+ FcPattern* fontPattern = fontSet->fonts[i];
+
+ FontPath path;
+
+ // Skip fonts with no path
+ if( GetFcString( fontPattern, FC_FILE, path ) )
+ {
+ FcCharSet* characterSet = NULL;
+ FcPatternGetCharSet( fontPattern, FC_CHARSET, 0u, &characterSet );
+
+ characterSetList.PushBack( characterSet );
+ fontList.push_back( FontDescription() );
+ FontDescription& newFontDescription = fontList.back();
+
+ newFontDescription.path = path;
+
+ int width = 0;
+ int weight = 0;
+ int slant = 0;
+ GetFcString( fontPattern, FC_FAMILY, newFontDescription.family );
+ GetFcInt( fontPattern, FC_WIDTH, width );
+ GetFcInt( fontPattern, FC_WEIGHT, weight );
+ GetFcInt( fontPattern, FC_SLANT, slant );
+ newFontDescription.width = IntToWidthType( width );
+ newFontDescription.weight = IntToWeightType( weight );
+ newFontDescription.slant = IntToSlantType( slant );
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", newFontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", newFontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[newFontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[newFontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[newFontDescription.slant] );
+ }
+ }
+
+ FcFontSetDestroy( fontSet );
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " No fonts found.\n" );
+ }
+
+ FcPatternDestroy( fontFamilyPattern );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::SetFontList\n" );
+}
+
+void FontClient::Plugin::GetDefaultFonts( FontList& defaultFonts )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultFonts\n" );
+
+ if( mDefaultFonts.empty() )
+ {
+ FontDescription fontDescription;
+ fontDescription.family = DEFAULT_FONT_FAMILY_NAME; // todo This could be set to the Platform font
+ fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH );
+ fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT );
+ fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT );
+ SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets );
+ }
+
+ defaultFonts = mDefaultFonts;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " number of default fonts : [%d]\n", mDefaultFonts.size() );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultFonts\n" );
+}
+
+void FontClient::Plugin::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultPlatformFontDescription\n");
+
+ if( !mDefaultFontDescriptionCached )
+ {
+ // Clear any font config stored info in the caches.
+ mDefaultFontCharacterSets.Clear();
+ mCharacterSetCache.Clear();
+
+ for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end(); it != endIt; ++it )
+ {
+ FallbackCacheItem& item = *it;
+
+ item.characterSets->Clear();
+ }
+
+ for( std::vector<FontFaceCacheItem>::iterator it = mFontCache.begin(), endIt = mFontCache.end(); it != endIt; ++it )
+ {
+ FontFaceCacheItem& item = *it;
+
+ // Set the character set pointer as null. Will be created again the next time IsCharacterSupportedByFont()
+ item.mCharacterSet = NULL;
+ }
+
+ // FcInitBringUptoDate did not seem to reload config file as was still getting old default font.
+ FcInitReinitialize();
+
+ FcPattern* matchPattern = FcPatternCreate();
+
+ if( matchPattern )
+ {
+ FcConfigSubstitute( NULL, matchPattern, FcMatchPattern );
+ FcDefaultSubstitute( matchPattern );
+
+ FcCharSet* characterSet = NULL;
+ MatchFontDescriptionToPattern( matchPattern, mDefaultFontDescription, &characterSet );
+ FcPatternDestroy( matchPattern );
+ }
+
+ // Create again the character sets as they are not valid after FcInitReinitialize()
+
+ for( FontList::const_iterator it = mDefaultFonts.begin(), endIt = mDefaultFonts.end(); it != endIt; ++it )
+ {
+ const FontDescription& description = *it;
+
+ mDefaultFontCharacterSets.PushBack( CreateCharacterSetFromDescription( description ) );
+ }
+
+ for( FontList::const_iterator it = mFontDescriptionCache.begin(), endIt = mFontDescriptionCache.end(); it != endIt; ++it )
+ {
+ const FontDescription& description = *it;
+
+ mCharacterSetCache.PushBack( CreateCharacterSetFromDescription( description ) );
+ }
+
+ for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end(); it != endIt; ++it )
+ {
+ FallbackCacheItem& item = *it;
+
+ if( NULL != item.fallbackFonts )
+ {
+ if( NULL == item.characterSets )
+ {
+ item.characterSets = new CharacterSetList;
+ }
+
+ for( FontList::const_iterator flIt = item.fallbackFonts->begin(), flEndIt = item.fallbackFonts->end(); flIt != flEndIt; ++flIt )
+ {
+ const FontDescription& description = *flIt;
+ item.characterSets->PushBack( CreateCharacterSetFromDescription( description ) );
+ }
+ }
+ }
+
+ mDefaultFontDescriptionCached = true;
+ }
+
+ fontDescription.path = mDefaultFontDescription.path;
+ fontDescription.family = mDefaultFontDescription.family;
+ fontDescription.width = mDefaultFontDescription.width;
+ fontDescription.weight = mDefaultFontDescription.weight;
+ fontDescription.slant = mDefaultFontDescription.slant;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultPlatformFontDescription\n");
+}
+
+void FontClient::Plugin::GetSystemFonts( FontList& systemFonts )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetSystemFonts\n");
+
+ if( mSystemFonts.empty() )
+ {
+ InitSystemFonts();
+ }
+
+ systemFonts = mSystemFonts;
+ DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : [%d]\n", mSystemFonts.size() );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetSystemFonts\n");
+}
+
+void FontClient::Plugin::GetDescription( FontId id,
+ FontDescription& fontDescription ) const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDescription\n");
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
+
+ for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
+ endIt = mFontIdCache.end();
+ it != endIt;
+ ++it )
+ {
+ const FontIdCacheItem& item = *it;
+
+ if( item.fontId == id )
+ {
+ fontDescription = *( mFontDescriptionCache.begin() + item.validatedFontId );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n");
+ return;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " No description found for the font ID %d\n", id );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n");
+}
+
+PointSize26Dot6 FontClient::Plugin::GetPointSize( FontId id )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetPointSize\n");
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
+ const FontId index = id - 1u;
+
+ if( ( id > 0u ) &&
+ ( index < mFontCache.size() ) )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " point size : %d\n", ( *( mFontCache.begin() + index ) ).mRequestedPointSize );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n");
+ return ( *( mFontCache.begin() + index ) ).mRequestedPointSize;
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font ID %d\n", id );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " default point size : %d\n", TextAbstraction::FontClient::DEFAULT_POINT_SIZE );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n");
+ return TextAbstraction::FontClient::DEFAULT_POINT_SIZE;
+}
+
+bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character character )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::IsCharacterSupportedByFont\n");
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character );
+
+ if( ( fontId < 1u ) || ( fontId > mFontCache.size() ) )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font id. Number of items in the cache: %d\n",mFontCache.size());
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n");
+ return false;
+ }
+
+ --fontId;
+
+ bool isSupported = false;
+
+ FontFaceCacheItem& cacheItem = mFontCache[fontId];
+
+ if( NULL == cacheItem.mCharacterSet )
+ {
+ // Create again the character set.
+ // It can be null if the ResetSystemDefaults() method has been called.
+
+ FontDescription description;
+ description.path = cacheItem.mPath;
+ description.family = FontFamily( cacheItem.mFreeTypeFace->family_name );
+ description.weight = FontWeight::NONE;
+ description.width = FontWidth::NONE;
+ description.slant = FontSlant::NONE;
+
+ // Note FreeType doesn't give too much info to build a proper font style.
+ if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC )
+ {
+ description.slant = FontSlant::ITALIC;
+ }
+ if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD )
+ {
+ description.weight = FontWeight::BOLD;
+ }
+
+ cacheItem.mCharacterSet = CreateCharacterSetFromDescription( description );
+ }
+
+ isSupported = FcCharSetHasChar( cacheItem.mCharacterSet, character );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " is supported : %s\n", (isSupported ? "true" : "false") );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n");
+ return isSupported;
+}
+
+FontId FontClient::Plugin::FindFontForCharacter( const FontList& fontList,
+ const CharacterSetList& characterSetList,
+ Character character,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ DALI_ASSERT_DEBUG( ( fontList.size() == characterSetList.Count() ) && "FontClient::Plugin::FindFontForCharacter. Different number of fonts and character sets." );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFontForCharacter\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
+
+ FontId fontId = 0u;
+ bool foundColor = false;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts : %d\n", fontList.size() );
+
+ // Traverse the list of fonts.
+ // Check for each font if supports the character.
+ for( unsigned int index = 0u, numberOfFonts = fontList.size(); index < numberOfFonts; ++index )
+ {
+ const FontDescription& description = fontList[index];
+ const FcCharSet* const characterSet = characterSetList[index];
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", description.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] );
+
+ bool foundInRanges = false;
+ if( NULL != characterSet )
+ {
+ foundInRanges = FcCharSetHasChar( characterSet, character );
+ }
+
+ if( foundInRanges )
+ {
+ fontId = GetFontId( description,
+ requestedPointSize,
+ 0u );
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " font id : %d\n", fontId );
+
+ if( preferColor )
+ {
+ if( ( fontId > 0 ) &&
+ ( fontId - 1u < mFontCache.size() ) )
+ {
+ const FontFaceCacheItem& item = mFontCache[fontId - 1u];
+
+ foundColor = item.mHasColorTables;
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " foundColor : %s\n", ( foundColor ? "true" : "false" ) );
+ }
+
+ // Keep going unless we prefer a different (color) font.
+ if( !preferColor || foundColor )
+ {
+ break;
+ }
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFontForCharacter\n" );
+ return fontId;
+}
+
+FontId FontClient::Plugin::FindDefaultFont( Character charcode,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindDefaultFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
+
+ FontId fontId(0);
+
+ // Create the list of default fonts if it has not been created.
+ if( mDefaultFonts.empty() )
+ {
+ FontDescription fontDescription;
+ fontDescription.family = DEFAULT_FONT_FAMILY_NAME;
+ fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH );
+ fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT );
+ fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT );
+
+ SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets );
+ }
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of default fonts : %d\n", mDefaultFonts.size() );
+
+
+ // Traverse the list of default fonts.
+ // Check for each default font if supports the character.
+ fontId = FindFontForCharacter( mDefaultFonts, mDefaultFontCharacterSets, charcode, requestedPointSize, preferColor );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindDefaultFont\n" );
+
+ return fontId;
+}
+
+FontId FontClient::Plugin::FindFallbackFont( Character charcode,
+ const FontDescription& preferredFontDescription,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
+
+ // The font id to be returned.
+ FontId fontId = 0u;
+
+ FontDescription fontDescription;
+
+ // Fill the font description with the preferred font description and complete with the defaults.
+ fontDescription.family = preferredFontDescription.family.empty() ? DEFAULT_FONT_FAMILY_NAME : preferredFontDescription.family;
+ fontDescription.weight = ( ( FontWeight::NONE == preferredFontDescription.weight ) ? IntToWeightType( DEFAULT_FONT_WEIGHT ) : preferredFontDescription.weight );
+ fontDescription.width = ( ( FontWidth::NONE == preferredFontDescription.width ) ? IntToWidthType( DEFAULT_FONT_WIDTH ) : preferredFontDescription.width );
+ fontDescription.slant = ( ( FontSlant::NONE == preferredFontDescription.slant ) ? IntToSlantType( DEFAULT_FONT_SLANT ) : preferredFontDescription.slant );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " preferredFontDescription --> fontDescription\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " [%s] --> [%s]\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWeight::Name[preferredFontDescription.weight], FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWidth::Name[preferredFontDescription.width], FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontSlant::Name[preferredFontDescription.slant], FontSlant::Name[fontDescription.slant] );
+
+ // Check first if the font's description has been queried before.
+ FontList* fontList = NULL;
+ CharacterSetList* characterSetList = NULL;
+
+ if( !FindFallbackFontList( fontDescription, fontList, characterSetList ) )
+ {
+ fontList = new FontList;
+ characterSetList = new CharacterSetList;
+
+ SetFontList( fontDescription, *fontList, *characterSetList );
+
+ // Add the font-list to the cache.
+ mFallbackCache.push_back( FallbackCacheItem( fontDescription, fontList, characterSetList ) );
+ }
+
+ if( fontList && characterSetList )
+ {
+ fontId = FindFontForCharacter( *fontList, *characterSetList, charcode, requestedPointSize, preferColor );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFont\n");
+ return fontId;
+}
+
+FontId FontClient::Plugin::GetFontId( const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex,
+ bool cacheDescription )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+
+ FontId id( 0 );
+
+ if( NULL != mFreeTypeLibrary )
+ {
+ FontId foundId(0);
+ if( FindFont( path, requestedPointSize, faceIndex, foundId ) )
+ {
+ id = foundId;
+ }
+ else
+ {
+ id = CreateFont( path, requestedPointSize, faceIndex, cacheDescription );
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" );
+
+ return id;
+}
+
+FontId FontClient::Plugin::GetFontId( const FontDescription& fontDescription,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+
+ // This method uses three vectors which caches:
+ // * Pairs of non validated font descriptions and an index to a vector with paths to font file names.
+ // * The path to font file names.
+ // * The font ids of pairs 'font point size, index to the vector with paths to font file names'.
+
+ // 1) Checks in the cache if the font's description has been validated before.
+ // If it was it gets an index to the vector with paths to font file names. Otherwise,
+ // retrieves using font config a path to a font file name which matches with the
+ // font's description. The path is stored in the cache.
+ //
+ // 2) Checks in the cache if the pair 'font point size, index to the vector with paths to
+ // font file names' exists. If exists, it gets the font id. If it doesn't it calls
+ // the GetFontId() method with the path to the font file name and the point size to
+ // get the font id.
+
+ // The font id to be returned.
+ FontId fontId = 0u;
+
+ // Check first if the font's description have been validated before.
+ FontDescriptionId validatedFontId = 0u;
+
+ if( !FindValidatedFont( fontDescription,
+ validatedFontId ) )
+ {
+ // Use font config to validate the font's description.
+ ValidateFont( fontDescription,
+ validatedFontId );
+ }
+
+ // Check if exists a pair 'validatedFontId, requestedPointSize' in the cache.
+ if( !FindFont( validatedFontId, requestedPointSize, fontId ) )
+ {
+ // Retrieve the font file name path.
+ const FontDescription& description = *( mFontDescriptionCache.begin() + validatedFontId );
+
+ // Retrieve the font id. Do not cache the description as it has been already cached.
+ fontId = GetFontId( description.path,
+ requestedPointSize,
+ faceIndex,
+ false );
+
+ mFontCache[fontId-1u].mCharacterSet = mCharacterSetCache[validatedFontId];
+
+ // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries.
+ mFontIdCache.push_back( FontIdCacheItem( validatedFontId,
+ requestedPointSize,
+ fontId ) );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" );
+
+ return fontId;
+}
+
+void FontClient::Plugin::ValidateFont( const FontDescription& fontDescription,
+ FontDescriptionId& validatedFontId )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::ValidateFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+
+ // Create a font pattern.
+ FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
+
+ FontDescription description;
+
+ FcCharSet* characterSet = NULL;
+ bool matched = MatchFontDescriptionToPattern( fontFamilyPattern, description, &characterSet );
+ FcPatternDestroy( fontFamilyPattern );
+
+ if( matched && ( NULL != characterSet ) )
+ {
+ // Set the index to the vector of paths to font file names.
+ validatedFontId = mFontDescriptionCache.size();
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " matched description; family : [%s]\n", description.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId );
+
+ // Add the path to the cache.
+ mFontDescriptionCache.push_back( description );
+ mCharacterSetCache.PushBack( characterSet );
+
+ // Cache the index and the matched font's description.
+ FontDescriptionCacheItem item( description,
+ validatedFontId );
+
+ mValidatedFontCache.push_back( item );
+
+ if( ( fontDescription.family != description.family ) ||
+ ( fontDescription.width != description.width ) ||
+ ( fontDescription.weight != description.weight ) ||
+ ( fontDescription.slant != description.slant ) )
+ {
+ // Cache the given font's description if it's different than the matched.
+ FontDescriptionCacheItem item( fontDescription,
+ validatedFontId );
+
+ mValidatedFontCache.push_back( item );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font validation failed for font [%s]\n", fontDescription.family.c_str() );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::ValidateFont\n" );
+}
+
+void FontClient::Plugin::GetFontMetrics( FontId fontId,
+ FontMetrics& metrics )
+{
+ if( ( fontId > 0 ) &&
+ ( fontId - 1u < mFontCache.size() ) )
+ {
+ const FontFaceCacheItem& font = mFontCache[fontId-1];
+
+ metrics = font.mMetrics;
+
+ // Adjust the metrics if the fixed-size font should be down-scaled
+ if( font.mIsFixedSizeBitmap )
+ {
+ const float desiredFixedSize = static_cast<float>( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical;
+
+ if( desiredFixedSize > 0.f )
+ {
+ const float scaleFactor = desiredFixedSize / static_cast<float>( font.mFixedHeightPixels );
+
+ metrics.ascender = floorf( metrics.ascender * scaleFactor );
+ metrics.descender = floorf( metrics.descender * scaleFactor );
+ metrics.height = floorf( metrics.height * scaleFactor );
+ metrics.underlinePosition = floorf( metrics.underlinePosition * scaleFactor );
+ metrics.underlineThickness = floorf( metrics.underlineThickness * scaleFactor );
+ }
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId );
+ }
+}
+
+GlyphIndex FontClient::Plugin::GetGlyphIndex( FontId fontId,
+ Character charcode )
+{
+ GlyphIndex index = 0u;
+
+ if( ( fontId > 0u ) &&
+ ( fontId - 1u < mFontCache.size() ) )
+ {
+ FT_Face ftFace = mFontCache[fontId-1u].mFreeTypeFace;
+
+ index = FT_Get_Char_Index( ftFace, charcode );
+ }
+
+ return index;
+}
+
+bool FontClient::Plugin::GetGlyphMetrics( GlyphInfo* array,
+ uint32_t size,
+ GlyphType type,
+ bool horizontal )
+{
+ if( VECTOR_GLYPH == type )
+ {
+ return GetVectorMetrics( array, size, horizontal );
+ }
+
+ return GetBitmapMetrics( array, size, horizontal );
+}
+
+bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array,
+ uint32_t size,
+ bool horizontal )
+{
+ bool success( true );
+
+ for( unsigned int i=0; i<size; ++i )
+ {
+ GlyphInfo& glyph = array[i];
+
+ FontId fontId = glyph.fontId;
+
+ if( fontId > 0 &&
+ fontId-1 < mFontCache.size() )
+ {
+ const FontFaceCacheItem& font = mFontCache[fontId-1];
+
+ FT_Face ftFace = font.mFreeTypeFace;
+
+#ifdef FREETYPE_BITMAP_SUPPORT
+ // Check to see if we should be loading a Fixed Size bitmap?
+ if ( font.mIsFixedSizeBitmap )
+ {
+ int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_COLOR );
+ if ( FT_Err_Ok == error )
+ {
+ glyph.width = font.mFixedWidthPixels;
+ glyph.height = font.mFixedHeightPixels;
+ glyph.advance = font.mFixedWidthPixels;
+ glyph.xBearing = 0.0f;
+ glyph.yBearing = font.mFixedHeightPixels;
+
+ // Adjust the metrics if the fixed-size font should be down-scaled
+ const float desiredFixedSize = static_cast<float>( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical;
+
+ if( desiredFixedSize > 0.f )
+ {
+ const float scaleFactor = desiredFixedSize / static_cast<float>( font.mFixedHeightPixels );
+
+ glyph.width = floorf( glyph.width * scaleFactor );
+ glyph.height = floorf( glyph.height * scaleFactor );
+ glyph.advance = floorf( glyph.advance * scaleFactor );
+ glyph.xBearing = floorf( glyph.xBearing * scaleFactor );
+ glyph.yBearing = floorf( glyph.yBearing * scaleFactor );
+
+ glyph.scaleFactor = scaleFactor;
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error );
+ success = false;
+ }
+ }
+ else
+#endif
+ {
+ int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_DEFAULT );
+
+ if( FT_Err_Ok == error )
+ {
+ glyph.width = static_cast< float >( ftFace->glyph->metrics.width ) * FROM_266;
+ glyph.height = static_cast< float >( ftFace->glyph->metrics.height ) * FROM_266 ;
+ if( horizontal )
+ {
+ glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingX ) * FROM_266;
+ glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingY ) * FROM_266;
+ }
+ else
+ {
+ glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingX ) * FROM_266;
+ glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingY ) * FROM_266;
+ }
+ }
+ else
+ {
+ success = false;
+ }
+ }
+ }
+ else
+ {
+ success = false;
+ }
+ }
+
+ return success;
+}
+
+bool FontClient::Plugin::GetVectorMetrics( GlyphInfo* array,
+ uint32_t size,
+ bool horizontal )
+{
+#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
+ bool success( true );
+
+ for( unsigned int i=0; i<size; ++i )
+ {
+ FontId fontId = array[i].fontId;
+
+ if( fontId > 0 &&
+ fontId-1 < mFontCache.size() )
+ {
+ FontFaceCacheItem& font = mFontCache[fontId-1];
+
+ if( ! font.mVectorFontId )
+ {
+ font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath );
+ }
+
+ mVectorFontCache->GetGlyphMetrics( font.mVectorFontId, array[i] );
+
+ // Vector metrics are in EMs, convert to pixels
+ const float scale = ( static_cast<float>( font.mRequestedPointSize ) * FROM_266 ) * static_cast<float>( mDpiVertical ) / POINTS_PER_INCH;
+ array[i].width *= scale;
+ array[i].height *= scale;
+ array[i].xBearing *= scale;
+ array[i].yBearing *= scale;
+ array[i].advance *= scale;
+ }
+ else
+ {
+ success = false;
+ }
+ }
+
+ return success;
+#else
+ return false;
+#endif
+}
+
+void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
+{
+ if( ( fontId > 0 ) &&
+ ( fontId - 1u < mFontCache.size() ) )
+ {
+ FT_Face ftFace = mFontCache[fontId - 1u].mFreeTypeFace;
+
+ FT_Error error;
+
+#ifdef FREETYPE_BITMAP_SUPPORT
+ // Check to see if this is fixed size bitmap
+ if ( mFontCache[fontId - 1u].mIsFixedSizeBitmap )
+ {
+ error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR );
+ }
+ else
+#endif
+ {
+ error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_DEFAULT );
+ }
+ if( FT_Err_Ok == error )
+ {
+ FT_Glyph glyph;
+ error = FT_Get_Glyph( ftFace->glyph, &glyph );
+
+ // Convert to bitmap if necessary
+ if ( FT_Err_Ok == error )
+ {
+ if( glyph->format != FT_GLYPH_FORMAT_BITMAP )
+ {
+ // Check whether we should create a bitmap for the outline
+ if( glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0 )
+ {
+ // Set up a stroker
+ FT_Stroker stroker;
+ error = FT_Stroker_New(mFreeTypeLibrary, &stroker );
+
+ if ( FT_Err_Ok == error )
+ {
+ FT_Stroker_Set( stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0 );
+ error = FT_Glyph_StrokeBorder( &glyph, stroker, 0, 1 );
+
+ if ( FT_Err_Ok == error )
+ {
+ FT_Stroker_Done( stroker );
+ }
+ else
+ {
+ DALI_LOG_ERROR( "FT_Glyph_StrokeBorder Failed with error: %d\n", error );
+ }
+ }
+ else
+ {
+ DALI_LOG_ERROR( "FT_Stroker_New Failed with error: %d\n", error );
+ }
+ }
+
+ error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 );
+ if ( FT_Err_Ok == error )
+ {
+ FT_BitmapGlyph bitmapGlyph = reinterpret_cast< FT_BitmapGlyph >( glyph );
+ ConvertBitmap( data, bitmapGlyph->bitmap );
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error );
+ }
+ }
+ else
+ {
+ ConvertBitmap( data, ftFace->glyph->bitmap );
+ }
+
+ // Created FT_Glyph object must be released with FT_Done_Glyph
+ FT_Done_Glyph( glyph );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error );
+ }
+ }
+}
+
+PixelData FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
+{
+ TextAbstraction::FontClient::GlyphBufferData data;
+
+ CreateBitmap( fontId, glyphIndex, data, outlineWidth );
+
+ return PixelData::New( data.buffer,
+ data.width * data.height * Pixel::GetBytesPerPixel( data.format ),
+ data.width,
+ data.height,
+ data.format,
+ PixelData::DELETE_ARRAY );
+}
+
+void FontClient::Plugin::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
+{
+ blob = NULL;
+ blobLength = 0;
+
+#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
+ if( fontId > 0 &&
+ fontId-1 < mFontCache.size() )
+ {
+ FontFaceCacheItem& font = mFontCache[fontId-1];
+
+ if( ! font.mVectorFontId )
+ {
+ font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath );
+ }
+
+ mVectorFontCache->GetVectorBlob( font.mVectorFontId, fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
+ }
+#endif
+}
+
+const GlyphInfo& FontClient::Plugin::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetEllipsisGlyph\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize %d.\n", requestedPointSize );
+
+ // First look into the cache if there is an ellipsis glyph for the requested point size.
+ for( Vector<EllipsisItem>::ConstIterator it = mEllipsisCache.Begin(),
+ endIt = mEllipsisCache.End();
+ it != endIt;
+ ++it )
+ {
+ const EllipsisItem& item = *it;
+
+ if( fabsf( item.requestedPointSize - requestedPointSize ) < Math::MACHINE_EPSILON_1000 )
+ {
+ // Use the glyph in the cache.
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" );
+
+ return item.glyph;
+ }
+ }
+
+ // No glyph has been found. Create one.
+ mEllipsisCache.PushBack( EllipsisItem() );
+ EllipsisItem& item = *( mEllipsisCache.End() - 1u );
+
+ item.requestedPointSize = requestedPointSize;
+
+ // Find a font for the ellipsis glyph.
+ item.glyph.fontId = FindDefaultFont( ELLIPSIS_CHARACTER,
+ requestedPointSize,
+ false );
+
+ // Set the character index to access the glyph inside the font.
+ item.glyph.index = FT_Get_Char_Index( mFontCache[item.glyph.fontId-1].mFreeTypeFace,
+ ELLIPSIS_CHARACTER );
+
+ GetBitmapMetrics( &item.glyph, 1u, true );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" );
+
+ return item.glyph;
+}
+
+bool FontClient::Plugin::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
+{
+ FT_Error error = -1;
+
+#ifdef FREETYPE_BITMAP_SUPPORT
+ if( ( fontId > 0 ) &&
+ ( fontId - 1u < mFontCache.size() ) )
+ {
+ const FontFaceCacheItem& item = mFontCache[fontId - 1u];
+ FT_Face ftFace = item.mFreeTypeFace;
+
+ // Check to see if this is fixed size bitmap
+ if( item.mHasColorTables )
+ {
+ error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR );
+ }
+ }
+#endif
+
+ return FT_Err_Ok == error;
+}
+
+void FontClient::Plugin::InitSystemFonts()
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::InitSystemFonts\n" );
+
+ FcFontSet* fontSet = GetFcFontSet();
+
+ if( fontSet )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : %d\n", fontSet->nfont );
+
+ // Reserve some space to avoid reallocations.
+ mSystemFonts.reserve( fontSet->nfont );
+
+ for( int i = 0u; i < fontSet->nfont; ++i )
+ {
+ FcPattern* fontPattern = fontSet->fonts[i];
+
+ FontPath path;
+
+ // Skip fonts with no path
+ if( GetFcString( fontPattern, FC_FILE, path ) )
+ {
+ mSystemFonts.push_back( FontDescription() );
+ FontDescription& fontDescription = mSystemFonts.back();
+
+ fontDescription.path = path;
+
+ int width = 0;
+ int weight = 0;
+ int slant = 0;
+ GetFcString( fontPattern, FC_FAMILY, fontDescription.family );
+ GetFcInt( fontPattern, FC_WIDTH, width );
+ GetFcInt( fontPattern, FC_WEIGHT, weight );
+ GetFcInt( fontPattern, FC_SLANT, slant );
+ fontDescription.width = IntToWidthType( width );
+ fontDescription.weight = IntToWeightType( weight );
+ fontDescription.slant = IntToSlantType( slant );
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ }
+ }
+
+ FcFontSetDestroy( fontSet );
+ }
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::InitSystemFonts\n" );
+}
+
+bool FontClient::Plugin::MatchFontDescriptionToPattern( FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, FcCharSet** characterSet )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::MatchFontDescriptionToPattern\n" );
+
+ FcResult result = FcResultMatch;
+ FcPattern* match = FcFontMatch( NULL /* use default configure */, pattern, &result );
+
+ const bool matched = NULL != match;
+ DALI_LOG_INFO( gLogFilter, Debug::General, " pattern matched : %s\n", ( matched ? "true" : "false" ) );
+
+ if( matched )
+ {
+ int width = 0;
+ int weight = 0;
+ int slant = 0;
+ GetFcString( match, FC_FILE, fontDescription.path );
+ GetFcString( match, FC_FAMILY, fontDescription.family );
+ GetFcInt( match, FC_WIDTH, width );
+ GetFcInt( match, FC_WEIGHT, weight );
+ GetFcInt( match, FC_SLANT, slant );
+ fontDescription.width = IntToWidthType( width );
+ fontDescription.weight = IntToWeightType( weight );
+ fontDescription.slant = IntToSlantType( slant );
+
+ // Cache the character ranges.
+ FcPatternGetCharSet( match, FC_CHARSET, 0u, characterSet );
+
+ // destroyed the matched pattern
+ FcPatternDestroy( match );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::MatchFontDescriptionToPattern\n" );
+ return matched;
+}
+
+FcPattern* FontClient::Plugin::CreateFontFamilyPattern( const FontDescription& fontDescription ) const
+{
+ // create the cached font family lookup pattern
+ // a pattern holds a set of names, each name refers to a property of the font
+ FcPattern* fontFamilyPattern = FcPatternCreate();
+
+ if( !fontFamilyPattern )
+ {
+ return NULL;
+ }
+
+ // add a property to the pattern for the font family
+ FcPatternAddString( fontFamilyPattern, FC_FAMILY, reinterpret_cast<const FcChar8*>( fontDescription.family.c_str() ) );
+
+ int width = FONT_WIDTH_TYPE_TO_INT[fontDescription.width];
+ if( width < 0 )
+ {
+ // Use default.
+ width = DEFAULT_FONT_WIDTH;
+ }
+
+ int weight = FONT_WEIGHT_TYPE_TO_INT[fontDescription.weight];
+ if( weight < 0 )
+ {
+ // Use default.
+ weight = DEFAULT_FONT_WEIGHT;
+ }
+
+ int slant = FONT_SLANT_TYPE_TO_INT[fontDescription.slant];
+ if( slant < 0 )
+ {
+ // Use default.
+ slant = DEFAULT_FONT_SLANT;
+ }
+
+ FcPatternAddInteger( fontFamilyPattern, FC_WIDTH, width );
+ FcPatternAddInteger( fontFamilyPattern, FC_WEIGHT, weight );
+ FcPatternAddInteger( fontFamilyPattern, FC_SLANT, slant );
+
+ // Add a property of the pattern, to say we want to match TrueType fonts
+ FcPatternAddString( fontFamilyPattern , FC_FONTFORMAT, reinterpret_cast<const FcChar8*>( FONT_FORMAT.c_str() ) );
+
+ // modify the config, with the mFontFamilyPatterm
+ FcConfigSubstitute( NULL /* use default configure */, fontFamilyPattern, FcMatchPattern );
+
+ // provide default values for unspecified properties in the font pattern
+ // e.g. patterns without a specified style or weight are set to Medium
+ FcDefaultSubstitute( fontFamilyPattern );
+
+ return fontFamilyPattern;
+}
+
+_FcFontSet* FontClient::Plugin::GetFcFontSet() const
+{
+ // create a new pattern.
+ // a pattern holds a set of names, each name refers to a property of the font
+ FcPattern* pattern = FcPatternCreate();
+
+ // create an object set used to define which properties are to be returned in the patterns from FcFontList.
+ FcObjectSet* objectSet = FcObjectSetCreate();
+
+ // build an object set from a list of property names
+ FcObjectSetAdd( objectSet, FC_FILE );
+ FcObjectSetAdd( objectSet, FC_FAMILY );
+ FcObjectSetAdd( objectSet, FC_WIDTH );
+ FcObjectSetAdd( objectSet, FC_WEIGHT );
+ FcObjectSetAdd( objectSet, FC_SLANT );
+
+ // get a list of fonts
+ // creates patterns from those fonts containing only the objects in objectSet and returns the set of unique such patterns
+ FcFontSet* fontset = FcFontList( NULL /* the default configuration is checked to be up to date, and used */, pattern, objectSet );
+
+ // clear up the object set
+ if( objectSet )
+ {
+ FcObjectSetDestroy( objectSet );
+ }
+ // clear up the pattern
+ if( pattern )
+ {
+ FcPatternDestroy( pattern );
+ }
+
+ return fontset;
+}
+
+bool FontClient::Plugin::GetFcString( const FcPattern* const pattern,
+ const char* const n,
+ std::string& string )
+{
+ FcChar8* file = NULL;
+ const FcResult retVal = FcPatternGetString( pattern, n, 0u, &file );
+
+ if( FcResultMatch == retVal )
+ {
+ // Have to use reinterpret_cast because FcChar8 is unsigned char*, not a const char*.
+ string.assign( reinterpret_cast<const char*>( file ) );
+
+ return true;
+ }
+
+ return false;
+}
+
+bool FontClient::Plugin::GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal )
+{
+ const FcResult retVal = FcPatternGetInteger( pattern, n, 0u, &intVal );
+
+ if( FcResultMatch == retVal )
+ {
+ return true;
+ }
+
+ return false;
+}
+
+FontId FontClient::Plugin::CreateFont( const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex,
+ bool cacheDescription )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::CreateFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+
+ FontId id = 0u;
+
+ // Create & cache new font face
+ FT_Face ftFace;
+ int error = FT_New_Face( mFreeTypeLibrary,
+ path.c_str(),
+ 0,
+ &ftFace );
+
+ if( FT_Err_Ok == error )
+ {
+ // Check if a font is scalable.
+ const bool isScalable = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_SCALABLE ) );
+ const bool hasFixedSizedBitmaps = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_FIXED_SIZES ) ) && ( 0 != ftFace->num_fixed_sizes );
+ const bool hasColorTables = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_COLOR ) );
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " isScalable : [%s]\n", ( isScalable ? "true" : "false" ) );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " hasFixedSizedBitmaps : [%s]\n", ( hasFixedSizedBitmaps ? "true" : "false" ) );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " hasColorTables : [%s]\n", ( hasColorTables ? "true" : "false" ) );
+
+ // Check to see if the font contains fixed sizes?
+ if( !isScalable && hasFixedSizedBitmaps )
+ {
+ PointSize26Dot6 actualPointSize = 0u;
+ int fixedSizeIndex = 0;
+ for( ; fixedSizeIndex < ftFace->num_fixed_sizes; ++fixedSizeIndex )
+ {
+ const PointSize26Dot6 fixedSize = ftFace->available_sizes[fixedSizeIndex].size;
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, size : %d\n", fixedSizeIndex, fixedSize );
+
+ if( fixedSize >= requestedPointSize )
+ {
+ actualPointSize = fixedSize;
+ break;
+ }
+ }
+
+ if( 0u == actualPointSize )
+ {
+ // The requested point size is bigger than the bigest fixed size.
+ fixedSizeIndex = ftFace->num_fixed_sizes - 1;
+ actualPointSize = ftFace->available_sizes[fixedSizeIndex].size;
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, actual size : %d\n", fixedSizeIndex, actualPointSize );
+
+ // Tell Freetype to use this size
+ error = FT_Select_Size( ftFace, fixedSizeIndex );
+ if ( FT_Err_Ok != error )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Select_Size error: %d\n", error );
+ }
+ else
+ {
+ float fixedWidth = static_cast< float >( ftFace->available_sizes[ fixedSizeIndex ].width );
+ float fixedHeight = static_cast< float >( ftFace->available_sizes[ fixedSizeIndex ].height );
+
+ // Indicate that the font is a fixed sized bitmap
+ FontMetrics metrics( fixedHeight, // The ascender in pixels.
+ 0.0f,
+ fixedHeight, // The height in pixels.
+ 0.0f,
+ 0.0f );
+
+ mFontCache.push_back( FontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics, fixedWidth, fixedHeight, hasColorTables ) );
+ id = mFontCache.size();
+ }
+ }
+ else
+ {
+ error = FT_Set_Char_Size( ftFace,
+ 0,
+ requestedPointSize,
+ mDpiHorizontal,
+ mDpiVertical );
+
+ if( FT_Err_Ok == error )
+ {
+
+ FT_Size_Metrics& ftMetrics = ftFace->size->metrics;
+
+ FontMetrics metrics( static_cast< float >( ftMetrics.ascender ) * FROM_266,
+ static_cast< float >( ftMetrics.descender ) * FROM_266,
+ static_cast< float >( ftMetrics.height ) * FROM_266,
+ static_cast< float >( ftFace->underline_position ) * FROM_266,
+ static_cast< float >( ftFace->underline_thickness ) * FROM_266 );
+
+ mFontCache.push_back( FontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics ) );
+ id = mFontCache.size();
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType Set_Char_Size error: %d for pointSize %d\n", error, requestedPointSize );
+ }
+ }
+
+ if( 0u != id )
+ {
+ if( cacheDescription )
+ {
+ CacheFontPath( ftFace, id, requestedPointSize, path );
+ }
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType New_Face error: %d for [%s]\n", error, path.c_str() );
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::CreateFont\n" );
+
+ return id;
+}
+
+void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap )
+{
+ if( srcBitmap.width*srcBitmap.rows > 0 )
+ {
+ switch( srcBitmap.pixel_mode )
+ {
+ case FT_PIXEL_MODE_GRAY:
+ {
+ if( srcBitmap.pitch == static_cast<int>( srcBitmap.width ) )
+ {
+ const unsigned int bufferSize = srcBitmap.width * srcBitmap.rows;
+ data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[].
+ data.width = srcBitmap.width;
+ data.height = srcBitmap.rows;
+ data.format = Pixel::L8;
+ memcpy( data.buffer, srcBitmap.buffer, bufferSize );
+ }
+ break;
+ }
+
+#ifdef FREETYPE_BITMAP_SUPPORT
+ case FT_PIXEL_MODE_BGRA:
+ {
+ if( srcBitmap.pitch == static_cast<int>( srcBitmap.width << 2u ) )
+ {
+ // Set the input dimensions.
+ const ImageDimensions inputDimensions( srcBitmap.width, srcBitmap.rows );
+
+ // Set the output dimensions.
+ // If the output dimension is not given, the input dimension is set
+ // and won't be downscaling.
+ data.width = ( data.width == 0 ) ? srcBitmap.width : data.width;
+ data.height = ( data.height == 0 ) ? srcBitmap.rows : data.height;
+ const ImageDimensions desiredDimensions( data.width, data.height );
+
+ // Creates the output buffer
+ const unsigned int bufferSize = data.width * data.height * 4u;
+ data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[].
+
+ if( inputDimensions == desiredDimensions )
+ {
+ // There isn't downscaling.
+ memcpy( data.buffer, srcBitmap.buffer, bufferSize );
+ }
+ else
+ {
+ Dali::Internal::Platform::LanczosSample4BPP( srcBitmap.buffer,
+ inputDimensions,
+ data.buffer,
+ desiredDimensions );
+ }
+ data.format = Pixel::BGRA8888;
+ }
+ break;
+ }
+#endif
+ default:
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::ConvertBitmap. FontClient Unable to create Bitmap of this PixelType\n" );
+ break;
+ }
+ }
+ }
+}
+
+bool FontClient::Plugin::FindFont( const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex,
+ FontId& fontId ) const
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fonts in the cache : %d\n", mFontCache.size() );
+
+ fontId = 0u;
+ for( std::vector<FontFaceCacheItem>::const_iterator it = mFontCache.begin(),
+ endIt = mFontCache.end();
+ it != endIt;
+ ++it, ++fontId )
+ {
+ const FontFaceCacheItem& cacheItem = *it;
+
+ if( cacheItem.mRequestedPointSize == requestedPointSize &&
+ cacheItem.mFaceIndex == faceIndex &&
+ cacheItem.mPath == path )
+ {
+ ++fontId;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
+
+ return true;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font not found\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
+
+ return false;
+}
+
+bool FontClient::Plugin::FindValidatedFont( const FontDescription& fontDescription,
+ FontDescriptionId& validatedFontId )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindValidatedFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of validated fonts in the cache : %d\n", mValidatedFontCache.size() );
+
+ validatedFontId = 0u;
+
+ for( std::vector<FontDescriptionCacheItem>::const_iterator it = mValidatedFontCache.begin(),
+ endIt = mValidatedFontCache.end();
+ it != endIt;
+ ++it )
+ {
+ const FontDescriptionCacheItem& item = *it;
+
+ if( !fontDescription.family.empty() &&
+ ( fontDescription.family == item.fontDescription.family ) &&
+ ( fontDescription.width == item.fontDescription.width ) &&
+ ( fontDescription.weight == item.fontDescription.weight ) &&
+ ( fontDescription.slant == item.fontDescription.slant ) )
+ {
+ validatedFontId = item.index;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " validated font found, id : %d\n", validatedFontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" );
+ return true;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " validated font not found\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" );
+ return false;
+}
+
+bool FontClient::Plugin::FindFallbackFontList( const FontDescription& fontDescription,
+ FontList*& fontList,
+ CharacterSetList*& characterSetList )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFontList\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
+ DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fallback font lists in the cache : %d\n", mFallbackCache.size() );
+
+ fontList = NULL;
+
+ for( std::vector<FallbackCacheItem>::const_iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end();
+ it != endIt;
+ ++it )
+ {
+ const FallbackCacheItem& item = *it;
+
+ if( !fontDescription.family.empty() &&
+ ( fontDescription.family == item.fontDescription.family ) &&
+ ( fontDescription.width == item.fontDescription.width ) &&
+ ( fontDescription.weight == item.fontDescription.weight ) &&
+ ( fontDescription.slant == item.fontDescription.slant ) )
+ {
+ fontList = item.fallbackFonts;
+ characterSetList = item.characterSets;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list found.\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" );
+ return true;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list not found.\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" );
+ return false;
+}
+
+bool FontClient::Plugin::FindFont( FontDescriptionId validatedFontId,
+ PointSize26Dot6 requestedPointSize,
+ FontId& fontId )
+{
+ DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
+
+ fontId = 0u;
+
+ for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
+ endIt = mFontIdCache.end();
+ it != endIt;
+ ++it )
+ {
+ const FontIdCacheItem& item = *it;
+
+ if( ( validatedFontId == item.validatedFontId ) &&
+ ( requestedPointSize == item.requestedPointSize ) )
+ {
+ fontId = item.fontId;
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
+ return true;
+ }
+ }
+
+ DALI_LOG_INFO( gLogFilter, Debug::General, " font not found.\n" );
+ DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
+ return false;
+}
+
+bool FontClient::Plugin::IsScalable( const FontPath& path )
+{
+ bool isScalable = false;
+
+ FT_Face ftFace;
+ int error = FT_New_Face( mFreeTypeLibrary,
+ path.c_str(),
+ 0,
+ &ftFace );
+ if( FT_Err_Ok != error )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: %s\n", path.c_str() );
+ }
+ else
+ {
+ isScalable = ftFace->face_flags & FT_FACE_FLAG_SCALABLE;
+ }
+
+ return isScalable;
+}
+
+bool FontClient::Plugin::IsScalable( const FontDescription& fontDescription )
+{
+ // Create a font pattern.
+ FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
+
+ FcResult result = FcResultMatch;
+
+ // match the pattern
+ FcPattern* match = FcFontMatch( NULL /* use default configure */, fontFamilyPattern, &result );
+ bool isScalable = false;
+
+ if( match )
+ {
+ // Get the path to the font file name.
+ FontPath path;
+ GetFcString( match, FC_FILE, path );
+ isScalable = IsScalable( path );
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() );
+ }
+ FcPatternDestroy( fontFamilyPattern );
+ FcPatternDestroy( match );
+ return isScalable;
+}
+
+void FontClient::Plugin::GetFixedSizes( const FontPath& path, Vector< PointSize26Dot6 >& sizes )
+{
+ // Empty the caller container
+ sizes.Clear();
+
+ FT_Face ftFace;
+ int error = FT_New_Face( mFreeTypeLibrary,
+ path.c_str(),
+ 0,
+ &ftFace );
+ if( FT_Err_Ok != error )
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font path : [%s]\n", path.c_str() );
+ }
+
+ // Fetch the number of fixed sizes available
+ if ( ftFace->num_fixed_sizes && ftFace->available_sizes )
+ {
+ for ( int i = 0; i < ftFace->num_fixed_sizes; ++i )
+ {
+ sizes.PushBack( ftFace->available_sizes[ i ].size );
+ }
+ }
+}
+
+void FontClient::Plugin::GetFixedSizes( const FontDescription& fontDescription,
+ Vector< PointSize26Dot6 >& sizes )
+{
+ // Create a font pattern.
+ FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
+
+ FcResult result = FcResultMatch;
+
+ // match the pattern
+ FcPattern* match = FcFontMatch( NULL /* use default configure */, fontFamilyPattern, &result );
+
+ if( match )
+ {
+ // Get the path to the font file name.
+ FontPath path;
+ GetFcString( match, FC_FILE, path );
+ GetFixedSizes( path, sizes );
+ }
+ else
+ {
+ DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() );
+ }
+ FcPatternDestroy( match );
+ FcPatternDestroy( fontFamilyPattern );
+}
+
+void FontClient::Plugin::CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path )
+{
+ FontDescription description;
+ description.path = path;
+ description.family = FontFamily( ftFace->family_name );
+ description.weight = FontWeight::NONE;
+ description.width = FontWidth::NONE;
+ description.slant = FontSlant::NONE;
+
+ // Note FreeType doesn't give too much info to build a proper font style.
+ if( ftFace->style_flags & FT_STYLE_FLAG_ITALIC )
+ {
+ description.slant = FontSlant::ITALIC;
+ }
+ if( ftFace->style_flags & FT_STYLE_FLAG_BOLD )
+ {
+ description.weight = FontWeight::BOLD;
+ }
+
+ FontDescriptionId validatedFontId = 0u;
+ if( !FindValidatedFont( description,
+ validatedFontId ) )
+ {
+ // Set the index to the vector of paths to font file names.
+ validatedFontId = mFontDescriptionCache.size();
+
+ FcPattern* pattern = CreateFontFamilyPattern( description );
+
+ FcResult result = FcResultMatch;
+ FcPattern* match = FcFontMatch( NULL, pattern, &result );
+
+ FcCharSet* characterSet = NULL;
+ FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet );
+
+ FcPatternDestroy( match );
+ FcPatternDestroy( pattern );
+
+ mFontCache[id-1u].mCharacterSet = characterSet;
+
+ // Add the path to the cache.
+ mFontDescriptionCache.push_back( description );
+ mCharacterSetCache.PushBack( characterSet );
+
+ // Cache the index and the font's description.
+ FontDescriptionCacheItem item( description,
+ validatedFontId );
+
+ mValidatedFontCache.push_back( item );
+
+ // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries.
+ mFontIdCache.push_back( FontIdCacheItem( validatedFontId,
+ requestedPointSize,
+ id ) );
+ }
+}
+
+FcCharSet* FontClient::Plugin::CreateCharacterSetFromDescription( const FontDescription& description ) const
+{
+ FcCharSet* characterSet = NULL;
+
+ FcPattern* pattern = CreateFontFamilyPattern( description );
+
+ if( NULL != pattern )
+ {
+ FcResult result = FcResultMatch;
+ FcPattern* match = FcFontMatch( NULL, pattern, &result );
+
+ FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet );
+
+ FcPatternDestroy( match );
+ FcPatternDestroy( pattern );
+ }
+
+ return characterSet;
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
+#define DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/text-abstraction/font-metrics.h>
+#include <dali/devel-api/text-abstraction/glyph-info.h>
+#include <dali/internal/text/text-abstraction/font-client-impl.h>
+
+#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
+#include <dali/internal/text/glyphy/vector-font-cache.h>
+#else
+class VectorFontCache;
+#endif
+
+// EXTERNAL INCLUDES
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+#include FT_OUTLINE_H
+#include FT_STROKER_H
+
+// forward declarations of font config types.
+struct _FcCharSet;
+struct _FcFontSet;
+struct _FcPattern;
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+/**
+ *@brief Type used for indices addressing the vector with front descriptions of validated fonts.
+ */
+typedef uint32_t FontDescriptionId;
+typedef Vector<_FcCharSet*> CharacterSetList;
+
+/**
+ * @brief FontClient implementation.
+ */
+struct FontClient::Plugin
+{
+ /**
+ * @brief Caches an list of fallback fonts for a given font-description
+ */
+ struct FallbackCacheItem
+ {
+ FallbackCacheItem( const FontDescription& fontDescription, FontList* fallbackFonts, CharacterSetList* characterSets );
+
+ FontDescription fontDescription; ///< The font description.
+ FontList* fallbackFonts; ///< The list of fallback fonts for the given font-description.
+ CharacterSetList* characterSets; ///< The list of character sets for the given font-description.
+ };
+
+ /**
+ * @brief Caches an index to the vector of font descriptions for a given font.
+ */
+ struct FontDescriptionCacheItem
+ {
+ FontDescriptionCacheItem( const FontDescription& fontDescription,
+ FontDescriptionId index );
+
+ FontDescription fontDescription; ///< The font description.
+ FontDescriptionId index; ///< Index to the vector of font descriptions.
+ };
+
+ /**
+ * @brief Caches the font id of the pair font point size and the index to the vector of font descriptions of validated fonts.
+ */
+ struct FontIdCacheItem
+ {
+ FontIdCacheItem( FontDescriptionId validatedFontId,
+ PointSize26Dot6 requestedPointSize,
+ FontId fontId );
+
+ FontDescriptionId validatedFontId; ///< Index to the vector with font descriptions.
+ PointSize26Dot6 requestedPointSize; ///< The font point size.
+ FontId fontId; ///< The font identifier.
+ };
+
+ /**
+ * @brief Caches the FreeType face and font metrics of the triplet 'path to the font file name, font point size and face index'.
+ */
+ struct FontFaceCacheItem
+ {
+ FontFaceCacheItem( FT_Face ftFace,
+ const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex face,
+ const FontMetrics& metrics );
+
+ FontFaceCacheItem( FT_Face ftFace,
+ const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex face,
+ const FontMetrics& metrics,
+ float fixedWidth,
+ float fixedHeight,
+ bool hasColorTables );
+
+ FT_Face mFreeTypeFace; ///< The FreeType face.
+ FontPath mPath; ///< The path to the font file name.
+ PointSize26Dot6 mRequestedPointSize; ///< The font point size.
+ FaceIndex mFaceIndex; ///< The face index.
+ FontMetrics mMetrics; ///< The font metrics.
+ _FcCharSet* mCharacterSet; ///< Pointer with the range of characters.
+ FT_Short mFixedWidthPixels; ///< The height in pixels (fixed size bitmaps only)
+ FT_Short mFixedHeightPixels; ///< The height in pixels (fixed size bitmaps only)
+ unsigned int mVectorFontId; ///< The ID of the equivalent vector-based font
+ bool mIsFixedSizeBitmap : 1; ///< Whether the font has fixed size bitmaps.
+ bool mHasColorTables : 1; ///< Whether the font has color tables.
+ };
+
+ struct EllipsisItem
+ {
+ PointSize26Dot6 requestedPointSize;
+ GlyphInfo glyph;
+ };
+
+ /**
+ * Constructor.
+ *
+ * Initializes the FreeType library.
+ * Initializes the dpi values.
+ *
+ * @param[in] horizontalDpi The horizontal dpi.
+ * @param[in] verticalDpi The vertical dpi.
+ */
+ Plugin( unsigned int horizontalDpi, unsigned int verticalDpi );
+
+ /**
+ * Default destructor.
+ *
+ * Frees any allocated resource.
+ */
+ ~Plugin();
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::SetDpi()
+ */
+ void SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::ResetSystemDefaults()
+ */
+ void ResetSystemDefaults();
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::SetDefaultFont()
+ */
+ void SetDefaultFont( const FontDescription& preferredFontDescription );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetDefaultPlatformFontDescription()
+ */
+ void GetDefaultPlatformFontDescription( FontDescription& fontDescription );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetDefaultFonts()
+ */
+ void GetDefaultFonts( FontList& defaultFonts );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetSystemFonts()
+ */
+ void GetSystemFonts( FontList& systemFonts );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetDescription()
+ */
+ void GetDescription( FontId id, FontDescription& fontDescription ) const;
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetPointSize()
+ */
+ PointSize26Dot6 GetPointSize( FontId id );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::IsCharacterSupportedByFont()
+ */
+ bool IsCharacterSupportedByFont( FontId fontId, Character character );
+
+ /**
+ * @brief Finds within the @p fontList a font which support the @p carcode.
+ *
+ * @param[in] fontList A list of font paths, family, width, weight and slant.
+ * @param[in] characterSetList A list that contains a character set for each description of the font list.
+ * @param[in] charcode The character for which a font is needed.
+ * @param[in] requestedPointSize The point size in 26.6 fractional points.
+ * @param[in] preferColor @e true if a color font is preferred.
+ *
+ * @return A valid font identifier, or zero if no font is found.
+ */
+ FontId FindFontForCharacter( const FontList& fontList,
+ const CharacterSetList& characterSetList,
+ Character charcode,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::FindDefaultFont()
+ */
+ FontId FindDefaultFont( Character charcode,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::FindFallbackFont()
+ */
+ FontId FindFallbackFont( Character charcode,
+ const FontDescription& preferredFontDescription,
+ PointSize26Dot6 requestedPointSize,
+ bool preferColor );
+
+ /**
+ * @see Dali::TextAbstraction::FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
+ *
+ * @param[in] cacheDescription Whether to cache the font description.
+ */
+ FontId GetFontId( const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex,
+ bool cacheDescription );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const FontDescription& preferredFontDescription, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
+ */
+ FontId GetFontId( const FontDescription& fontDescription,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontPath& path )
+ */
+ bool IsScalable( const FontPath& path );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontDescription& fontDescription )
+ */
+ bool IsScalable( const FontDescription& fontDescription );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes()
+ */
+ void GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes()
+ */
+ void GetFixedSizes( const FontDescription& fontDescription,
+ Dali::Vector< PointSize26Dot6 >& sizes );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetFontMetrics()
+ */
+ void GetFontMetrics( FontId fontId, FontMetrics& metrics );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetGlyphIndex()
+ */
+ GlyphIndex GetGlyphIndex( FontId fontId, Character charcode );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetGlyphMetrics()
+ */
+ bool GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal );
+
+ /**
+ * Helper for GetGlyphMetrics when using bitmaps
+ */
+ bool GetBitmapMetrics( GlyphInfo* array, uint32_t size, bool horizontal );
+
+ /**
+ * Helper for GetGlyphMetrics when using vectors
+ */
+ bool GetVectorMetrics( GlyphInfo* array, uint32_t size, bool horizontal );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
+ */
+ void CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
+ */
+ PixelData CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::CreateVectorBlob()
+ */
+ void CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::GetEllipsisGlyph()
+ */
+ const GlyphInfo& GetEllipsisGlyph( PointSize26Dot6 requestedPointSize );
+
+ /**
+ * @copydoc Dali::TextAbstraction::FontClient::IsColorGlyph()
+ */
+ bool IsColorGlyph( FontId fontId, GlyphIndex glyphIndex );
+
+private:
+
+ /**
+ * @brief Caches the fonts present in the platform.
+ *
+ * Calls GetFcFontSet() to retrieve the fonts.
+ */
+ void InitSystemFonts();
+
+ /**
+ * @brief Gets the FontDescription which matches the given pattern.
+ * @param[in] pattern pattern to match against.
+ * @param[out] fontDescription the resultant fontDescription that matched.
+ * @param[out] characterSet The character set for that pattern.
+ * @return true if match found.
+ */
+ bool MatchFontDescriptionToPattern( _FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, _FcCharSet** characterSet );
+
+ /**
+ * @brief Creates a font family pattern used to match fonts.
+ *
+ * @param[in] fontDescription The font to cache.
+ *
+ * @return The pattern.
+ */
+ _FcPattern* CreateFontFamilyPattern( const FontDescription& fontDescription ) const;
+
+ /**
+ * Retrieves the fonts present in the platform.
+ *
+ * @return A font fonfig data structure with the platform's fonts.
+ */
+ _FcFontSet* GetFcFontSet() const;
+
+ /**
+ * Retrieves a font config object's value from a pattern.
+ *
+ * @param[in] pattern The font config pattern.
+ * @param[in] n The object.
+ * @param[out] string The object's value.
+ *
+ * @return @e true if the operation is successful.
+ */
+ bool GetFcString( const _FcPattern* const pattern, const char* const n, std::string& string );
+
+ /**
+ * Retrieves a font config object's value from a pattern.
+ *
+ * @param[in] pattern The font config pattern.
+ * @param[in] n The object.
+ * @param[out] intVal The object's value.
+ *
+ * @return @e true if the operation is successful.
+ */
+ bool GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal );
+
+ /**
+ * @brief Creates a font.
+ *
+ * @param[in] path The path to the font file name.
+ * @param[in] requestedPointSize The requested point size.
+ * @param[in] faceIndex A face index.
+ * @param[in] cacheDescription Whether to cache the font description.
+ *
+ * @return The font identifier.
+ */
+ FontId CreateFont( const FontPath& path,
+ PointSize26Dot6 requestedPointSize,
+ FaceIndex faceIndex,
+ bool cacheDescription );
+
+ /**
+ * @brief Copy the FreeType bitmap to the given buffer.
+ *
+ * @param[out] data The bitmap data.
+ * @param[in] srcBitmap The FreeType bitmap.
+ */
+ void ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap );
+
+ /**
+ * @brief Finds in the cache if there is a triplet with the path to the font file name, the font point size and the face index.
+ * If there is one , if writes the font identifier in the param @p fontId.
+ *
+ * @param[in] path Path to the font file name.
+ * @param[in] requestedPointSize The font point size.
+ * @param[in] faceIndex The face index.
+ * @param[out] fontId The font identifier.
+ *
+ * @return @e true if there triplet is found.
+ */
+ bool FindFont( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex, FontId& fontId ) const;
+
+ /**
+ * @brief Finds in the cache a cluster 'font family, font width, font weight, font slant'
+ * If there is one, it writes the index to the vector with font descriptions in the param @p validatedFontId.
+ *
+ * @param[in] fontDescription The font to validate.
+ * @param[out] validatedFontId The index to the vector with font descriptions.
+ *
+ * @return @e true if the pair is found.
+ */
+ bool FindValidatedFont( const FontDescription& fontDescription,
+ FontDescriptionId& validatedFontId );
+
+ /**
+ * @brief Finds a fallback font list from the cache for a given font-description
+ *
+ * @param[in] fontDescription The font to validate.
+ * @param[out] A valid pointer to a font list, or NULL if not found.
+ * @param[out] characterSetList A valid pointer to a character set list, or NULL if not found.
+ */
+ bool FindFallbackFontList( const FontDescription& fontDescription,
+ FontList*& fontList,
+ CharacterSetList*& characterSetList );
+
+ /**
+ * @brief Finds in the cache a pair 'validated font identifier and font point size'.
+ * If there is one it writes the font identifier in the param @p fontId.
+ *
+ * @param[in] validatedFontId Index to the vector with font descriptions.
+ * @param[in] requestedPointSize The font point size.
+ * @param[out] fontId The font identifier.
+ *
+ * @return @e true if the pair is found.
+ */
+ bool FindFont( FontDescriptionId validatedFontId,
+ PointSize26Dot6 requestedPointSize,
+ FontId& fontId );
+
+ /**
+ * @brief Validate a font description.
+ *
+ * @param[in] fontDescription The font to validate.
+ * @param[out] validatedFontId Result of validation
+ */
+ void ValidateFont( const FontDescription& fontDescription,
+ FontDescriptionId& validatedFontId );
+
+ /**
+ * Helper for GetDefaultFonts etc.
+ *
+ * @param[in] fontDescription A font description.
+ * @param[out] fontList A list of the fonts which are a close match for fontDescription.
+ * @param[out] characterSetList A list of the character sets which are a close match for fontDescription.
+ */
+ void SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList );
+
+ /**
+ * Caches a font path.
+ *
+ * @param[in] ftFace The FreeType face.
+ * @param[in] id The font identifier.
+ * @param[in] requestedPointSize The font point size.
+ * @param[in] path Path to the font file name.
+ */
+ void CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path );
+
+ /**
+ * @brief Creates a character set from a given font's @p description.
+ *
+ * @param[in] description The font's description.
+ *
+ * @return A character set.
+ */
+ _FcCharSet* CreateCharacterSetFromDescription( const FontDescription& description ) const;
+
+private:
+
+ // Declared private and left undefined to avoid copies.
+ Plugin( const Plugin& );
+ // Declared private and left undefined to avoid copies.
+ Plugin& operator=( const Plugin& );
+
+private:
+
+ FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance.
+
+ unsigned int mDpiHorizontal; ///< Horizontal dpi.
+ unsigned int mDpiVertical; ///< Vertical dpi.
+
+ FontDescription mDefaultFontDescription; ///< The cached default font from the system
+
+ FontList mSystemFonts; ///< Cached system fonts.
+ FontList mDefaultFonts; ///< Cached default fonts.
+ CharacterSetList mDefaultFontCharacterSets;
+
+ std::vector<FallbackCacheItem> mFallbackCache; ///< Cached fallback font lists.
+
+ std::vector<FontFaceCacheItem> mFontCache; ///< Caches the FreeType face and font metrics of the triplet 'path to the font file name, font point size and face index'.
+ std::vector<FontDescriptionCacheItem> mValidatedFontCache; ///< Caches indices to the vector of font descriptions for a given font.
+ FontList mFontDescriptionCache; ///< Caches font descriptions for the validated font.
+ CharacterSetList mCharacterSetCache; ///< Caches character set lists for the validated font.
+ std::vector<FontIdCacheItem> mFontIdCache; ///< Caches font identifiers for the pairs of font point size and the index to the vector with font descriptions of the validated fonts.
+
+ VectorFontCache* mVectorFontCache; ///< Separate cache for vector data blobs etc.
+
+ Vector<EllipsisItem> mEllipsisCache; ///< Caches ellipsis glyphs for a particular point size.
+
+ bool mDefaultFontDescriptionCached : 1; ///< Whether the default font is cached or not
+};
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/segmentation-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+
+// EXTERNAL INCLUDES
+#include <third-party/libunibreak/linebreak.h>
+#include <third-party/libunibreak/wordbreak.h>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+struct Segmentation::Plugin
+{
+ void GetLineBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ LineBreakInfo* breakInfo )
+ {
+ set_linebreaks_utf32( text, numberOfCharacters, NULL, breakInfo );
+ }
+
+ void GetWordBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ WordBreakInfo* breakInfo )
+ {
+ set_wordbreaks_utf32( text, numberOfCharacters, NULL, breakInfo );
+ }
+};
+
+Segmentation::Segmentation()
+: mPlugin( NULL )
+{}
+
+Segmentation::~Segmentation()
+{
+ delete mPlugin;
+}
+
+TextAbstraction::Segmentation Segmentation::Get()
+{
+ TextAbstraction::Segmentation segmentationHandle;
+
+ SingletonService service( SingletonService::Get() );
+ if( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Segmentation ) );
+ if( handle )
+ {
+ // If so, downcast the handle
+ Segmentation* impl = dynamic_cast< Internal::Segmentation* >( handle.GetObjectPtr() );
+ segmentationHandle = TextAbstraction::Segmentation( impl );
+ }
+ else // create and register the object
+ {
+ segmentationHandle = TextAbstraction::Segmentation( new Segmentation );
+ service.Register( typeid( segmentationHandle ), segmentationHandle );
+ }
+ }
+
+ return segmentationHandle;
+}
+
+void Segmentation::GetLineBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ LineBreakInfo* breakInfo )
+{
+ CreatePlugin();
+
+ mPlugin->GetLineBreakPositions( text, numberOfCharacters, breakInfo );
+}
+
+void Segmentation::GetWordBreakPositions( const Character* const text,
+ Length numberOfCharacters,
+ WordBreakInfo* breakInfo )
+{
+ CreatePlugin();
+
+ mPlugin->GetWordBreakPositions( text, numberOfCharacters, breakInfo );
+}
+
+void Segmentation::CreatePlugin()
+{
+ if( !mPlugin )
+ {
+ mPlugin = new Plugin();
+ }
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/text-abstraction/shaping-impl.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/singleton-service-impl.h>
+#include <dali/devel-api/text-abstraction/font-client.h>
+#include <dali/devel-api/text-abstraction/glyph-info.h>
+#include <dali/integration-api/debug.h>
+
+// EXTERNAL INCLUDES
+#include <harfbuzz/hb.h>
+#include <harfbuzz/hb-ft.h>
+
+#include <ft2build.h>
+#include <iostream>
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+const char* DEFAULT_LANGUAGE = "en";
+const unsigned int DEFAULT_LANGUAGE_LENGTH = 2u;
+const float FROM_266 = 1.0f / 64.0f;
+
+const hb_script_t SCRIPT_TO_HARFBUZZ[] =
+{
+ HB_SCRIPT_COMMON,
+
+ HB_SCRIPT_COMMON, // ASCII_DIGITS
+ HB_SCRIPT_COMMON, // ASCII_PS
+
+ HB_SCRIPT_COMMON, // C1_CONTROLS
+ HB_SCRIPT_COMMON, // C1_PS
+ HB_SCRIPT_COMMON, // C1_MATH
+ HB_SCRIPT_COMMON, // SML_P
+ HB_SCRIPT_COMMON, // PHONETIC_U
+ HB_SCRIPT_COMMON, // PHONETIC_SS
+ HB_SCRIPT_COMMON, // NUMERIC_SS
+ HB_SCRIPT_COMMON, // LETTER_LIKE
+ HB_SCRIPT_COMMON, // NUMBER_FORMS
+ HB_SCRIPT_COMMON, // FRACTIONS_NF
+ HB_SCRIPT_COMMON, // NON_LATIN_LED
+ HB_SCRIPT_COMMON, // HWFW_S
+
+ HB_SCRIPT_CYRILLIC,
+ HB_SCRIPT_GREEK,
+ HB_SCRIPT_LATIN,
+
+ HB_SCRIPT_ARABIC,
+ HB_SCRIPT_HEBREW,
+
+ HB_SCRIPT_ARMENIAN,
+ HB_SCRIPT_GEORGIAN,
+
+ HB_SCRIPT_HAN,
+ HB_SCRIPT_HANGUL,
+ HB_SCRIPT_HIRAGANA,
+ HB_SCRIPT_KATAKANA,
+ HB_SCRIPT_BOPOMOFO,
+
+ HB_SCRIPT_BENGALI,
+ HB_SCRIPT_MYANMAR,
+ HB_SCRIPT_DEVANAGARI,
+ HB_SCRIPT_GUJARATI,
+ HB_SCRIPT_GURMUKHI,
+ HB_SCRIPT_KANNADA,
+ HB_SCRIPT_MALAYALAM,
+ HB_SCRIPT_ORIYA,
+ HB_SCRIPT_SINHALA,
+ HB_SCRIPT_TAMIL,
+ HB_SCRIPT_TELUGU,
+
+ HB_SCRIPT_LAO,
+ HB_SCRIPT_THAI,
+ HB_SCRIPT_KHMER,
+ HB_SCRIPT_JAVANESE,
+ HB_SCRIPT_SUNDANESE,
+
+ HB_SCRIPT_ETHIOPIC,
+ HB_SCRIPT_OL_CHIKI,
+ HB_SCRIPT_TAGALOG,
+ HB_SCRIPT_MEETEI_MAYEK,
+
+ HB_SCRIPT_UNKNOWN, // EMOJI
+ HB_SCRIPT_UNKNOWN, // SYMBOLS1
+ HB_SCRIPT_UNKNOWN, // SYMBOLS2
+ HB_SCRIPT_UNKNOWN, // SYMBOLS3
+ HB_SCRIPT_UNKNOWN, // SYMBOLS4
+ HB_SCRIPT_UNKNOWN, // SYMBOLS5
+ HB_SCRIPT_UNKNOWN
+};
+
+struct Shaping::Plugin
+{
+ Plugin()
+ : mFreeTypeLibrary( NULL ),
+ mIndices(),
+ mAdvance(),
+ mCharacterMap(),
+ mFontId( 0u )
+ {
+ }
+
+ ~Plugin()
+ {
+ FT_Done_FreeType( mFreeTypeLibrary );
+ }
+
+ void Initialize()
+ {
+ int error = FT_Init_FreeType( &mFreeTypeLibrary );
+ if( FT_Err_Ok != error )
+ {
+ DALI_LOG_ERROR( "FreeType Init error: %d\n", error );
+ }
+ }
+
+ Length Shape( const Character* const text,
+ Length numberOfCharacters,
+ FontId fontId,
+ Script script )
+ {
+ // Clear previoursly shaped texts.
+ mIndices.Clear();
+ mAdvance.Clear();
+ mCharacterMap.Clear();
+ mOffset.Clear();
+ mFontId = fontId;
+
+ // Reserve some space to avoid reallocations.
+ const Length numberOfGlyphs = static_cast<Length>( 1.3f * static_cast<float>( numberOfCharacters ) );
+ mIndices.Reserve( numberOfGlyphs );
+ mAdvance.Reserve( numberOfGlyphs );
+ mCharacterMap.Reserve( numberOfGlyphs );
+ mOffset.Reserve( 2u * numberOfGlyphs );
+
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+
+ // Get the font's path file name from the font Id.
+ FontDescription fontDescription;
+ fontClient.GetDescription( fontId, fontDescription );
+
+ // Create a FreeType font's face.
+ FT_Face face;
+ FT_Error retVal = FT_New_Face( mFreeTypeLibrary, fontDescription.path.c_str(), 0u, &face );
+ if( FT_Err_Ok != retVal )
+ {
+ DALI_LOG_ERROR( "Failed to open face: %s\n", fontDescription.path.c_str() );
+ return 0u;
+ }
+
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ fontClient.GetDpi( horizontalDpi, verticalDpi );
+
+ FT_Set_Char_Size( face,
+ 0u,
+ fontClient.GetPointSize( fontId ),
+ horizontalDpi,
+ verticalDpi );
+
+ /* Get our harfbuzz font struct */
+ hb_font_t* harfBuzzFont;
+ harfBuzzFont = hb_ft_font_create( face, NULL );
+
+ /* Create a buffer for harfbuzz to use */
+ hb_buffer_t* harfBuzzBuffer = hb_buffer_create();
+
+ const bool rtlDirection = IsRightToLeftScript( script );
+ hb_buffer_set_direction( harfBuzzBuffer,
+ rtlDirection ? HB_DIRECTION_RTL : HB_DIRECTION_LTR ); /* or LTR */
+
+ hb_buffer_set_script( harfBuzzBuffer,
+ SCRIPT_TO_HARFBUZZ[ script ] ); /* see hb-unicode.h */
+
+
+ char* currentLocale = setlocale(LC_MESSAGES,NULL);
+
+ std::istringstream stringStream( currentLocale );
+ std::string localeString;
+ std::getline(stringStream, localeString, '_');
+ hb_buffer_set_language( harfBuzzBuffer, hb_language_from_string( localeString.c_str(), localeString.size() ) );
+
+ /* Layout the text */
+ hb_buffer_add_utf32( harfBuzzBuffer, text, numberOfCharacters, 0u, numberOfCharacters );
+
+ hb_shape( harfBuzzFont, harfBuzzBuffer, NULL, 0u );
+
+ /* Get glyph data */
+ unsigned int glyphCount;
+ hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( harfBuzzBuffer, &glyphCount );
+ hb_glyph_position_t *glyphPositions = hb_buffer_get_glyph_positions( harfBuzzBuffer, &glyphCount );
+ const GlyphIndex lastGlyphIndex = glyphCount - 1u;
+ for( GlyphIndex i = 0u; i < glyphCount; )
+ {
+ if( rtlDirection )
+ {
+ // If the direction is right to left, Harfbuzz retrieves the glyphs in the visual order.
+ // The glyphs are needed in the logical order to layout the text in lines.
+ // Do not change the order of the glyphs if they belong to the same cluster.
+ GlyphIndex rtlIndex = lastGlyphIndex - i;
+
+ unsigned int cluster = glyphInfo[rtlIndex].cluster;
+ unsigned int previousCluster = cluster;
+ Length numberOfGlyphsInCluster = 0u;
+
+ while( ( cluster == previousCluster ) )
+ {
+ ++numberOfGlyphsInCluster;
+ previousCluster = cluster;
+
+ if( rtlIndex > 0u )
+ {
+ --rtlIndex;
+
+ cluster = glyphInfo[rtlIndex].cluster;
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ rtlIndex = lastGlyphIndex - ( i + ( numberOfGlyphsInCluster - 1u ) );
+
+ for( GlyphIndex j = 0u; j < numberOfGlyphsInCluster; ++j )
+ {
+ const GlyphIndex index = rtlIndex + j;
+
+ mIndices.PushBack( glyphInfo[index].codepoint );
+ mAdvance.PushBack( floor( glyphPositions[index].x_advance * FROM_266 ) );
+ mCharacterMap.PushBack( glyphInfo[index].cluster );
+ mOffset.PushBack( floor( glyphPositions[index].x_offset * FROM_266 ) );
+ mOffset.PushBack( floor( glyphPositions[index].y_offset * FROM_266 ) );
+ }
+
+ i += numberOfGlyphsInCluster;
+ }
+ else
+ {
+ mIndices.PushBack( glyphInfo[i].codepoint );
+ mAdvance.PushBack( floor( glyphPositions[i].x_advance * FROM_266 ) );
+ mCharacterMap.PushBack( glyphInfo[i].cluster );
+ mOffset.PushBack( floor( glyphPositions[i].x_offset * FROM_266 ) );
+ mOffset.PushBack( floor( glyphPositions[i].y_offset * FROM_266 ) );
+
+ ++i;
+ }
+ }
+
+ /* Cleanup */
+ hb_buffer_destroy( harfBuzzBuffer );
+ hb_font_destroy( harfBuzzFont );
+ FT_Done_Face( face );
+
+ return mIndices.Count();
+ }
+
+ void GetGlyphs( GlyphInfo* glyphInfo,
+ CharacterIndex* glyphToCharacterMap )
+ {
+ Vector<CharacterIndex>::ConstIterator indicesIt = mIndices.Begin();
+ Vector<float>::ConstIterator advanceIt = mAdvance.Begin();
+ Vector<float>::ConstIterator offsetIt = mOffset.Begin();
+ Vector<CharacterIndex>::ConstIterator characterMapIt = mCharacterMap.Begin();
+
+ for( GlyphIndex index = 0u, size = mIndices.Count(); index < size; ++index )
+ {
+ GlyphInfo& glyph = *( glyphInfo + index );
+ CharacterIndex& glyphToCharacter = *( glyphToCharacterMap + index );
+
+ glyph.fontId = mFontId;
+ glyph.index = *( indicesIt + index );
+ glyph.advance = *( advanceIt + index );
+
+ const GlyphIndex offsetIndex = 2u * index;
+ glyph.xBearing = *( offsetIt + offsetIndex );
+ glyph.yBearing = *( offsetIt + offsetIndex + 1u );
+
+ glyphToCharacter = *( characterMapIt + index );
+ }
+ }
+
+ FT_Library mFreeTypeLibrary;
+
+ Vector<CharacterIndex> mIndices;
+ Vector<float> mAdvance;
+ Vector<float> mOffset;
+ Vector<CharacterIndex> mCharacterMap;
+ FontId mFontId;
+};
+
+Shaping::Shaping()
+: mPlugin( NULL )
+{
+}
+
+Shaping::~Shaping()
+{
+ delete mPlugin;
+}
+
+TextAbstraction::Shaping Shaping::Get()
+{
+ TextAbstraction::Shaping shapingHandle;
+
+ SingletonService service( SingletonService::Get() );
+ if( service )
+ {
+ // Check whether the singleton is already created
+ Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Shaping ) );
+ if( handle )
+ {
+ // If so, downcast the handle
+ Shaping* impl = dynamic_cast< Internal::Shaping* >( handle.GetObjectPtr() );
+ shapingHandle = TextAbstraction::Shaping( impl );
+ }
+ else // create and register the object
+ {
+ shapingHandle = TextAbstraction::Shaping( new Shaping );
+ service.Register( typeid( shapingHandle ), shapingHandle );
+ }
+ }
+
+ return shapingHandle;
+}
+
+Length Shaping::Shape( const Character* const text,
+ Length numberOfCharacters,
+ FontId fontId,
+ Script script )
+{
+ CreatePlugin();
+
+ return mPlugin->Shape( text,
+ numberOfCharacters,
+ fontId,
+ script );
+}
+
+void Shaping::GetGlyphs( GlyphInfo* glyphInfo,
+ CharacterIndex* glyphToCharacterMap )
+{
+ CreatePlugin();
+
+ mPlugin->GetGlyphs( glyphInfo,
+ glyphToCharacterMap );
+}
+
+void Shaping::CreatePlugin()
+{
+ if( !mPlugin )
+ {
+ mPlugin = new Plugin();
+ mPlugin->Initialize();
+ }
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/text/glyphy/vector-font-cache.h>
+
+// EXTERNAL INCLUDES
+#include <vector>
+#include <math.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/text/glyphy/glyphy.h>
+#include <dali/internal/text/glyphy/glyphy-freetype.h>
+
+using namespace std;
+
+namespace
+{
+
+const unsigned int INITIAL_GLYPH_CAPACITY = 50;
+const double MIN_FONT_SIZE = 10;
+
+static glyphy_bool_t
+accumulate_endpoint( glyphy_arc_endpoint_t* endpoint,
+ vector<glyphy_arc_endpoint_t>* endpoints )
+{
+ endpoints->push_back( *endpoint );
+ return true;
+}
+
+} // unnamed namespace
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+typedef vector<VectorBlob> BlobArray;
+
+struct VectorGlyph
+{
+ /**
+ * @brief Create a vector-based glyph.
+ */
+ static VectorGlyph* New( FT_Face face,
+ FontId fontId,
+ GlyphIndex index,
+ glyphy_arc_accumulator_t* accumulator )
+ {
+ VectorGlyph* newGlyph = new VectorGlyph();
+ newGlyph->blobData.resize( 1024 * 16 );
+
+ if( FT_Err_Ok != FT_Load_Glyph( face,
+ index,
+ FT_LOAD_NO_BITMAP |
+ FT_LOAD_NO_HINTING |
+ FT_LOAD_NO_AUTOHINT |
+ FT_LOAD_NO_SCALE |
+ FT_LOAD_LINEAR_DESIGN |
+ FT_LOAD_IGNORE_TRANSFORM))
+ {
+ DALI_LOG_ERROR( "FT_Load_Glyph failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+
+ const double upem = static_cast<double>( face->units_per_EM );
+ const double tolerance = upem * 1.0f/2048.0f;
+
+ glyphy_arc_accumulator_reset( accumulator);
+ glyphy_arc_accumulator_set_tolerance( accumulator, tolerance );
+
+ vector<glyphy_arc_endpoint_t> endpoints;
+ glyphy_arc_accumulator_set_callback( accumulator,
+ reinterpret_cast<glyphy_arc_endpoint_accumulator_callback_t>( accumulate_endpoint ),
+ &endpoints );
+
+ if( FT_Err_Ok != glyphy_freetype_outline_decompose( &face->glyph->outline, accumulator ) )
+ {
+ DALI_LOG_ERROR( "glyphy_freetype_outline_decompose failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+
+ DALI_ASSERT_DEBUG( glyphy_arc_accumulator_get_error(accumulator) <= tolerance && "glyphy_arc_accumulator_get_error > tolerance" );
+
+ if( endpoints.size() )
+ {
+ glyphy_outline_winding_from_even_odd( &endpoints[0], endpoints.size (), false );
+ }
+
+ unsigned int blobLength( 0 );
+ double averageFetchAchieved( 0.0 );
+ if (!glyphy_arc_list_encode_blob( endpoints.size() ? &endpoints[0] : NULL,
+ endpoints.size(),
+ &newGlyph->blobData[0],
+ newGlyph->blobData.capacity(),
+ upem / ( MIN_FONT_SIZE * M_SQRT2 ),
+ 4,
+ &averageFetchAchieved,
+ &blobLength,
+ &newGlyph->nominalWidth,
+ &newGlyph->nominalHeight,
+ &newGlyph->extents ) )
+ {
+ DALI_LOG_ERROR( "glyphy_arc_list_encode_blob failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+ newGlyph->blobData.resize( blobLength );
+
+ glyphy_extents_scale( &newGlyph->extents, 1.0/upem, 1.0/upem );
+
+ newGlyph->glyphInfo.fontId = fontId;
+ newGlyph->glyphInfo.index = index;
+
+ if( glyphy_extents_is_empty( &newGlyph->extents ) )
+ {
+ newGlyph->glyphInfo.width = 0.0f;
+ newGlyph->glyphInfo.height = 0.0f;
+
+ newGlyph->glyphInfo.xBearing = 0.0f;
+ newGlyph->glyphInfo.yBearing = 0.0f;
+ }
+ else
+ {
+ newGlyph->glyphInfo.width = (newGlyph->extents.max_x - newGlyph->extents.min_x);
+ newGlyph->glyphInfo.height = (newGlyph->extents.max_y - newGlyph->extents.min_y);
+
+ newGlyph->glyphInfo.xBearing = newGlyph->extents.min_x;
+ newGlyph->glyphInfo.yBearing = newGlyph->glyphInfo.height + (newGlyph->extents.min_y);
+ }
+
+ newGlyph->glyphInfo.advance = face->glyph->metrics.horiAdvance / upem;
+ newGlyph->glyphInfo.scaleFactor = 0.0f;
+
+ return newGlyph;
+ }
+
+ VectorGlyph()
+ : advance( 0.0 ),
+ nominalWidth( 0 ),
+ nominalHeight( 0 ),
+ glyphInfo(),
+ blobData()
+ {
+ glyphy_extents_clear( &extents );
+ }
+
+ glyphy_extents_t extents;
+ double advance;
+ unsigned int nominalWidth;
+ unsigned int nominalHeight;
+ GlyphInfo glyphInfo;
+ BlobArray blobData;
+};
+
+typedef vector<VectorGlyph*> GlyphCache;
+
+struct VectorFont
+{
+ VectorFont( FT_Face face )
+ : mFace( face ),
+ mGlyphCache()
+ {
+ mGlyphCache.reserve( INITIAL_GLYPH_CAPACITY );
+ }
+
+ FT_Face mFace;
+ GlyphCache mGlyphCache;
+};
+
+struct VectorFontCache::Impl
+{
+ Impl( FT_Library freeTypeLibrary )
+ : mFreeTypeLibrary( freeTypeLibrary ),
+ mIdLookup(),
+ mVectorFonts(),
+ mAccumulator( NULL )
+ {
+ mAccumulator = glyphy_arc_accumulator_create();
+ }
+
+ ~Impl()
+ {
+ glyphy_arc_accumulator_destroy( mAccumulator );
+ }
+
+private:
+
+ // Declared private and left undefined to avoid copies.
+ Impl( const Impl& );
+ // Declared private and left undefined to avoid copies.
+ Impl& operator=( const Impl& );
+
+public:
+
+ FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance.
+
+ vector<string> mIdLookup;
+
+ vector<VectorFont*> mVectorFonts;
+
+ glyphy_arc_accumulator_t* mAccumulator;
+};
+
+VectorFontCache::VectorFontCache( FT_Library freeTypeLibrary )
+: mImpl( NULL )
+{
+ mImpl = new Impl( freeTypeLibrary );
+}
+
+VectorFontCache::~VectorFontCache()
+{
+ delete mImpl;
+}
+
+FontId VectorFontCache::GetFontId( const std::string& url )
+{
+ FontId id( 0 );
+
+ if( mImpl )
+ {
+ if( ! FindFont( url, id ) )
+ {
+ id = CreateFont( url );
+ }
+ }
+
+ return id;
+}
+
+void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo )
+{
+ if( mImpl )
+ {
+ if( vectorFontId > 0 &&
+ vectorFontId-1 < mImpl->mVectorFonts.size() )
+ {
+ VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
+ GlyphCache& cache = font->mGlyphCache;
+
+ bool foundGlyph( false );
+ unsigned int foundIndex( 0 );
+ for( unsigned int i=0; i<cache.size(); ++i )
+ {
+ VectorGlyph* glyph = cache[i];
+
+ if( glyph->glyphInfo.index == glyphInfo.index )
+ {
+ foundIndex = i;
+ foundGlyph = true;
+ break;
+ }
+ }
+
+ if( foundGlyph )
+ {
+ VectorGlyph* glyph = cache[foundIndex];
+ // Note - this clobbers the original fontId, but helps avoid duplicating identical blobs
+ // e.g. if when the same font family is requested in different point-sizes
+ glyphInfo = glyph->glyphInfo;
+ }
+ else
+ {
+ VectorGlyph* newGlyph = VectorGlyph::New( font->mFace,
+ glyphInfo.fontId,
+ glyphInfo.index,
+ mImpl->mAccumulator );
+
+ if( newGlyph )
+ {
+ glyphInfo = newGlyph->glyphInfo;
+
+ cache.push_back( newGlyph );
+ }
+ }
+ }
+ }
+}
+
+void VectorFontCache::GetVectorBlob( FontId vectorFontId,
+ FontId fontId,
+ GlyphIndex glyphIndex,
+ VectorBlob*& blob,
+ unsigned int& blobLength,
+ unsigned int& nominalWidth,
+ unsigned int& nominalHeight )
+{
+ if( mImpl )
+ {
+ if( vectorFontId > 0 &&
+ vectorFontId-1 < mImpl->mVectorFonts.size() )
+ {
+ VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
+ GlyphCache& cache = font->mGlyphCache;
+
+ bool foundGlyph( false );
+ unsigned int foundIndex( 0 );
+ for( unsigned int i=0; i<cache.size(); ++i )
+ {
+ VectorGlyph* glyph = cache[i];
+
+ if( glyph->glyphInfo.index == glyphIndex )
+ {
+ foundIndex = i;
+ foundGlyph = true;
+ break;
+ }
+ }
+
+ if( foundGlyph )
+ {
+ VectorGlyph* glyph = cache[foundIndex];
+
+ blob = &glyph->blobData[0];
+ blobLength = glyph->blobData.size();
+ nominalWidth = glyph->nominalWidth;
+ nominalHeight = glyph->nominalHeight;
+ }
+ else
+ {
+ VectorGlyph* newGlyph = VectorGlyph::New( font->mFace, fontId, glyphIndex, mImpl->mAccumulator );
+
+ if( newGlyph )
+ {
+ blob = &newGlyph->blobData[0];
+ blobLength = newGlyph->blobData.size();
+ nominalWidth = newGlyph->nominalWidth;
+ nominalHeight = newGlyph->nominalHeight;
+
+ cache.push_back( newGlyph );
+ }
+ }
+ }
+ }
+}
+
+bool VectorFontCache::FindFont( const string& url, FontId& vectorFontId ) const
+{
+ vectorFontId = 0u;
+
+ const vector<string>& idLookup = mImpl->mIdLookup;
+
+ for( unsigned int i=0; i<idLookup.size(); ++i, ++vectorFontId )
+ {
+ if( url == idLookup[i] )
+ {
+ ++vectorFontId;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+FontId VectorFontCache::CreateFont( const string& url )
+{
+ FontId id( 0 );
+
+ // Create & cache new font face
+ FT_Face face;
+ int error = FT_New_Face( mImpl->mFreeTypeLibrary,
+ url.c_str(),
+ 0,
+ &face );
+
+ if( FT_Err_Ok == error )
+ {
+ mImpl->mIdLookup.push_back( url );
+ id = mImpl->mIdLookup.size();
+
+ VectorFont* newFont = new VectorFont( face );
+ mImpl->mVectorFonts.push_back( newFont );
+
+ DALI_ASSERT_DEBUG( mImpl->mIdLookup.size() == mImpl->mVectorFonts.size() );
+ }
+
+ return id;
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/video/common/video-player-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dlfcn.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/object/any.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace // unnamed namespace
+{
+
+#if _GLIBCXX_USE_CXX11_ABI
+const char* VIDEO_PLUGIN_SO( "libdali-video-player-plugin.so" );
+#else
+const char* VIDEO_PLUGIN_SO( "libdali-video-player-plugin-cxx03.so" );
+#endif
+
+Dali::BaseHandle Create()
+{
+ return Dali::VideoPlayer::New();
+}
+
+Dali::TypeRegistration type( typeid( Dali::VideoPlayer ), typeid( Dali::BaseHandle ), Create );
+
+} // unnamed namespace
+
+VideoPlayerPtr VideoPlayer::New()
+{
+ VideoPlayerPtr player = new VideoPlayer();
+ return player;
+}
+
+VideoPlayer::VideoPlayer()
+: mPlugin( NULL ),
+ mHandle( NULL ),
+ mCreateVideoPlayerPtr( NULL ),
+ mDestroyVideoPlayerPtr( NULL )
+{
+}
+
+VideoPlayer::~VideoPlayer()
+{
+ if( mHandle != NULL )
+ {
+ if( mDestroyVideoPlayerPtr != NULL )
+ {
+ mDestroyVideoPlayerPtr( mPlugin );
+ }
+
+ dlclose( mHandle );
+ }
+}
+
+void VideoPlayer::Initialize()
+{
+ char* error = NULL;
+
+ mHandle = dlopen( VIDEO_PLUGIN_SO, RTLD_LAZY );
+
+ error = dlerror();
+ if( mHandle == NULL || error != NULL )
+ {
+ DALI_LOG_ERROR( "VideoPlayer::Initialize(), dlopen error: %s\n", error );
+ return;
+ }
+
+ mCreateVideoPlayerPtr = reinterpret_cast< CreateVideoPlayerFunction >( dlsym( mHandle, "CreateVideoPlayerPlugin" ) );
+ if( mCreateVideoPlayerPtr == NULL )
+ {
+ DALI_LOG_ERROR( "Can't load symbol CreateVideoPlayerPlugin(), error: %s\n", error );
+ return;
+ }
+
+ mPlugin = mCreateVideoPlayerPtr();
+
+ if( mPlugin == NULL )
+ {
+ DALI_LOG_ERROR( "Can't create the VideoPlayerPlugin object\n" );
+ return;
+ }
+
+ mDestroyVideoPlayerPtr = reinterpret_cast< DestroyVideoPlayerFunction >( dlsym( mHandle, "DestroyVideoPlayerPlugin" ) );
+ if( mDestroyVideoPlayerPtr == NULL )
+ {
+ DALI_LOG_ERROR( "Can't load symbol DestroyVideoPlayerPlugin(), error: %s\n", error );
+ return;
+ }
+
+}
+
+void VideoPlayer::SetUrl( const std::string& url )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetUrl( url );
+ }
+}
+
+std::string VideoPlayer::GetUrl()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->GetUrl();
+ }
+
+ return std::string();
+}
+
+void VideoPlayer::SetLooping(bool looping)
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetLooping( looping );
+ }
+}
+
+bool VideoPlayer::IsLooping()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->IsLooping();
+ }
+
+ return false;
+}
+
+void VideoPlayer::Play()
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->Play();
+ }
+}
+
+void VideoPlayer::Pause()
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->Pause();
+ }
+}
+
+void VideoPlayer::Stop()
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->Stop();
+ }
+}
+
+void VideoPlayer::SetMute( bool mute )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetMute( mute );
+ }
+}
+
+bool VideoPlayer::IsMuted()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->IsMuted();
+ }
+
+ return false;
+}
+
+void VideoPlayer::SetVolume( float left, float right )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetVolume( left, right );
+ }
+}
+
+void VideoPlayer::GetVolume( float& left, float& right )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->GetVolume( left, right );
+ }
+}
+
+void VideoPlayer::SetRenderingTarget( Dali::Any target )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetRenderingTarget( target );
+ }
+}
+
+void VideoPlayer::SetPlayPosition( int millisecond )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetPlayPosition( millisecond );
+ }
+}
+
+int VideoPlayer::GetPlayPosition()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->GetPlayPosition();
+ }
+ return 0;
+}
+
+void VideoPlayer::SetDisplayArea( DisplayArea area )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetDisplayArea( area );
+ }
+}
+
+void VideoPlayer::SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->SetDisplayRotation( rotation );
+ }
+}
+
+Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->GetDisplayRotation();
+ }
+
+ return Dali::VideoPlayerPlugin::ROTATION_NONE;
+}
+
+Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal()
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->FinishedSignal();
+ }
+
+ return mFinishedSignal;
+}
+
+void VideoPlayer::Forward( int millisecond )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->Forward( millisecond );
+ }
+}
+
+void VideoPlayer::Backward( int millisecond )
+{
+ if( mPlugin != NULL )
+ {
+ mPlugin->Backward( millisecond );
+ }
+}
+
+bool VideoPlayer::IsVideoTextureSupported() const
+{
+ if( mPlugin != NULL )
+ {
+ return mPlugin->IsVideoTextureSupported();
+ }
+
+ return false;
+}
+
+} // namespace Adaptor;
+} // namespace Internal;
+} // namespace Dali;
+
--- /dev/null
+#ifndef __DALI_VIDEO_PLAYER_IMPL_H__
+#define __DALI_VIDEO_PLAYER_IMPL_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/video-player.h>
+#include <dali/devel-api/adaptor-framework/video-player-plugin.h>
+
+namespace Dali
+{
+class Any;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class VideoPlayer;
+
+typedef IntrusivePtr< VideoPlayer > VideoPlayerPtr;
+
+/**
+ * @brief VideoPlayer class is used for video playback.
+ * @SINCE_1_1.24
+ */
+class VideoPlayer: public Dali::BaseObject
+{
+public:
+
+ /**
+ * @brief Creates a new VideoPlayer handle
+ * @SINCE_1_1.24
+ * @return VideoPlayer pointer
+ */
+ static VideoPlayerPtr New();
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetUrl()
+ */
+ void SetUrl( const std::string& url );
+
+ /**
+ * @copydoc Dali::VideoPlayer::GetUrl()
+ */
+ std::string GetUrl();
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetLooping()
+ */
+ void SetLooping(bool looping);
+
+ /**
+ * @copydoc Dali::VideoPlayer::IsLooping()
+ */
+ bool IsLooping();
+
+ /**
+ * @copydoc Dali::VideoPlayer::Play()
+ */
+ void Play();
+
+ /**
+ * @copydoc Dali::VideoPlayer::Pause()
+ */
+ void Pause();
+
+ /**
+ * @copydoc Dali::VideoPlayer::Stop()
+ */
+ void Stop();
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetMute()
+ */
+ void SetMute( bool mute );
+
+ /**
+ * @copydoc Dali::VideoPlayer::IsMuted()
+ */
+ bool IsMuted();
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetVolume()
+ */
+ void SetVolume( float left, float right );
+
+ /**
+ * @copydoc Dali::VideoPlayer::GetVolume()
+ */
+ void GetVolume( float& left, float& right );
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetRenderingTarget()
+ */
+ void SetRenderingTarget( Dali::Any target );
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetPlayPosition()
+ */
+ void SetPlayPosition( int millisecond );
+
+ /**
+ * @copydoc Dali::VideoPlayer::GetPlayPosition()
+ */
+ int GetPlayPosition();
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetDisplayArea()
+ */
+ void SetDisplayArea( DisplayArea area );
+
+ /**
+ * @copydoc Dali::VideoPlayer::SetSetDisplayRotation()
+ */
+ void SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation );
+
+ /**
+ * @copydoc Dali::VideoPlayer::GetDisplayRotation()
+ */
+ Dali::VideoPlayerPlugin::DisplayRotation GetDisplayRotation();
+
+ /**
+ * @copydoc Dali::VideoPlayer::FinishedSignal()
+ */
+ Dali::VideoPlayerPlugin::VideoPlayerSignalType& FinishedSignal();
+
+ /**
+ * @brief Initializes member data.
+ */
+ void Initialize();
+
+ /**
+ * @brief Dali::VideoPlayer::Forward()
+ */
+ void Forward( int millisecond );
+
+ /**
+ * @brief Dali::VideoPlayer::Backward()
+ */
+ void Backward( int millisecond );
+
+ /**
+ * @brief Dali::VideoPlayer::IsVideoTextureSupported()
+ */
+ bool IsVideoTextureSupported() const;
+
+private:
+
+ /**
+ * @brief Constructor.
+ * @SINCE_1_1.24
+ */
+ VideoPlayer();
+
+ /**
+ * @brief Destructor.
+ * @SINCE_1_1.24
+ */
+ virtual ~VideoPlayer();
+
+ // Undefined copy constructor
+ VideoPlayer( const VideoPlayer& player );
+
+ // Undefined assignment operator
+ VideoPlayer& operator=( const VideoPlayer& player );
+
+private:
+
+ Dali::VideoPlayerPlugin* mPlugin; ///< Videoplayer plugin handle
+ void* mHandle; ///< Handle for the loaded library
+
+ typedef Dali::VideoPlayerPlugin* (*CreateVideoPlayerFunction)();
+ typedef void (*DestroyVideoPlayerFunction)( Dali::VideoPlayerPlugin* plugin );
+
+ CreateVideoPlayerFunction mCreateVideoPlayerPtr;
+ DestroyVideoPlayerFunction mDestroyVideoPlayerPtr;
+
+ Dali::VideoPlayerPlugin::VideoPlayerSignalType mFinishedSignal;
+};
+
+} // namespace Adaptor
+} // namespace Internal
+
+inline static Internal::Adaptor::VideoPlayer& GetImplementation( Dali::VideoPlayer& player )
+{
+ DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." );
+
+ BaseObject& handle = player.GetBaseObject();
+
+ return static_cast< Internal::Adaptor::VideoPlayer& >( handle );
+}
+
+inline static const Internal::Adaptor::VideoPlayer& GetImplementation( const Dali::VideoPlayer& player )
+{
+ DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." );
+
+ const BaseObject& handle = player.GetBaseObject();
+
+ return static_cast< const Internal::Adaptor::VideoPlayer& >( handle );
+}
+
+} // namespace Dali;
+
+#endif
+
--- /dev/null
+
+
+# module: video, backend: common
+adaptor_video_common_src_files=\
+ ${adaptor_video_dir}/common/video-player-impl.cpp
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_FACTORY_H
+#define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_FACTORY_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+class DisplayConnection;
+class DisplayConnectionFactory
+{
+public:
+
+ DisplayConnectionFactory() = default;
+ virtual ~DisplayConnectionFactory() = default;
+
+ virtual std::unique_ptr<Dali::Internal::Adaptor::DisplayConnection> CreateDisplayConnection() = 0;
+
+};
+
+extern std::unique_ptr<DisplayConnectionFactory> GetDisplayConnectionFactory();
+
+extern void DisplayConnectionFactoryGetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_FACTORY_H
--- /dev/null
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection-impl.h>
+#include <dali/internal/window-system/common/display-connection-factory.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ // Call static factory function
+ DisplayConnectionFactoryGetDpi( dpiHorizontal, dpiVertical );
+}
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_IMPL_H
+#define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_IMPL_H
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+#include <memory>
+
+namespace Dali
+{
+
+class RenderSurface;
+class DisplayConnection;
+
+namespace Internal
+{
+namespace Adaptor
+{
+class Impl;
+/**
+ * DisplayConnection implementation
+ */
+class DisplayConnection : public Dali::BaseObject
+{
+public:
+
+ /**
+ * @brief Default constructor
+ */
+ DisplayConnection() = default;
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ *
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New();
+
+public:
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDisplay
+ */
+ virtual Any GetDisplay() = 0;
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDpi
+ */
+ static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+ /**
+ * @copydoc Dali::DisplayConnection::ConsumeEvents
+ */
+ virtual void ConsumeEvents() = 0;
+
+ /**
+ * @copydoc Dali::DisplayConnection::InitializeEgl
+ */
+ virtual bool InitializeEgl(EglInterface& egl) = 0;
+
+ virtual void SetSurfaceType( RenderSurface::Type type ) = 0;
+
+public:
+
+ /**
+ * Destructor
+ */
+ ~DisplayConnection() override = default;
+
+protected:
+
+ // Undefined
+ DisplayConnection(const DisplayConnection&) = delete;
+
+ // Undefined
+ DisplayConnection& operator=(const DisplayConnection& rhs) = delete;
+
+};
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_IMPL_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/display-connection.h>
+#include <dali/internal/window-system/common/display-connection-factory.h>
+// EXTERNAL INCLUDES
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection-impl.h>
+#include <dali/internal/window-system/common/display-connection-factory.h>
+#include <dali/integration-api/egl-interface.h>
+
+namespace Dali
+{
+
+DisplayConnection* DisplayConnection::New()
+{
+ auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory();
+ auto displayConnection = factory->CreateDisplayConnection();
+
+ Internal::Adaptor::DisplayConnection* internal( displayConnection.release() );
+
+ return new DisplayConnection(internal);
+}
+
+DisplayConnection* DisplayConnection::New( RenderSurface::Type type )
+{
+ auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory();
+ auto displayConnection = factory->CreateDisplayConnection();
+
+ Internal::Adaptor::DisplayConnection* internal( displayConnection.release() );
+
+ internal->SetSurfaceType( type );
+
+ return new DisplayConnection(internal);
+}
+
+DisplayConnection::DisplayConnection() = default;
+
+DisplayConnection::~DisplayConnection() = default;
+
+DisplayConnection::DisplayConnection(Internal::Adaptor::DisplayConnection* impl)
+{
+ mImpl.reset( impl );
+}
+
+Any DisplayConnection::GetDisplay()
+{
+ return mImpl->GetDisplay();
+}
+
+void DisplayConnection::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ Internal::Adaptor::DisplayConnection::GetDpi(dpiHorizontal, dpiVertical);
+}
+
+void DisplayConnection::ConsumeEvents()
+{
+ mImpl->ConsumeEvents();
+}
+
+bool DisplayConnection::InitializeEgl(EglInterface& egl)
+{
+ return mImpl->InitializeEgl(egl);
+}
+
+}
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_H
+#define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_H
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/any.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+
+#include <memory>
+
+namespace Dali
+{
+
+class EglInterface;
+
+namespace Internal
+{
+namespace Adaptor
+{
+class DisplayConnection;
+}
+}
+
+class DisplayConnection
+{
+public:
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ *
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New();
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ * Native surface will need this instead of DisplayConnection::New()
+ *
+ * @param[in] type Render surface type
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New( RenderSurface::Type type );
+
+ /**
+ * @brief Create a DisplayConnection handle; this can be initialised with DisplayConnection::New().
+ *
+ * Calling member functions with an uninitialised handle is not allowed.
+ */
+ DisplayConnection();
+
+ /**
+ * @brief Destructor
+ *
+ * This is non-virtual since derived Handle types must not contain data or virtual methods.
+ */
+ ~DisplayConnection();
+
+ /**
+ * @brief Get display
+ *
+ * @return display
+ */
+ Any GetDisplay();
+
+ /**
+ * @brief Get DPI
+ * @param[out] dpiHorizontal set to the horizontal dpi
+ * @param[out] dpiVertical set to the vertical dpi
+ */
+ static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+ /**
+ * @brief Consumes any possible events on the queue so that there is no leaking between frames
+ */
+ void ConsumeEvents();
+
+ /**
+ * @brief Initialize EGL display
+ *
+ * @param egl implementation to use for the creation
+ */
+ bool InitializeEgl(EglInterface& egl);
+
+public:
+
+ /**
+ * @brief This constructor is used by DisplayConnection New() methods.
+ *
+ * @param [in] handle A pointer to a newly allocated DisplayConnection resource
+ */
+ explicit DALI_INTERNAL DisplayConnection(Internal::Adaptor::DisplayConnection* impl);
+
+private:
+
+ std::unique_ptr<Internal::Adaptor::DisplayConnection> mImpl;
+};
+
+}
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_H
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_UTILs_H
+#define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_UTILs_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <memory>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+namespace Utils
+{
+
+template<typename T, typename... Args>
+std::unique_ptr<T> MakeUnique(Args&&... args)
+{
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+} // namespace Utils
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_UTILs_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/ecore-indicator-impl.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Evas.h>
+#ifdef WAYLAND
+#include <Ecore_Wayland.h>
+#else
+#include <Ecore_X.h>
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <iomanip>
+#include <fstream>
+
+#include <dali/public-api/images/native-image.h>
+#include <dali/public-api/events/touch-event.h>
+#include <dali/public-api/events/touch-point.h>
+#include <dali/public-api/common/stage.h>
+#include <dali/public-api/images/buffer-image.h>
+#include <dali/public-api/images/pixel.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+using Dali::Vector4;
+
+#if defined(DEBUG_ENABLED)
+#define STATE_DEBUG_STRING(state) (state==DISCONNECTED?"DISCONNECTED":state==CONNECTED?"CONNECTED":"UNKNOWN")
+#endif
+
+namespace
+{
+
+const float SLIDING_ANIMATION_DURATION( 0.2f ); // 200 milli seconds
+const float AUTO_INDICATOR_STAY_DURATION(3.0f); // 3 seconds
+const float SHOWING_DISTANCE_HEIGHT_RATE(0.34f); // 20 pixels
+
+enum
+{
+ KEEP_SHOWING = -1,
+ HIDE_NOW = 0
+};
+
+const int NUM_GRADIENT_INTERVALS(5); // Number of gradient intervals
+const float GRADIENT_ALPHA[NUM_GRADIENT_INTERVALS+1] = { 0.6f, 0.38f, 0.20f, 0.08f, 0.0f, 0.0f };
+
+#define MAKE_SHADER(A)#A
+
+const char* BACKGROUND_VERTEX_SHADER = MAKE_SHADER(
+ attribute mediump vec2 aPosition;
+ attribute mediump float aAlpha;
+ varying mediump float vAlpha;
+ uniform mediump mat4 uMvpMatrix;
+ uniform mediump vec3 uSize;
+
+ void main()
+ {
+ mediump vec4 vertexPosition = vec4( aPosition * uSize.xy, 0.0, 1.0 );
+ vertexPosition = uMvpMatrix * vertexPosition;
+
+ vAlpha = aAlpha;
+ gl_Position = vertexPosition;
+ }
+);
+
+const char* BACKGROUND_FRAGMENT_SHADER = MAKE_SHADER(
+ uniform lowp vec4 uColor;
+ varying mediump float vAlpha;
+
+ void main()
+ {
+ gl_FragColor = uColor;
+ gl_FragColor.a *= vAlpha;
+ }
+);
+
+const char* FOREGROUND_VERTEX_SHADER = DALI_COMPOSE_SHADER(
+ attribute mediump vec2 aPosition;\n
+ varying mediump vec2 vTexCoord;\n
+ uniform mediump mat4 uMvpMatrix;\n
+ uniform mediump vec3 uSize;\n
+ uniform mediump vec4 sTextureRect;\n
+ \n
+ void main()\n
+ {\n
+ gl_Position = uMvpMatrix * vec4(aPosition * uSize.xy, 0.0, 1.0);\n
+ vTexCoord = aPosition + vec2(0.5);\n
+ }\n
+);
+
+const char* FOREGROUND_FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
+ varying mediump vec2 vTexCoord;\n
+ uniform sampler2D sTexture;\n
+ \n
+ void main()\n
+ {\n
+ gl_FragColor = texture2D( sTexture, vTexCoord );\n // the foreground does not apply actor color
+ }\n
+);
+
+Dali::Geometry CreateQuadGeometry()
+{
+ Dali::Property::Map quadVertexFormat;
+ quadVertexFormat["aPosition"] = Dali::Property::VECTOR2;
+ Dali::PropertyBuffer vertexData = Dali::PropertyBuffer::New( quadVertexFormat );
+
+ const float halfQuadSize = .5f;
+ struct QuadVertex { Dali::Vector2 position; };
+ QuadVertex quadVertexData[4] = {
+ { Dali::Vector2(-halfQuadSize, -halfQuadSize) },
+ { Dali::Vector2(-halfQuadSize, halfQuadSize) },
+ { Dali::Vector2( halfQuadSize, -halfQuadSize) },
+ { Dali::Vector2( halfQuadSize, halfQuadSize) } };
+ vertexData.SetData(quadVertexData, 4);
+
+ Dali::Geometry quad = Dali::Geometry::New();
+ quad.AddVertexBuffer( vertexData );
+ quad.SetType( Dali::Geometry::TRIANGLE_STRIP );
+ return quad;
+}
+
+const float OPAQUE_THRESHOLD(0.99f);
+const float TRANSPARENT_THRESHOLD(0.05f);
+
+// indicator service name
+const char* INDICATOR_SERVICE_NAME("elm_indicator");
+
+// Copied from ecore_evas_extn_engine.h
+
+#define NBUF 2
+
+enum // opcodes
+{
+ OP_RESIZE,
+ OP_SHOW,
+ OP_HIDE,
+ OP_FOCUS,
+ OP_UNFOCUS,
+ OP_UPDATE,
+ OP_UPDATE_DONE,
+ OP_SHM_REF0,
+ OP_SHM_REF1,
+ OP_SHM_REF2,
+ OP_PROFILE_CHANGE_REQUEST,
+ OP_PROFILE_CHANGE_DONE,
+ OP_EV_MOUSE_IN,
+ OP_EV_MOUSE_OUT,
+ OP_EV_MOUSE_UP,
+ OP_EV_MOUSE_DOWN,
+ OP_EV_MOUSE_MOVE,
+ OP_EV_MOUSE_WHEEL,
+ OP_EV_MULTI_UP,
+ OP_EV_MULTI_DOWN,
+ OP_EV_MULTI_MOVE,
+ OP_EV_KEY_UP,
+ OP_EV_KEY_DOWN,
+ OP_EV_HOLD,
+ OP_MSG_PARENT,
+ OP_MSG,
+ OP_PIXMAP_REF,
+};
+
+// Copied from elm_conform.c
+
+const int MSG_DOMAIN_CONTROL_INDICATOR( 0x10001 );
+const int MSG_ID_INDICATOR_REPEAT_EVENT( 0x10002 );
+const int MSG_ID_INDICATOR_ROTATION( 0x10003 );
+const int MSG_ID_INDICATOR_OPACITY( 0X1004 );
+const int MSG_ID_INDICATOR_TYPE( 0X1005 );
+const int MSG_ID_INDICATOR_START_ANIMATION( 0X10006 );
+
+struct IpcDataUpdate
+{
+ int x, w, y, h;
+};
+
+struct IpcDataResize
+{
+ int w, h;
+};
+
+struct IpcIndicatorDataAnimation
+{
+ unsigned int xwin;
+ double duration;
+};
+
+struct IpcDataEvMouseUp
+{
+ int b;
+ Evas_Button_Flags flags;
+ int mask;
+ unsigned int timestamp;
+ Evas_Event_Flags event_flags;
+
+ IpcDataEvMouseUp(unsigned long timestamp)
+ : b(1),
+ flags(EVAS_BUTTON_NONE),
+ mask(0),
+ timestamp(static_cast<unsigned int>(timestamp)),
+ event_flags(EVAS_EVENT_FLAG_NONE)
+ {
+ }
+};
+
+struct IpcDataEvMouseDown
+{
+ int b;
+ Evas_Button_Flags flags;
+ int mask;
+ unsigned int timestamp;
+ Evas_Event_Flags event_flags;
+
+ IpcDataEvMouseDown(unsigned long timestamp)
+ : b(1),
+ flags(EVAS_BUTTON_NONE),
+ mask(0),
+ timestamp(static_cast<unsigned int>(timestamp)),
+ event_flags(EVAS_EVENT_FLAG_NONE)
+ {
+ }
+};
+
+struct IpcDataEvMouseMove
+{
+ int x, y;
+ Evas_Button_Flags flags;
+ int mask;
+ unsigned int timestamp;
+ Evas_Event_Flags event_flags;
+
+ IpcDataEvMouseMove(const Dali::Vector2& touchPoint, unsigned long timestamp)
+ : x(static_cast<Evas_Coord>(touchPoint.x)),
+ y(static_cast<Evas_Coord>(touchPoint.y)),
+ flags(EVAS_BUTTON_NONE),
+ mask(0),
+ timestamp(static_cast<unsigned int>(timestamp)),
+ event_flags(EVAS_EVENT_FLAG_NONE)
+ {
+ }
+};
+
+struct IpcDataEvMouseOut
+{
+ unsigned int timestamp;
+ int mask;
+ Evas_Event_Flags event_flags;
+
+ IpcDataEvMouseOut(unsigned long timestamp)
+ : timestamp(static_cast<unsigned int>(timestamp)),
+ mask(0),
+ event_flags(EVAS_EVENT_FLAG_NONE)
+ {
+ }
+};
+
+#ifdef ENABLE_INDICATOR_IMAGE_SAVING
+
+void SaveIndicatorImage( Dali::NativeImageSourcePtr nativeImageSource )
+{
+ // Save image data to disk in BMP form.
+ static int gFilenameCounter = 0;
+ static const char bmpHeader[] = {
+ 0x42, 0x4d, 0x0a, 0xcb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x7c, 0x00,
+ 0x00, 0x00,
+ 0xe0, 0x01, 0x00, 0x00, // Width (480)
+ 0x1b, 0x00, 0x00, 0x00, // Height ( 27)
+ 0x01, 0x00, 0x20, 0x00, 0x03, 0x00,
+ 0x00, 0x00, 0x80, 0xca, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x13, 0x0b, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
+ 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x42, 0x47, 0x52, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ };
+
+ // This is a BMP header with width & height hard-coded in.
+ // The data was first determined by dumping the raw data and inspecting in GIMP, before creating this header data.
+ std::vector<unsigned char> buffer;
+ unsigned int w = 0;
+ unsigned int h = 0;
+ Dali::Pixel::Format pixelFormat;
+ if( nativeImageSource->GetPixels( buffer, w, h, pixelFormat ) )
+ {
+ int imageSize = w * h * 4;
+ std::stringstream fileName;
+ // Give each file an incremental filename.
+ fileName << "/opt/usr/media/Images/out-" << std::setfill( '0' ) << std::setw( 5 ) << gFilenameCounter << ".bmp";
+
+ std::ofstream outfile( fileName.str().c_str(), std::ofstream::binary );
+ if( outfile.is_open() )
+ {
+ DALI_LOG_WARNING( "Saving Indicator Image w:%d, h:%d, %s\n", w, h, fileName.str().c_str() );
+
+ outfile.write( bmpHeader, sizeof( bmpHeader ) / sizeof( bmpHeader[0] ) ); // Size of the BMP header.
+ outfile.write( (const char*)buffer.data(), imageSize );
+ outfile.close();
+ gFilenameCounter++;
+ }
+ else
+ {
+ DALI_LOG_ERROR( "COULD NOT OPEN FOR SAVING: %s\n", fileName.str().c_str() );
+ }
+ }
+}
+
+#endif
+
+} // anonymous namespace
+
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gIndicatorLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_INDICATOR");
+#endif
+
+// Impl to hide EFL implementation.
+
+struct Indicator::Impl
+{
+ enum // operation mode
+ {
+ INDICATOR_HIDE,
+ INDICATOR_STAY_WITH_DURATION
+ };
+
+ /**
+ * Constructor
+ */
+ Impl(Indicator* indicator)
+ : mIndicator(indicator),
+ mEcoreEventHandler(NULL)
+ {
+#if defined(DALI_PROFILE_MOBILE)
+#if defined(WAYLAND)
+ mEcoreEventHandler = ecore_event_handler_add(ECORE_WL_EVENT_INDICATOR_FLICK, EcoreEventIndicator, this);
+#else
+ mEcoreEventHandler = ecore_event_handler_add(ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, this);
+#endif
+#endif // WAYLAND && DALI_PROFILE_MOBILE
+ }
+
+ /**
+ * Destructor
+ */
+ ~Impl()
+ {
+ if ( mEcoreEventHandler )
+ {
+ ecore_event_handler_del(mEcoreEventHandler);
+ }
+ }
+
+ static void SetIndicatorVisibility( void* data, int operation )
+ {
+ Indicator::Impl* indicatorImpl((Indicator::Impl*)data);
+
+ if ( indicatorImpl == NULL || indicatorImpl->mIndicator == NULL)
+ {
+ return;
+ }
+ if ( operation == INDICATOR_STAY_WITH_DURATION )
+ {
+ // if indicator is not showing, INDICATOR_FLICK_DONE is given
+ if( indicatorImpl->mIndicator->mVisible == Dali::Window::AUTO &&
+ !indicatorImpl->mIndicator->mIsShowing )
+ {
+ indicatorImpl->mIndicator->ShowIndicator( AUTO_INDICATOR_STAY_DURATION );
+ }
+ }
+ else if( operation == INDICATOR_HIDE )
+ {
+ if( indicatorImpl->mIndicator->mVisible == Dali::Window::AUTO &&
+ indicatorImpl->mIndicator->mIsShowing )
+ {
+ indicatorImpl->mIndicator->ShowIndicator( HIDE_NOW );
+ }
+ }
+ }
+#if defined(DALI_PROFILE_MOBILE)
+#if defined(WAYLAND)
+ /**
+ * Called when the Ecore indicator event is received.
+ */
+ static Eina_Bool EcoreEventIndicator( void* data, int type, void* event )
+ {
+ SetIndicatorVisibility( data, INDICATOR_STAY_WITH_DURATION );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+#else
+ /**
+ * Called when the client messages (i.e. quick panel state) are received.
+ */
+ static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
+ {
+ Ecore_X_Event_Client_Message* clientMessageEvent((Ecore_X_Event_Client_Message*)event);
+
+ if ( clientMessageEvent != NULL )
+ {
+ if (clientMessageEvent->message_type == ECORE_X_ATOM_E_INDICATOR_FLICK_DONE)
+ {
+ SetIndicatorVisibility( data, INDICATOR_STAY_WITH_DURATION );
+ }
+ else if ( clientMessageEvent->message_type == ECORE_X_ATOM_E_MOVE_QUICKPANEL_STATE )
+ {
+ SetIndicatorVisibility( data, INDICATOR_HIDE );
+ }
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+#endif
+#endif // WAYLAND && DALI_PROFILE_MOBILE
+
+ // Data
+ Indicator* mIndicator;
+ Ecore_Event_Handler* mEcoreEventHandler;
+};
+
+Indicator::LockFile::LockFile(const std::string filename)
+: mFilename(filename),
+ mErrorThrown(false)
+{
+ mFileDescriptor = open(filename.c_str(), O_RDWR);
+ if( mFileDescriptor == -1 )
+ {
+ mFileDescriptor = 0;
+ mErrorThrown = true;
+ DALI_LOG_ERROR( "### Cannot open %s for indicator lock ###\n", mFilename.c_str() );
+ }
+}
+
+Indicator::LockFile::~LockFile()
+{
+ // Closing file descriptor also unlocks file.
+ if( mFileDescriptor > 0 )
+ {
+ close( mFileDescriptor );
+ }
+}
+
+bool Indicator::LockFile::Lock()
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ bool locked = false;
+ if( mFileDescriptor > 0 )
+ {
+ struct flock filelock;
+
+ filelock.l_type = F_RDLCK;
+ filelock.l_whence = SEEK_SET;
+ filelock.l_start = 0;
+ filelock.l_len = 0;
+ if( fcntl( mFileDescriptor, F_SETLKW, &filelock ) == -1 )
+ {
+ mErrorThrown = true;
+ DALI_LOG_ERROR( "### Failed to lock with fd : %s ###\n", mFilename.c_str() );
+ }
+ else
+ {
+ locked = true;
+ }
+ }
+ else
+ {
+ mErrorThrown = true;
+ DALI_LOG_ERROR( "### Invalid fd ###\n" );
+ }
+
+ return locked;
+}
+
+void Indicator::LockFile::Unlock()
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ if( mFileDescriptor > 0 )
+ {
+ struct flock filelock;
+
+ filelock.l_type = F_UNLCK;
+ filelock.l_whence = SEEK_SET;
+ filelock.l_start = 0;
+ filelock.l_len = 0;
+ if (fcntl(mFileDescriptor, F_SETLKW, &filelock) == -1)
+ {
+ mErrorThrown = true;
+ DALI_LOG_ERROR( "### Failed to lock with fd : %s ###\n", mFilename.c_str() );
+ }
+ }
+}
+
+bool Indicator::LockFile::RetrieveAndClearErrorStatus()
+{
+ bool error = mErrorThrown;
+ mErrorThrown = false;
+ return error;
+}
+
+Indicator::ScopedLock::ScopedLock(LockFile* lockFile)
+: mLockFile(lockFile),
+ mLocked(false)
+{
+ if(mLockFile)
+ {
+ mLocked = mLockFile->Lock();
+ }
+}
+
+Indicator::ScopedLock::~ScopedLock()
+{
+ if( mLockFile )
+ {
+ mLockFile->Unlock();
+ }
+}
+
+bool Indicator::ScopedLock::IsLocked()
+{
+ return mLocked;
+}
+
+Indicator::Indicator( Adaptor* adaptor, Dali::Window::WindowOrientation orientation, IndicatorInterface::Observer* observer )
+: mPixmap( 0 ),
+ mGestureDeltaY( 0.0f ),
+ mGestureDetected( false ),
+ mConnection( this ),
+ mOpacityMode( Dali::Window::OPAQUE ),
+ mState( DISCONNECTED ),
+ mAdaptor(adaptor),
+ mServerConnection( NULL ),
+ mObserver( observer ),
+ mOrientation( orientation ),
+ mImageWidth( 0 ),
+ mImageHeight( 0 ),
+ mVisible( Dali::Window::INVISIBLE ),
+ mIsShowing( true ),
+ mIsAnimationPlaying( false ),
+ mCurrentSharedFile( 0 ),
+ mSharedBufferType( BUFFER_TYPE_SHM ),
+ mImpl( NULL ),
+ mBackgroundVisible( false ),
+ mTopMargin( 0 )
+{
+ mIndicatorContentActor = Dali::Actor::New();
+ mIndicatorContentActor.SetParentOrigin( ParentOrigin::TOP_CENTER );
+ mIndicatorContentActor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+
+ // Indicator image handles the touch event including "leave"
+ mIndicatorContentActor.SetLeaveRequired( true );
+ mIndicatorContentActor.TouchSignal().Connect( this, &Indicator::OnTouch );
+ mIndicatorContentActor.SetColor( Color::BLACK );
+
+ mIndicatorActor = Dali::Actor::New();
+ mIndicatorActor.Add( mIndicatorContentActor );
+
+ // Event handler to find out flick down gesture
+ mEventActor = Dali::Actor::New();
+ mEventActor.SetParentOrigin( ParentOrigin::TOP_CENTER );
+ mEventActor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ mIndicatorActor.Add( mEventActor );
+
+ // Attach pan gesture to find flick down during hiding.
+ // It can prevent the problem that scrollview gets pan gesture even indicator area is touched,
+ // since it consumes the pan gesture in advance.
+ mPanDetector = Dali::PanGestureDetector::New();
+ mPanDetector.DetectedSignal().Connect( this, &Indicator::OnPan );
+ mPanDetector.Attach( mEventActor );
+
+ Open( orientation );
+
+ // register indicator to accessibility adaptor
+ Dali::AccessibilityAdaptor accessibilityAdaptor = AccessibilityAdaptor::Get();
+ if(accessibilityAdaptor)
+ {
+ AccessibilityAdaptor::GetImplementation( accessibilityAdaptor ).SetIndicator( this );
+ }
+ // hide the indicator by default
+ mIndicatorActor.SetVisible( false );
+
+ // create impl to handle ecore event
+ mImpl = new Impl(this);
+}
+
+Indicator::~Indicator()
+{
+ if(mImpl)
+ {
+ delete mImpl;
+ mImpl = NULL;
+ }
+
+ if(mEventActor)
+ {
+ mEventActor.TouchSignal().Disconnect( this, &Indicator::OnTouch );
+ }
+ Disconnect();
+}
+
+void Indicator::SetAdaptor(Adaptor* adaptor)
+{
+ mAdaptor = adaptor;
+ mIndicatorBuffer->SetAdaptor( adaptor );
+}
+
+Dali::Actor Indicator::GetActor()
+{
+ return mIndicatorActor;
+}
+
+void Indicator::Open( Dali::Window::WindowOrientation orientation )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // Calls from Window should be set up to ensure we are in a
+ // disconnected state before opening a second time.
+ DALI_ASSERT_DEBUG( mState == DISCONNECTED );
+
+ mOrientation = orientation;
+
+ Connect();
+
+ // Change background visibility depending on orientation
+ if( mOrientation == Dali::Window::LANDSCAPE || mOrientation == Dali::Window::LANDSCAPE_INVERSE )
+ {
+ if( mBackgroundRenderer )
+ {
+ mIndicatorContentActor.RemoveRenderer( mBackgroundRenderer );
+ mBackgroundVisible = false;
+ }
+ }
+ else
+ {
+ SetOpacityMode( mOpacityMode );
+ }
+}
+
+void Indicator::Close()
+{
+ DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "State: %s", STATE_DEBUG_STRING(mState) );
+
+ if( mState == CONNECTED )
+ {
+ Disconnect();
+ if( mObserver != NULL )
+ {
+ mObserver->IndicatorClosed( this );
+ }
+ }
+
+ Dali::Texture emptyTexture;
+ SetForegroundImage( emptyTexture );
+}
+
+void Indicator::SetOpacityMode( Dali::Window::IndicatorBgOpacity mode )
+{
+ mOpacityMode = mode;
+
+ Dali::Geometry geometry = CreateBackgroundGeometry();
+ if( geometry )
+ {
+ if( mBackgroundRenderer )
+ {
+ if( mBackgroundRenderer.GetGeometry() != geometry )
+ {
+ mBackgroundRenderer.SetGeometry( geometry );
+ }
+ }
+ else
+ {
+ if( !mBackgroundShader )
+ {
+ mBackgroundShader = Dali::Shader::New( BACKGROUND_VERTEX_SHADER, BACKGROUND_FRAGMENT_SHADER, Dali::Shader::Hint::OUTPUT_IS_TRANSPARENT );
+ }
+
+ mBackgroundRenderer = Dali::Renderer::New( geometry, mBackgroundShader );
+ }
+
+ if( !mBackgroundVisible )
+ {
+ mIndicatorContentActor.AddRenderer( mBackgroundRenderer );
+ mBackgroundVisible = true;
+ }
+ }
+ else if( mBackgroundRenderer )
+ {
+ mIndicatorContentActor.RemoveRenderer( mBackgroundRenderer );
+ mBackgroundVisible = false;
+ }
+ UpdateTopMargin();
+}
+
+void Indicator::SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate )
+{
+ if ( visibleMode != mVisible || forceUpdate )
+ {
+ // If we were previously hidden, then we should update the image data before we display the indicator
+ if ( mVisible == Dali::Window::INVISIBLE )
+ {
+ UpdateImageData( mCurrentSharedFile );
+ }
+
+ if ( visibleMode == Dali::Window::INVISIBLE )
+ {
+ if (mServerConnection)
+ {
+ mServerConnection->SendEvent( OP_HIDE, NULL, 0 );
+ }
+ }
+ else
+ {
+ mIndicatorActor.SetVisible( true );
+
+ if( mServerConnection )
+ {
+ mServerConnection->SendEvent( OP_SHOW, NULL, 0 );
+ }
+ }
+
+ mVisible = visibleMode;
+ UpdateTopMargin();
+
+ if( mForegroundRenderer && mForegroundRenderer.GetTextures().GetTexture( 0u ) )
+ {
+ if( CheckVisibleState() && mVisible == Dali::Window::AUTO )
+ {
+ // hide indicator
+ ShowIndicator( AUTO_INDICATOR_STAY_DURATION /* stay n sec */ );
+ }
+ else if( CheckVisibleState() && mVisible == Dali::Window::VISIBLE )
+ {
+ // show indicator
+ ShowIndicator( KEEP_SHOWING );
+ }
+ else
+ {
+ // hide indicator
+ ShowIndicator( HIDE_NOW );
+ }
+ }
+ else
+ {
+ mIsShowing = false;
+ }
+ }
+}
+
+bool Indicator::IsConnected()
+{
+ return ( mState == CONNECTED );
+}
+
+bool Indicator::SendMessage( int messageDomain, int messageId, const void *data, int size )
+{
+ if(IsConnected())
+ {
+ return mServerConnection->SendEvent( OP_MSG, messageDomain, messageId, data, size );
+ }
+ else
+ {
+ return false;
+ }
+}
+
+bool Indicator::OnTouch(Dali::Actor indicator, const Dali::TouchData& touchData)
+{
+ if( mServerConnection )
+ {
+ // Send touch event to indicator server when indicator is showing
+ if( CheckVisibleState() || mIsShowing )
+ {
+ switch( touchData.GetState(0) )
+ {
+ case Dali::PointState::DOWN:
+ {
+ IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
+ IpcDataEvMouseDown ipcDown( touchData.GetTime() );
+ mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
+ mServerConnection->SendEvent( OP_EV_MOUSE_DOWN, &ipcDown, sizeof(ipcDown) );
+
+ if( mVisible == Dali::Window::AUTO )
+ {
+ // Stop hiding indicator
+ ShowIndicator( KEEP_SHOWING );
+ }
+ }
+ break;
+
+ case Dali::PointState::MOTION:
+ {
+ IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
+ mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
+ }
+ break;
+
+ case Dali::PointState::UP:
+ case Dali::PointState::INTERRUPTED:
+ {
+ IpcDataEvMouseUp ipcUp( touchData.GetTime() );
+ mServerConnection->SendEvent( OP_EV_MOUSE_UP, &ipcUp, sizeof(ipcUp) );
+
+ if( mVisible == Dali::Window::AUTO )
+ {
+ // Hide indicator
+ ShowIndicator( 0.5f /* hide after 0.5 sec */ );
+ }
+ }
+ break;
+
+ case Dali::TouchPoint::Leave:
+ {
+ IpcDataEvMouseMove ipcMove( touchData.GetLocalPosition(0), touchData.GetTime() );
+ mServerConnection->SendEvent( OP_EV_MOUSE_MOVE, &ipcMove, sizeof(ipcMove) );
+ IpcDataEvMouseUp ipcOut( touchData.GetTime() );
+ mServerConnection->SendEvent( OP_EV_MOUSE_OUT, &ipcOut, sizeof(ipcOut) );
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool Indicator::Connect()
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ DALI_ASSERT_DEBUG( mState == DISCONNECTED );
+
+ bool connected = false;
+
+ mServerConnection = new ServerConnection( INDICATOR_SERVICE_NAME, 0, false, this );
+ if( mServerConnection )
+ {
+ connected = mServerConnection->IsConnected();
+ if( ! connected )
+ {
+ delete mServerConnection;
+ mServerConnection = NULL;
+ }
+ }
+
+ if( !connected )
+ {
+ StartReconnectionTimer();
+ }
+ else
+ {
+ mState = CONNECTED;
+ }
+
+ return connected;
+}
+
+void Indicator::StartReconnectionTimer()
+{
+ if( ! mReconnectTimer )
+ {
+ mReconnectTimer = Dali::Timer::New(1000);
+ mConnection.DisconnectAll();
+ mReconnectTimer.TickSignal().Connect( mConnection, &Indicator::OnReconnectTimer );
+ }
+ mReconnectTimer.Start();
+}
+
+bool Indicator::OnReconnectTimer()
+{
+ bool retry = false;
+
+ if( mState == DISCONNECTED )
+ {
+ if( !Connect() )
+ {
+ retry = true;
+ }
+ }
+
+ return retry;
+}
+
+void Indicator::Disconnect()
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ mState = DISCONNECTED;
+
+ delete mServerConnection;
+ mServerConnection = NULL;
+
+ ClearSharedFileInfo();
+}
+
+void Indicator::Resize( int width, int height )
+{
+ if( width < 1 )
+ {
+ width = 1;
+ }
+ if( height < 1 )
+ {
+ height = 1;
+ }
+
+ if( mImageWidth != width || mImageHeight != height )
+ {
+ mImageWidth = width;
+ mImageHeight = height;
+
+ mIndicatorContentActor.SetSize( mImageWidth, mImageHeight );
+ mIndicatorActor.SetSize( mImageWidth, mImageHeight );
+ mEventActor.SetSize(mImageWidth, mImageHeight);
+ UpdateTopMargin();
+ }
+}
+
+void Indicator::SetLockFileInfo( Ecore_Ipc_Event_Server_Data *epcEvent )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // epcEvent->ref == w
+ // epcEvent->ref_to == h
+ // epcEvent->response == buffer num
+ // epcEvent->data = lockfile + nul byte
+
+ if( (epcEvent->ref > 0) && (epcEvent->ref_to > 0) && (epcEvent->data) &&
+ (((unsigned char *)epcEvent->data)[epcEvent->size - 1] == 0) )
+ {
+ int n = epcEvent->response;
+
+ if( n >= 0 && n < SHARED_FILE_NUMBER )
+ {
+ mCurrentSharedFile = n;
+
+ mSharedFileInfo[n].mImageWidth = epcEvent->ref;
+ mSharedFileInfo[n].mImageHeight = epcEvent->ref_to;
+
+ mSharedFileInfo[n].mLockFileName.clear();
+
+ mSharedFileInfo[n].mLockFileName = static_cast< char* >( epcEvent->data );
+
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "SetLockFileInfo: buffer num = %d, w = %d, h = %d, lock = %s\n",
+ n, mSharedFileInfo[n].mImageWidth, mSharedFileInfo[n].mImageHeight, mSharedFileInfo[n].mLockFileName.c_str() );
+ }
+ }
+}
+
+void Indicator::SetSharedImageInfo( Ecore_Ipc_Event_Server_Data *epcEvent )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // epcEvent->ref == shm id
+ // epcEvent->ref_to == shm num
+ // epcEvent->response == buffer num
+ // epcEvent->data = shm ref string + nul byte
+
+ if ( (epcEvent->data) &&
+ (epcEvent->size > 0) &&
+ (((unsigned char *)epcEvent->data)[epcEvent->size - 1] == 0) )
+ {
+ int n = epcEvent->response;
+
+ if( n >= 0 && n < SHARED_FILE_NUMBER )
+ {
+ mCurrentSharedFile = n;
+
+ mSharedFileInfo[n].mSharedFileName.clear();
+
+ mSharedFileInfo[n].mSharedFileName = static_cast< char* >( epcEvent->data );
+
+ mSharedFileInfo[n].mSharedFileID = epcEvent->ref;
+ mSharedFileInfo[n].mSharedFileNumber = epcEvent->ref_to;
+
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "SetSharedImageInfo: buffer num %d, shared file = %s, id = %d, num = %d\n",
+ n, mSharedFileInfo[n].mSharedFileName.c_str(), mSharedFileInfo[n].mSharedFileID, mSharedFileInfo[n].mSharedFileNumber );
+ }
+ }
+}
+
+void Indicator::LoadSharedImage( Ecore_Ipc_Event_Server_Data *epcEvent )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // epcEvent->ref == alpha
+ // epcEvent->ref_to == sys
+ // epcEvent->response == buffer num
+
+ if ( mSharedBufferType != BUFFER_TYPE_SHM )
+ {
+ return ;
+ }
+
+ int n = epcEvent->response;
+
+ if( n >= 0 && n < SHARED_FILE_NUMBER )
+ {
+ mCurrentSharedFile = n;
+
+ delete mSharedFileInfo[n].mSharedFile;
+ mSharedFileInfo[n].mSharedFile = NULL;
+
+ delete mSharedFileInfo[n].mLock;
+ mSharedFileInfo[n].mLock = NULL;
+
+ std::stringstream sharedFileID;
+ std::stringstream sharedFileNumber;
+
+ sharedFileID << mSharedFileInfo[n].mSharedFileID;
+ sharedFileNumber << mSharedFileInfo[n].mSharedFileNumber;
+
+ std::string sharedFilename = "/" + mSharedFileInfo[n].mSharedFileName + "-" + sharedFileID.str() + "." + sharedFileNumber.str();
+
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "LoadSharedImage: file name = %s\n", sharedFilename.c_str() );
+
+ mSharedFileInfo[n].mSharedFile = SharedFile::New( sharedFilename.c_str(), mSharedFileInfo[n].mImageWidth * mSharedFileInfo[n].mImageWidth * 4, true );
+ if( mSharedFileInfo[n].mSharedFile != NULL )
+ {
+ mSharedFileInfo[n].mLock = new Indicator::LockFile( mSharedFileInfo[n].mLockFileName );
+ if( mSharedFileInfo[n].mLock->RetrieveAndClearErrorStatus() )
+ {
+ DALI_LOG_ERROR( "### Indicator error: Cannot open lock file %s ###\n", mSharedFileInfo[n].mLockFileName.c_str() );
+ }
+ else
+ {
+ CreateNewImage( n );
+ UpdateVisibility();
+ }
+ }
+ }
+}
+
+void Indicator::LoadPixmapImage( Ecore_Ipc_Event_Server_Data *epcEvent )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // epcEvent->ref == pixmap id
+ // epcEvent->ref_to == type
+ // epcEvent->response == buffer num
+
+ if( (epcEvent->ref > 0) && (epcEvent->ref_to > 0) )
+ {
+ mSharedBufferType = (BufferType)(epcEvent->ref_to);
+
+ ClearSharedFileInfo();
+
+ mPixmap = static_cast<PixmapId>(epcEvent->ref);
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "mPixmap [%x]", mPixmap);
+
+ CreateNewPixmapImage();
+ UpdateVisibility();
+ }
+}
+
+void Indicator::UpdateTopMargin()
+{
+ int newMargin = (mVisible == Dali::Window::VISIBLE && mOpacityMode == Dali::Window::OPAQUE) ? mImageHeight : 0;
+ if (mTopMargin != newMargin)
+ {
+ mTopMargin = newMargin;
+ mAdaptor->IndicatorSizeChanged( mTopMargin );
+ }
+}
+
+void Indicator::UpdateVisibility()
+{
+ if( CheckVisibleState() )
+ {
+ // set default indicator type (enable the quick panel)
+ OnIndicatorTypeChanged( INDICATOR_TYPE_1 );
+ }
+ else
+ {
+ // set default indicator type (disable the quick panel)
+ OnIndicatorTypeChanged( INDICATOR_TYPE_2 );
+ }
+
+ if( !mIsShowing )
+ {
+ mIndicatorContentActor.SetPosition( 0.0f, -mImageHeight, 0.0f );
+ }
+
+ SetVisible(mVisible, true);
+}
+
+void Indicator::UpdateImageData( int bufferNumber )
+{
+ DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "State: %s mVisible: %s", STATE_DEBUG_STRING(mState), mVisible?"T":"F" );
+
+ if( mState == CONNECTED && mVisible )
+ {
+ if(mPixmap == 0)
+ {
+ // in case of shm indicator (not pixmap), not sure we can skip it when mIsShowing is false
+ CopyToBuffer( bufferNumber );
+ }
+ else
+ {
+ if(mIsShowing)
+ {
+ mAdaptor->RequestUpdateOnce();
+ }
+ }
+ }
+}
+
+bool Indicator::CopyToBuffer( int bufferNumber )
+{
+ bool success = false;
+
+ if( mSharedFileInfo[bufferNumber].mLock )
+ {
+ Indicator::ScopedLock scopedLock(mSharedFileInfo[bufferNumber].mLock);
+ if( mSharedFileInfo[bufferNumber].mLock->RetrieveAndClearErrorStatus() )
+ {
+ // Do nothing here.
+ }
+ else if( scopedLock.IsLocked() )
+ {
+ unsigned char *src = mSharedFileInfo[bufferNumber].mSharedFile->GetAddress();
+ size_t size = static_cast< size_t >( mSharedFileInfo[bufferNumber].mImageWidth ) * mSharedFileInfo[bufferNumber].mImageHeight * 4;
+
+ if( mIndicatorBuffer->UpdatePixels( src, size ) )
+ {
+ mAdaptor->RequestUpdateOnce();
+ success = true;
+ }
+ }
+ }
+
+ return success;
+}
+
+void Indicator::CreateNewPixmapImage()
+{
+ DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "W:%d H:%d", mImageWidth, mImageHeight );
+ Dali::NativeImageSourcePtr nativeImageSource = Dali::NativeImageSource::New( mPixmap );
+
+#ifdef ENABLE_INDICATOR_IMAGE_SAVING
+ SaveIndicatorImage( nativeImageSource );
+#endif
+
+ if( nativeImageSource )
+ {
+ Dali::Texture texture = Dali::Texture::New( *nativeImageSource );
+ SetForegroundImage( texture );
+ mIndicatorContentActor.SetSize( mImageWidth, mImageHeight );
+ mIndicatorActor.SetSize( mImageWidth, mImageHeight );
+ mEventActor.SetSize( mImageWidth, mImageHeight );
+ UpdateTopMargin();
+ }
+ else
+ {
+ DALI_LOG_WARNING("### Cannot create indicator image - disconnecting ###\n");
+ Disconnect();
+ if( mObserver != NULL )
+ {
+ mObserver->IndicatorClosed( this );
+ }
+ // Don't do connection in this callback - strange things happen!
+ StartReconnectionTimer();
+ }
+}
+
+void Indicator::CreateNewImage( int bufferNumber )
+{
+ DALI_LOG_TRACE_METHOD_FMT( gIndicatorLogFilter, "W:%d H:%d", mSharedFileInfo[bufferNumber].mImageWidth, mSharedFileInfo[bufferNumber].mImageHeight );
+ mIndicatorBuffer = new IndicatorBuffer( mAdaptor, mSharedFileInfo[bufferNumber].mImageWidth, mSharedFileInfo[bufferNumber].mImageHeight, Pixel::BGRA8888 );
+ bool success = false;
+
+ if( CopyToBuffer( bufferNumber ) ) // Only create images if we have valid image buffer
+ {
+ Dali::Texture texture = Dali::Texture::New( mIndicatorBuffer->GetNativeImage() );
+ if( texture )
+ {
+ SetForegroundImage( texture );
+ success = true;
+ }
+ }
+
+ if( !success )
+ {
+ DALI_LOG_WARNING("### Cannot create indicator image ###\n");
+ }
+}
+
+Dali::Geometry Indicator::CreateBackgroundGeometry()
+{
+ switch( mOpacityMode )
+ {
+ case Dali::Window::TRANSLUCENT:
+ if( !mTranslucentGeometry )
+ {
+ // Construct 5 interval mesh
+ // 0 +---+ 1
+ // | \ |
+ // 2 +---+ 3
+ // | \ |
+ // 4 +---+ 5
+ // | \ |
+ // 6 +---+ 7
+ // | \ |
+ // 8 +---+ 9
+ // | \ |
+ // 10 +---+ 11
+
+ // Create vertices
+ struct BackgroundVertex
+ {
+ Vector2 mPosition;
+ float mAlpha;
+ };
+
+ unsigned int numVertices = 2 * ( NUM_GRADIENT_INTERVALS + 1 );
+ BackgroundVertex vertices[ numVertices ];
+
+ float d = -0.5f;
+ float delta = 1.0f / NUM_GRADIENT_INTERVALS;
+ BackgroundVertex* currentVertex = vertices;
+ for( int y = 0; y < NUM_GRADIENT_INTERVALS + 1; ++y, d += delta )
+ {
+ currentVertex->mPosition = Vector2( -0.5f, d );
+ currentVertex->mAlpha = GRADIENT_ALPHA[ y ];
+ currentVertex++;
+
+ currentVertex->mPosition = Vector2( 0.5f, d );
+ currentVertex->mAlpha = GRADIENT_ALPHA[ y ];
+ currentVertex++;
+ }
+
+ // Create indices
+ unsigned int numIndices = 2 * 3 * NUM_GRADIENT_INTERVALS;
+ unsigned short indices[ numIndices ];
+
+ unsigned short* currentIndex = indices;
+ for( int y = 0; y < NUM_GRADIENT_INTERVALS; ++y )
+ {
+ *currentIndex++ = (2 * y);
+ *currentIndex++ = (2 * y) + 3;
+ *currentIndex++ = (2 * y) + 1;
+
+ *currentIndex++ = (2 * y);
+ *currentIndex++ = (2 * y) + 2;
+ *currentIndex++ = (2 * y) + 3;
+ }
+
+ Dali::Property::Map vertexFormat;
+ vertexFormat[ "aPosition" ] = Dali::Property::VECTOR2;
+ vertexFormat[ "aAlpha" ] = Dali::Property::FLOAT;
+ Dali::PropertyBuffer vertexPropertyBuffer = Dali::PropertyBuffer::New( vertexFormat );
+ vertexPropertyBuffer.SetData( vertices, numVertices );
+
+ // Create the geometry object
+ mTranslucentGeometry = Dali::Geometry::New();
+ mTranslucentGeometry.AddVertexBuffer( vertexPropertyBuffer );
+ mTranslucentGeometry.SetIndexBuffer( &indices[0], numIndices );
+ }
+
+ return mTranslucentGeometry;
+ case Dali::Window::OPAQUE:
+
+ if( !mSolidGeometry )
+ {
+ // Create vertices
+ struct BackgroundVertex
+ {
+ Vector2 mPosition;
+ float mAlpha;
+ };
+
+ BackgroundVertex vertices[ 4 ] = { { Vector2( -0.5f, -0.5f ), 1.0f }, { Vector2( 0.5f, -0.5f ), 1.0f },
+ { Vector2( -0.5f, 0.5f ), 1.0f }, { Vector2( 0.5f, 0.5f ), 1.0f } };
+
+ // Create indices
+ unsigned short indices[ 6 ] = { 0, 3, 1, 0, 2, 3 };
+
+ Dali::Property::Map vertexFormat;
+ vertexFormat[ "aPosition" ] = Dali::Property::VECTOR2;
+ vertexFormat[ "aAlpha" ] = Dali::Property::FLOAT;
+ Dali::PropertyBuffer vertexPropertyBuffer = Dali::PropertyBuffer::New( vertexFormat );
+ vertexPropertyBuffer.SetData( vertices, 4 );
+
+
+ // Create the geometry object
+ mSolidGeometry = Dali::Geometry::New();
+ mSolidGeometry.AddVertexBuffer( vertexPropertyBuffer );
+ mSolidGeometry.SetIndexBuffer( &indices[0], 6 );
+ }
+
+ return mSolidGeometry;
+ case Dali::Window::TRANSPARENT:
+ break;
+ }
+
+ return Dali::Geometry();
+}
+
+void Indicator::SetForegroundImage( Dali::Texture texture )
+{
+ if( !mForegroundRenderer && texture )
+ {
+ // Create Shader
+ Dali::Shader shader = Dali::Shader::New( FOREGROUND_VERTEX_SHADER, FOREGROUND_FRAGMENT_SHADER );
+
+ // Create renderer from geometry and material
+ Dali::Geometry quad = CreateQuadGeometry();
+ mForegroundRenderer = Dali::Renderer::New( quad, shader );
+ // Make sure the foreground stays in front of the background
+ mForegroundRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, 1.f );
+
+ // Set blend function
+ mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_SRC_RGB, Dali::BlendFactor::ONE );
+ mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_DEST_RGB, Dali::BlendFactor::ONE_MINUS_SRC_ALPHA );
+ mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_SRC_ALPHA, Dali::BlendFactor::ONE );
+ mForegroundRenderer.SetProperty( Dali::Renderer::Property::BLEND_FACTOR_DEST_ALPHA, Dali::BlendFactor::ONE );
+
+ // Create a texture-set and add to renderer
+
+ Dali::TextureSet textureSet = Dali::TextureSet::New();
+ textureSet.SetTexture( 0u, texture );
+ mForegroundRenderer.SetTextures( textureSet );
+
+ mIndicatorContentActor.AddRenderer( mForegroundRenderer );
+ }
+ else if( mForegroundRenderer )
+ {
+ Dali::TextureSet textureSet = mForegroundRenderer.GetTextures();
+ textureSet.SetTexture( 0u, texture );
+ }
+
+ if( mImageWidth == 0 && mImageHeight == 0 && texture)
+ {
+ Resize( texture.GetWidth(), texture.GetHeight() );
+ }
+}
+
+void Indicator::OnIndicatorTypeChanged( Type indicatorType )
+{
+ if( mObserver != NULL )
+ {
+ mObserver->IndicatorTypeChanged( indicatorType );
+ }
+}
+
+void Indicator::DataReceived( void* event )
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+ Ecore_Ipc_Event_Server_Data *epcEvent = static_cast<Ecore_Ipc_Event_Server_Data *>( event );
+
+ switch( epcEvent->minor )
+ {
+ case OP_UPDATE:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_UPDATE\n" );
+ if( mIsShowing )
+ {
+ mAdaptor->RequestUpdateOnce();
+ }
+ break;
+ }
+ case OP_UPDATE_DONE:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_UPDATE_DONE [%d]\n", epcEvent->response );
+ // epcEvent->response == display buffer #
+ UpdateImageData( epcEvent->response );
+ break;
+ }
+ case OP_SHM_REF0:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF0\n" );
+ SetSharedImageInfo( epcEvent );
+ break;
+ }
+ case OP_SHM_REF1:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF1\n" );
+ SetLockFileInfo( epcEvent );
+ break;
+ }
+ case OP_SHM_REF2:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_SHM_REF2\n" );
+ LoadSharedImage( epcEvent );
+ break;
+ }
+ case OP_PIXMAP_REF:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_PIXMAP_REF\n" );
+ LoadPixmapImage( epcEvent );
+ break;
+ }
+ case OP_RESIZE:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_RESIZE\n" );
+
+ if( (epcEvent->data) && (epcEvent->size >= (int)sizeof(IpcDataResize)) )
+ {
+ IpcDataResize *newSize = static_cast<IpcDataResize*>( epcEvent->data );
+ Resize( newSize->w, newSize->h );
+ }
+ break;
+ }
+ case OP_MSG_PARENT:
+ {
+ int msgDomain = epcEvent->ref;
+ int msgId = epcEvent->ref_to;
+
+ void *msgData = NULL;
+ int msgDataSize = 0;
+ msgData = epcEvent->data;
+ msgDataSize = epcEvent->size;
+
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_MSG_PARENT. msgDomain = %d\n", msgDomain );
+
+ if( msgDomain == MSG_DOMAIN_CONTROL_INDICATOR )
+ {
+ switch( msgId )
+ {
+ case MSG_ID_INDICATOR_TYPE:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: OP_MSG_PARENT, INDICATOR_TYPE\n" );
+ Type* indicatorType = static_cast<Type*>( epcEvent->data );
+ OnIndicatorTypeChanged( *indicatorType );
+ break;
+ }
+
+ case MSG_ID_INDICATOR_START_ANIMATION:
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "Indicator client received: MSG_ID_INDICATOR_START_ANIMATION\n" );
+
+ if (msgDataSize != (int)sizeof(IpcIndicatorDataAnimation))
+ {
+ DALI_LOG_ERROR("Message data is incorrect\n");
+ break;
+ }
+
+ IpcIndicatorDataAnimation *animData = static_cast<IpcIndicatorDataAnimation*>(msgData);
+
+ if(!CheckVisibleState())
+ {
+ ShowIndicator( animData->duration /* n sec */ );
+ }
+ break;
+ }
+ }
+ }
+ break;
+ }
+ }
+}
+
+void Indicator::ConnectionClosed()
+{
+ DALI_LOG_TRACE_METHOD( gIndicatorLogFilter );
+
+ // Will get this callback if the server connection failed to start up.
+ delete mServerConnection;
+ mServerConnection = NULL;
+ mState = DISCONNECTED;
+
+ // Attempt to re-connect
+ Connect();
+}
+
+bool Indicator::CheckVisibleState()
+{
+ if( mOrientation == Dali::Window::LANDSCAPE
+ || mOrientation == Dali::Window::LANDSCAPE_INVERSE
+ || (mVisible == Dali::Window::INVISIBLE)
+ || (mVisible == Dali::Window::AUTO && !mIsShowing) )
+ {
+ return false;
+ }
+
+ return true;
+}
+
+void Indicator::ClearSharedFileInfo()
+{
+ for( int i = 0; i < SHARED_FILE_NUMBER; i++ )
+ {
+ delete mSharedFileInfo[i].mLock;
+ mSharedFileInfo[i].mLock = NULL;
+
+ delete mSharedFileInfo[i].mSharedFile;
+ mSharedFileInfo[i].mSharedFile = NULL;
+
+ mSharedFileInfo[i].mLockFileName.clear();
+ mSharedFileInfo[i].mSharedFileName.clear();
+ }
+}
+
+/**
+ * duration can be this
+ *
+ * enum
+ * {
+ * KEEP_SHOWING = -1,
+ * HIDE_NOW = 0
+ * };
+ */
+void Indicator::ShowIndicator(float duration)
+{
+ if( !mIndicatorAnimation )
+ {
+ mIndicatorAnimation = Dali::Animation::New(SLIDING_ANIMATION_DURATION);
+ mIndicatorAnimation.FinishedSignal().Connect(this, &Indicator::OnAnimationFinished);
+ }
+
+ if(mIsShowing && !EqualsZero(duration))
+ {
+ // If need to show during showing, do nothing.
+ // In 2nd phase (below) will update timer
+ }
+ else if(!mIsShowing && mIsAnimationPlaying && EqualsZero(duration))
+ {
+ // If need to hide during hiding or hidden already, do nothing
+ }
+ else
+ {
+ mIndicatorAnimation.Clear();
+
+ if( EqualsZero(duration) )
+ {
+ mIndicatorAnimation.AnimateTo( Property( mIndicatorContentActor, Dali::Actor::Property::POSITION ), Vector3(0, -mImageHeight, 0), Dali::AlphaFunction::EASE_OUT );
+
+ mIsShowing = false;
+
+ OnIndicatorTypeChanged( INDICATOR_TYPE_2 ); // un-toucable
+ }
+ else
+ {
+ mIndicatorAnimation.AnimateTo( Property( mIndicatorContentActor, Dali::Actor::Property::POSITION ), Vector3(0, 0, 0), Dali::AlphaFunction::EASE_OUT );
+
+ mIsShowing = true;
+
+ OnIndicatorTypeChanged( INDICATOR_TYPE_1 ); // touchable
+ }
+
+ mIndicatorAnimation.Play();
+ mIsAnimationPlaying = true;
+ }
+
+ if(duration > 0)
+ {
+ if(!mShowTimer)
+ {
+ mShowTimer = Dali::Timer::New(1000 * duration);
+ mShowTimer.TickSignal().Connect(this, &Indicator::OnShowTimer);
+ }
+ mShowTimer.SetInterval(1000* duration);
+ mShowTimer.Start();
+
+ if( mVisible == Dali::Window::AUTO )
+ {
+ // check the stage touch
+ Dali::Stage::GetCurrent().TouchSignal().Connect( this, &Indicator::OnStageTouch );
+ }
+ }
+ else
+ {
+ if(mShowTimer && mShowTimer.IsRunning())
+ {
+ mShowTimer.Stop();
+ }
+
+ if( mVisible == Dali::Window::AUTO )
+ {
+ // check the stage touch
+ Dali::Stage::GetCurrent().TouchSignal().Disconnect( this, &Indicator::OnStageTouch );
+ }
+ }
+}
+
+bool Indicator::OnShowTimer()
+{
+ // after time up, hide indicator
+ ShowIndicator( HIDE_NOW );
+
+ return false;
+}
+
+void Indicator::OnAnimationFinished(Dali::Animation& animation)
+{
+ mIsAnimationPlaying = false;
+ // once animation is finished and indicator is hidden, take it off stage
+ if( mObserver != NULL )
+ {
+ mObserver->IndicatorVisibilityChanged( mIsShowing ); // is showing?
+ }
+}
+
+void Indicator::OnPan( Dali::Actor actor, const Dali::PanGesture& gesture )
+{
+ // Nothing to do, but we still want to consume pan
+}
+
+void Indicator::OnStageTouch(const Dali::TouchData& touchData)
+{
+ // when stage is touched while indicator is showing temporary, hide it
+ if( mIsShowing && ( CheckVisibleState() == false || mVisible == Dali::Window::AUTO ) )
+ {
+ switch( touchData.GetState(0) )
+ {
+ case Dali::PointState::DOWN:
+ {
+ // if touch point is inside the indicator, indicator is not hidden
+ if( mImageHeight < int( touchData.GetScreenPosition(0).y ) )
+ {
+ ShowIndicator( HIDE_NOW );
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+ }
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_INTERNAL_ECORE_INDICATOR_H__
+#define __DALI_INTERNAL_ECORE_INDICATOR_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/animation/animation.h>
+#include <dali/public-api/events/pan-gesture.h>
+#include <dali/public-api/events/pan-gesture-detector.h>
+#include <dali/public-api/events/touch-data.h>
+#include <dali/public-api/rendering/renderer.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/indicator-interface.h>
+#include <dali/internal/window-system/common/indicator-buffer.h>
+#include <dali/internal/window-system/common/ecore-server-connection.h>
+#include <dali/internal/system/common/shared-file.h>
+#include <dali/public-api/adaptor-framework/timer.h>
+#include <dali/public-api/adaptor-framework/window.h>
+
+namespace Dali
+{
+namespace Integration
+{
+class Core;
+}
+
+namespace Internal
+{
+namespace Adaptor
+{
+class Adaptor;
+
+typedef unsigned int PixmapId;
+
+/**
+ * The Indicator class connects to the indicator server, and gets and draws the indicator
+ * for the given orientation.
+ */
+class Indicator : public ConnectionTracker, public ServerConnection::Observer, public IndicatorInterface
+{
+public:
+
+ enum State
+ {
+ DISCONNECTED,
+ CONNECTED
+ };
+
+ /**
+ * copied from ecore_evas_extn_engine.h
+ */
+ enum BufferType
+ {
+ BUFFER_TYPE_SHM = 0, ///< shared memory-based buffer backend
+ BUFFER_TYPE_DRI2_PIXMAP, ///< dri2 pixmap-based buffer backend
+ BUFFER_TYPE_EVASGL_PIXMAP, ///< pixmap backend for Evas GL only (DEPRECATED)
+ BUFFER_TYPE_GL_PIXMAP, ///< double buffered GL pixmap backend
+ };
+
+protected:
+ /**
+ * Class to encapsulate lock file
+ */
+ class LockFile
+ {
+ public:
+ /**
+ * Constructor. open lock file
+ */
+ LockFile(const std::string filename);
+
+ /**
+ * Close lock file
+ */
+ ~LockFile();
+
+ /**
+ * Grab an exclusive lock on this file
+ * @return true if the lock succeeded, false if it failed
+ */
+ bool Lock();
+
+ /**
+ * Remove the lock
+ */
+ void Unlock();
+
+ /**
+ * Test if there is an error with the lock file, and clears
+ * the error flag;
+ * @return true if an error was thrown
+ */
+ bool RetrieveAndClearErrorStatus();
+
+ private:
+ std::string mFilename;
+ int mFileDescriptor;
+ bool mErrorThrown;
+ };
+
+ /**
+ * Class to ensure lock/unlock through object destruction
+ */
+ class ScopedLock
+ {
+ public:
+ /**
+ * Constructor - creates a lock on the lockfile
+ * @param[in] lockFile The lockfile to use
+ */
+ ScopedLock( LockFile* lockFile );
+
+ /**
+ * Destructor - removes the lock (if any) on the lockfile
+ */
+ ~ScopedLock();
+
+ /**
+ * Method to test if the locking succeeded
+ * @return TRUE if locked
+ */
+ bool IsLocked();
+
+ private:
+ LockFile* mLockFile; ///< The lock file to use
+ bool mLocked; ///< Whether the lock succeeded
+ };
+
+
+public: // Dali::Internal::Adaptor::IndicicatorInterface
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::IndicatorInterface
+ */
+ Indicator( Adaptor* adaptor,
+ Dali::Window::WindowOrientation orientation,
+ IndicatorInterface::Observer* observer );
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::~IndicatorInterface
+ */
+ virtual ~Indicator();
+
+
+ virtual void SetAdaptor(Adaptor* adaptor);
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::GetActor
+ */
+ virtual Dali::Actor GetActor();
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::Open
+ */
+ virtual void Open( Dali::Window::WindowOrientation orientation );
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::Close
+ */
+ virtual void Close();
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::SetOpacityMode
+ */
+ virtual void SetOpacityMode( Dali::Window::IndicatorBgOpacity mode );
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::SetVisible
+ */
+ virtual void SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate = false );
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::IsConnected
+ */
+ virtual bool IsConnected();
+
+ /**
+ * @copydoc Dali::Internal::IndicatorInterface::SendMessage
+ */
+ virtual bool SendMessage( int messageDomain, int messageId, const void *data, int size );
+
+private:
+ /**
+ * Initialize the indicator actors
+ */
+ void Initialize();
+
+ /**
+ * Constructs the renderers used for the background
+ */
+ Dali::Geometry CreateBackgroundGeometry();
+
+ /**
+ * Set the texture to be rendered as indicator foreground
+ * @param[in] texture The foreground texture.
+ */
+ void SetForegroundImage( Dali::Texture texture );
+
+ /**
+ * Touch event callback.
+ * It should pass the valid touch event to indicator server
+ *
+ * @param[in] indicator The indicator actor that was touched
+ * @param[in] touchEvent The touch data
+ */
+ bool OnTouch(Dali::Actor indicator, const Dali::TouchData& touchData);
+
+ /**
+ * Pan gesture callback.
+ * It finds flick down gesture to show hidden indicator image
+ *
+ * @param[in] actor The actor for gesture
+ * @param[in] gesture The gesture event
+ */
+ void OnPan( Dali::Actor actor, const Dali::PanGesture& gesture );
+
+ /**
+ * Touch event callback on stage.
+ * If stage is touched, hide showing indicator image
+ *
+ * @param[in] touchEvent The touch data
+ */
+ void OnStageTouch(const Dali::TouchData& touchData);
+
+ /**
+ * Connect to the indicator service
+ */
+ bool Connect();
+
+ /**
+ * Start the reconnection timer. This will run every second until we reconnect to
+ * the indicator service.
+ */
+ void StartReconnectionTimer();
+
+ /**
+ * If connection failed, attempt to re-connect every second
+ */
+ bool OnReconnectTimer();
+
+ /**
+ * Disconnect from the indicator service
+ */
+ void Disconnect();
+
+ /**
+ * Handle Resize event
+ * @param[in] width The new width
+ * @param[in] height The new height
+ */
+ void Resize( int width, int height );
+
+ /**
+ * Set the lock file info.
+ * @param[in] epcEvent Current ecore event.
+ */
+ void SetLockFileInfo( Ecore_Ipc_Event_Server_Data *epcEvent );
+
+ /**
+ * Set the shared indicator image info
+ * @param[in] epcEvent The event containing the image data
+ */
+ void SetSharedImageInfo( Ecore_Ipc_Event_Server_Data *epcEvent );
+
+ /**
+ * Load the shared indicator image
+ * @param[in] epcEvent The event containing the image data
+ */
+ void LoadSharedImage( Ecore_Ipc_Event_Server_Data *epcEvent );
+
+ /**
+ * Load the pixmap indicator image
+ * @param[in] epcEvent The event containing the image data
+ */
+ void LoadPixmapImage( Ecore_Ipc_Event_Server_Data *epcEvent );
+
+ /**
+ * Update top margin of the stage as much as indicator height
+ */
+ void UpdateTopMargin();
+
+ /**
+ * Update the visibility and position of the actors
+ */
+ void UpdateVisibility();
+
+ /**
+ * Inform dali that the indicator data has been updated.
+ * @param[in] bufferNumber The shared file number
+ */
+ void UpdateImageData( int bufferNumber );
+
+ /**
+ * Lock the temporary file, Copy the shared image into IndicatorBuffer
+ * and then unlock the temporary file.
+ * Caller should ensure we are not writing image to gl texture.
+ * @param[in] bufferNumber The shared file number
+ */
+ bool CopyToBuffer( int bufferNumber );
+
+ /**
+ * Create a new image for the indicator, and set up signal handling for it.
+ * @param[in] bufferNumber The shared file number
+ */
+ void CreateNewImage( int bufferNumber );
+
+ /**
+ * Create a new pixmap image for the indicator, and set up signal handling for it.
+ */
+ void CreateNewPixmapImage();
+
+ /**
+ * Indicator type has changed.
+ * Inform observer
+ * @param[in] type The new indicator type
+ */
+ void OnIndicatorTypeChanged( Type type );
+
+ /**
+ * Check whether the indicator could be visible or invisible
+ * @return true if indicator should be shown
+ */
+ bool CheckVisibleState();
+
+ /**
+ * Show/Hide indicator actor with effect
+ * @param[in] duration how long need to show the indicator,
+ * if it equal to 0, hide the indicator
+ * if it less than 0, show always
+ */
+ void ShowIndicator( float duration );
+
+ /**
+ * Showing timer callback
+ */
+ bool OnShowTimer();
+
+ /**
+ * Showing animation finished callback
+ * @param[in] animation
+ */
+ void OnAnimationFinished( Dali::Animation& animation );
+
+private: // Implementation of ServerConnection::Observer
+ /**
+ * @copydoc Dali::Internal::Adaptor::ServerConnection::Observer::DataReceived()
+ */
+ virtual void DataReceived( void* event );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::ServerConnection::Observer::DataReceived()
+ */
+ virtual void ConnectionClosed();
+
+private:
+
+ /**
+ * Clear shared file info
+ */
+ void ClearSharedFileInfo();
+
+private:
+
+ struct SharedFileInfo
+ {
+ SharedFileInfo()
+ : mLock( NULL ),
+ mSharedFile( NULL ),
+ mImageWidth( 0 ),
+ mImageHeight( 0 ),
+ mLockFileName(),
+ mSharedFileName(),
+ mSharedFileID( 0 ),
+ mSharedFileNumber( 0 )
+ {
+ }
+
+ LockFile* mLock; ///< File lock for the shared file
+ SharedFile* mSharedFile; ///< Shared file
+
+ int mImageWidth; ///< Shared image width
+ int mImageHeight; ///< Shared image height
+
+ std::string mLockFileName; ///< Lock file name
+ std::string mSharedFileName; ///< Shared file name
+ int mSharedFileID; ///< Shared file ID
+ int mSharedFileNumber; ///< Shared file number
+ };
+
+ static const int SHARED_FILE_NUMBER = 2; ///< Shared file number
+
+ Dali::Geometry mTranslucentGeometry; ///< Geometry used for rendering the translucent background
+ Dali::Geometry mSolidGeometry; ///< Geometry used for rendering the opaque background
+ Dali::Shader mBackgroundShader; ///< Shader used for rendering the background
+
+ IndicatorBufferPtr mIndicatorBuffer; ///< class which handles indicator rendering
+ PixmapId mPixmap; ///< Pixmap including indicator content
+ Dali::Renderer mForegroundRenderer; ///< Renderer renders the indicator foreground
+ Dali::Renderer mBackgroundRenderer; ///< Renderer renders the indicator background
+
+ Dali::Actor mIndicatorContentActor; ///< Actor container for image and background
+ Dali::Actor mIndicatorActor; ///< Handle to topmost indicator actor
+ Dali::Actor mEventActor; ///< Handle to event
+ Dali::PanGestureDetector mPanDetector; ///< Pan detector to find flick gesture for hidden indicator
+ float mGestureDeltaY; ///< Checking how much panning moved
+ bool mGestureDetected; ///< Whether find the flick gesture
+
+ Dali::Timer mReconnectTimer; ///< Reconnection timer
+ SlotDelegate< Indicator > mConnection;
+
+ Dali::Window::IndicatorBgOpacity mOpacityMode; ///< Opacity enum for background
+ Indicator::State mState; ///< The connection state
+
+ Adaptor* mAdaptor;
+ ServerConnection* mServerConnection;
+ IndicatorInterface::Observer* mObserver; ///< Upload observer
+
+ Dali::Window::WindowOrientation mOrientation;
+ int mImageWidth;
+ int mImageHeight;
+ Dali::Window::IndicatorVisibleMode mVisible; ///< Whether the indicator is visible
+
+ Dali::Timer mShowTimer; ///< Timer to show indicator
+ bool mIsShowing; ///< Whether the indicator is showing on the screen
+ Dali::Animation mIndicatorAnimation; ///< Animation to show/hide indicator image
+
+ bool mIsAnimationPlaying; ///< Whether the animation is playing
+
+ int mCurrentSharedFile; ///< Current shared file number
+ SharedFileInfo mSharedFileInfo[SHARED_FILE_NUMBER]; ///< Table to store shared file info
+
+ BufferType mSharedBufferType; ///< Shared buffer type which is used to render indicator
+
+ struct Impl; ///< Contains Ecore specific information
+ Impl* mImpl; ///< Created on construction and destroyed on destruction.
+
+ bool mBackgroundVisible; ///< Indicate whether background is visible
+ int mTopMargin; ///< Top margin of the stage for indicator
+};
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/ecore-server-connection.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+
+namespace
+{
+// Copied from ecore_evas_extn_engine.h
+// procotol version - change this as needed
+const int MAJOR( 0x2011 );
+}
+
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gIndicatorLogFilter;
+#endif
+
+ServerConnection::ServerConnection(
+ const char* serviceName,
+ int serviceNumber,
+ bool isSystem,
+ ServerConnection::Observer* observer)
+
+: mConnected(false),
+ mObserver(observer)
+{
+ Ecore_Ipc_Type ipctype = ECORE_IPC_LOCAL_USER;
+
+ ecore_ipc_init();
+ mService.name = eina_stringshare_add(serviceName);
+ mService.num = serviceNumber;
+ mService.isSystem = isSystem;
+
+ if( mService.isSystem )
+ {
+ ipctype = ECORE_IPC_LOCAL_SYSTEM;
+ }
+
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: Connecting to %s %d\n", mService.name, mService.num );
+
+ mIpcServer = ecore_ipc_server_connect( ipctype, (char *)mService.name, mService.num, this );
+
+ if( !mIpcServer )
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "mIpcServer is null\n" );
+ ecore_ipc_shutdown();
+ }
+ else
+ {
+ mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_ADD,
+ &ServerConnection::IpcServerAdd,
+ this ) );
+
+ mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_DEL,
+ &ServerConnection::IpcServerDel,
+ this ) );
+
+ mIpcHandlers.push_back( ecore_event_handler_add( ECORE_IPC_EVENT_SERVER_DATA,
+ &ServerConnection::IpcServerData,
+ this));
+
+ mConnected = true;
+ }
+}
+
+ServerConnection::~ServerConnection()
+{
+ CloseConnection();
+
+ if( mService.name != NULL )
+ {
+ eina_stringshare_del(mService.name);
+ }
+
+ for( Handlers::iterator iter = mIpcHandlers.begin(); iter != mIpcHandlers.end(); ++iter )
+ {
+ ecore_event_handler_del(*iter);
+ }
+ mIpcHandlers.clear();
+}
+
+bool ServerConnection::IsConnected()
+{
+ return mConnected;
+}
+
+void ServerConnection::OnDisconnect()
+{
+ mConnected = false;
+ mIpcServer = NULL;
+ ecore_ipc_shutdown();
+ if( mObserver )
+ {
+ mObserver->ConnectionClosed();
+ }
+}
+
+bool ServerConnection::SendEvent( int event, const void *data, int size )
+{
+ return SendEvent(event, 0, 0, data, size);
+}
+
+bool ServerConnection::SendEvent( int event, int ref, int ref_to, const void *data, int size )
+{
+ if( mIpcServer != NULL && ecore_ipc_server_send(mIpcServer, MAJOR, event, ref, ref_to, 0, data, size) )
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+}
+
+Eina_Bool ServerConnection::IpcServerAdd( void *data, int /*type*/, void *event )
+{
+ DALI_LOG_INFO(gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerAdd\n" );
+
+ return ECORE_CALLBACK_PASS_ON;
+}
+
+Eina_Bool ServerConnection::IpcServerDel( void *data, int /*type*/, void *event )
+{
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerDel\n" );
+
+ Ecore_Ipc_Event_Server_Del *e = static_cast<Ecore_Ipc_Event_Server_Del *>( event );
+ ServerConnection* connection = static_cast<ServerConnection*>( data );
+
+ if( connection != NULL )
+ {
+ if( connection->mIpcServer == e->server)
+ {
+ // No longer have a server connection
+ connection->OnDisconnect();
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+}
+
+Eina_Bool ServerConnection::IpcServerData( void *data, int /*type*/, void *event )
+{
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: IpcServerData\n" );
+
+ Ecore_Ipc_Event_Server_Data *e = static_cast<Ecore_Ipc_Event_Server_Data *>( event );
+ ServerConnection* connection = static_cast<ServerConnection*>( data );
+
+ if( connection != NULL )
+ {
+ if( connection != ecore_ipc_server_data_get( e->server ) )
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ if( e->major != MAJOR )
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ if( connection->mObserver )
+ {
+ connection->mObserver->DataReceived( event );
+ }
+ }
+ return ECORE_CALLBACK_PASS_ON;
+}
+
+void ServerConnection::CloseConnection()
+{
+ if( mConnected )
+ {
+ DALI_LOG_INFO( gIndicatorLogFilter, Debug::General, "ServerConnection: CloseConnection\n" );
+
+ if( mIpcServer )
+ {
+ ecore_ipc_server_del( mIpcServer );
+ mIpcServer = NULL;
+ }
+
+ ecore_ipc_shutdown();
+ mConnected = false;
+ }
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
\ No newline at end of file
--- /dev/null
+#ifndef __DALI_INTERNAL_EVENT_HANDLER_H__
+#define __DALI_INTERNAL_EVENT_HANDLER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/events/key-event-integ.h>
+#include <dali/integration-api/events/point.h>
+#include <dali/integration-api/events/touch-event-combiner.h>
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/damage-observer.h>
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+#include <dali/internal/accessibility/common/accessibility-adaptor-impl.h>
+#include <dali/internal/clipboard/common/clipboard-event-notifier-impl.h>
+#include <dali/internal/input/common/imf-manager-impl.h>
+#include <dali/internal/window-system/common/rotation-observer.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class CoreEventInterface;
+class GestureManager;
+class StyleMonitor;
+
+/**
+ * The Event Handler class is responsible for setting up receiving of Ecore events and then converts them
+ * to TouchEvents when it does receive them.
+ *
+ * These TouchEvents are then passed on to Core.
+ */
+class EventHandler
+{
+public:
+
+ /**
+ * Constructor.
+ * @param[in] surface The surface where events will be sent to.
+ * @param[in] coreEventInterface Used to send events to Core.
+ * @param[in] gestureManager The Gesture Manager.
+ * @param[in] damageObserver The damage observer (to pass damage events to).
+ * @param[in] dndDetector The Drag & Drop listener (to pass DnD events to).
+ */
+ EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector );
+
+ /**
+ * Destructor.
+ */
+ ~EventHandler();
+
+ /**
+ * Feed (Send) touch event to core and gesture manager
+ * @param[in] touchEvent The touch event holding the touch point information.
+ */
+ void FeedTouchPoint( TouchPoint& point, int timeStamp );
+
+ /**
+ * Feed (Send) wheel event to core and gesture manager
+ * @param[in] wheelEvent The wheel event
+ */
+ void FeedWheelEvent( WheelEvent& wheelEvent );
+
+ /**
+ * Feed (Send) key event to core
+ * @param[in] keyEvent The key event holding the key information.
+ */
+ void FeedKeyEvent( KeyEvent& keyEvent );
+
+ /**
+ * Feed (Send) an event to core
+ * @param[in] event The event information.
+ */
+ void FeedEvent( Integration::Event& event );
+
+ /**
+ * Called when the adaptor is paused.
+ */
+ void Pause();
+
+ /**
+ * Called when the adaptor is resumed (from pause).
+ */
+ void Resume();
+
+ /**
+ * Sets the Drag & Drop detector.
+ * @param[in] detector An intrusive pointer to the Drag & Drop listener to set. To unset pass in NULL.
+ */
+ void SetDragAndDropDetector( DragAndDropDetectorPtr detector );
+
+ /**
+ * Set the rotation observer (note, some adaptors may not have a rotation observer)
+ * @param[in] observer The rotation observer
+ */
+ void SetRotationObserver( RotationObserver* observer );
+
+private:
+
+ /**
+ * Send touch event to core.
+ * @param[in] point The touch point information.
+ * @param[in] timeStamp The time the touch occurred.
+ */
+ void SendEvent(Integration::Point& point, unsigned long timeStamp);
+
+ /**
+ * Send key event to core.
+ * @param[in] keyEvent The KeyEvent to send.
+ */
+ void SendEvent(Integration::KeyEvent& keyEvent);
+
+ /**
+ * Send wheel event to core.
+ * @param[in] wheelEvent The wheel event
+ */
+ void SendWheelEvent( WheelEvent& wheelEvent );
+
+ /**
+ * Send a style change event to the style monitor.
+ * @param[in] styleChange The style that has changed.
+ */
+ void SendEvent( StyleChange::Type styleChange );
+
+ /**
+ * Send a window damage event to the observer.
+ * @param[in] area Damaged area.
+ */
+ void SendEvent( const DamageArea& area );
+
+ /**
+ * Inform rotation observer of rotation prepare event
+ * @param[in] rotation The rotation event
+ */
+ void SendRotationPrepareEvent( const RotationEvent& rotation );
+
+ /**
+ * Inform rotation observer of rotation prepare event
+ */
+ void SendRotationRequestEvent();
+
+ /**
+ * Resets the event handler.
+ * Called when the adaptor is paused or resumed.
+ */
+ void Reset();
+
+private:
+
+ // Undefined
+ EventHandler( const EventHandler& eventHandler );
+
+ // Undefined
+ EventHandler& operator=( const EventHandler& eventHandler );
+
+private:
+
+ CoreEventInterface& mCoreEventInterface; ///< Used to send events to Core.
+ Dali::Integration::TouchEventCombiner mCombiner; ///< Combines multi-touch events.
+ GestureManager& mGestureManager; ///< Reference to the GestureManager, set on construction, to send touch events to for analysis.
+ Dali::StyleMonitor mStyleMonitor; ///< Handle to the style monitor, set on construction, to send font size and font change events to.
+ DamageObserver& mDamageObserver; ///< Reference to the DamageObserver, set on construction, to sent damage events to.
+ RotationObserver* mRotationObserver; ///< Pointer to rotation observer, if present.
+
+ DragAndDropDetectorPtr mDragAndDropDetector; ///< Pointer to the drag & drop detector, to send Drag & Drop events to.
+ Dali::AccessibilityAdaptor mAccessibilityAdaptor; ///< Pointer to the accessibility adaptor
+ Dali::ClipboardEventNotifier mClipboardEventNotifier; ///< Pointer to the clipboard event notifier
+ Dali::Clipboard mClipboard;///< Pointer to the clipboard
+
+ struct Impl; ///< Implementation
+ Impl* mImpl; ///< Created on construction and destroyed on destruction.
+
+ bool mPaused; ///< The paused state of the adaptor.
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_EVENT_HANDLER_H__
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/indicator-buffer.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+IndicatorBuffer::IndicatorBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat )
+: mAdaptor(adaptor),
+ mImageWidth(width),
+ mImageHeight(height),
+ mPixelFormat(pixelFormat)
+{
+ DALI_ASSERT_ALWAYS( adaptor );
+
+ // Use BitmapImage when SharedGlBuffer extension is unavailable
+ mBitmapBuffer = new NativeBitmapBuffer( adaptor, mImageWidth, mImageHeight, mPixelFormat );
+ mNativeImage = mBitmapBuffer;
+}
+
+bool IndicatorBuffer::UpdatePixels( const unsigned char *src, size_t size )
+{
+ // Use double buffered bitmap when SharedGlBuffer extension is unavailable
+ mBitmapBuffer->Write( src, size );
+ return true;
+}
+
+NativeImageInterface& IndicatorBuffer::GetNativeImage() const
+{
+ DALI_ASSERT_DEBUG(mNativeImage.Get());
+ return *mNativeImage;
+}
+
+void IndicatorBuffer::SetAdaptor( Adaptor* adaptor )
+{
+ mAdaptor = adaptor;
+}
+
+} // Adaptor
+} // Internal
+} // Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_INDICATOR_BUFFER_H__
+#define __DALI_INTERNAL_INDICATOR_BUFFER_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/ref-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/native-bitmap-buffer-impl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+namespace Adaptor
+{
+
+class NativeBitmapBuffer;
+class IndicatorBuffer;
+
+typedef IntrusivePtr<IndicatorBuffer> IndicatorBufferPtr;
+
+/**
+ * The IndicatorBuffer class uses the best available implementation for rendering indicator data.
+ * On platforms where EglImage is available it uses either SharedGlBuffer or NativeImageSource, on older
+ * platforms it falls back to using a bitmap buffer based solution.
+ */
+class IndicatorBuffer : public RefObject
+{
+public:
+
+ /**
+ * Constructor
+ */
+ IndicatorBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat );
+
+ /**
+ * Copy bitmap data to pixel buffer.
+ * @param src bitmap data source
+ * @param size size of bitmap data
+ * @return true if successful, false otherwise
+ */
+ bool UpdatePixels( const unsigned char *src, size_t size );
+
+ /**
+ * Returns the NativeImage used internally
+ * @return the NativeImage used internally
+ */
+ NativeImageInterface& GetNativeImage() const;
+
+ /**
+ * Set currently used Adaptor
+ * @param adaptor
+ */
+ void SetAdaptor( Adaptor* adaptor );
+
+private:
+ NativeImageInterfacePtr mNativeImage; ///< Image buffer created for shared file copy
+
+ NativeBitmapBufferPtr mBitmapBuffer; ///< Image buffer created for shared file copy if extension not available
+
+ Adaptor* mAdaptor;
+
+ int mImageWidth;
+ int mImageHeight;
+ Pixel::Format mPixelFormat;
+};
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif // __DALI_INTERNAL_INDICATOR_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_BASE_INDICATOR_INTERFACE_H__
+#define __DALI_INTERNAL_BASE_INDICATOR_INTERFACE_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/actors/actor.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/window.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+class Adaptor;
+
+/**
+ * @brief The Indicator interface.
+ * Can be used to draw an indicator graphic generated from the platform as an overlay on
+ * top of DALi scene contents.
+ */
+class IndicatorInterface
+{
+public:
+
+ /**
+ * @brief Type of indiciator
+ */
+ enum Type
+ {
+ INDICATOR_TYPE_UNKNOWN,
+ INDICATOR_TYPE_1,
+ INDICATOR_TYPE_2
+ };
+
+
+public:
+
+ /**
+ * @brief observer for listening to indicator events
+ */
+ class Observer
+ {
+ public:
+ /**
+ * @brief Notify the observer if the indicator type changes
+ * @param[in] type The new indicator type
+ */
+ virtual void IndicatorTypeChanged( Type type ) = 0;
+
+ /**
+ * @brief Notify the observer when the upload has completed.
+ * @param[in] indicator The indicator that has finished uploading.
+ */
+ virtual void IndicatorClosed(IndicatorInterface* indicator) = 0;
+
+ /**
+ * @brief Notify the observer when the indicator visible status is changed.
+ * @param[in] isShowing Whether the indicator is visible.
+ */
+ virtual void IndicatorVisibilityChanged( bool isVisible ) = 0;
+ };
+
+
+public:
+
+ /**
+ * @brief constructor
+ */
+ IndicatorInterface() {}
+
+ /**
+ * @brief Virtual Destructor
+ */
+ virtual ~IndicatorInterface() {}
+
+ /**
+ * @brief assign the adaptor to this object
+ * @param[in] adaptor
+ */
+ virtual void SetAdaptor(Adaptor* adaptor) = 0;
+
+ /**
+ * @brief Get the actor which contains the indicator image. Ensure that the handle is
+ * released when no longer needed.
+ * Changes from the indicator service will modify the image and resize the actor appropriately.
+ * @return The indicator actor.
+ */
+ virtual Dali::Actor GetActor() = 0;
+
+ /**
+ * Opens a new connection for the required orientation.
+ * @param[in] orientation The new orientation
+ */
+ virtual void Open( Dali::Window::WindowOrientation orientation ) = 0;
+
+ /**
+ * Close the current connection. Will respond with Observer::IndicatorClosed()
+ * when done.
+ * @note, IndicatorClosed() will be called synchronously if there's no update
+ * in progress, or asychronously if waiting for SignalUploaded )
+ */
+ virtual void Close() = 0;
+
+ /**
+ * Set the opacity mode of the indicator background.
+ * @param[in] mode opacity mode
+ */
+ virtual void SetOpacityMode( Dali::Window::IndicatorBgOpacity mode ) = 0;
+
+ /**
+ * Set whether the indicator is visible or not.
+ * @param[in] visibleMode visible mode for indicator bar.
+ * @param[in] forceUpdate true if want to change visible mode forcely
+ */
+ virtual void SetVisible( Dali::Window::IndicatorVisibleMode visibleMode, bool forceUpdate = false ) = 0;
+
+ /**
+ * Check whether the indicator is connected to the indicator service.
+ * @return whether the indicator is connected or not.
+ */
+ virtual bool IsConnected() = 0;
+
+ /**
+ * Send message to the indicator service.
+ * @param[in] messageDomain Message Reference number
+ * @param[in] messageId Reference number of the message this message refers to
+ * @param[in] data The data to send as part of the message
+ * @param[in] size Length of the data, in bytes, to send
+ * @return whether the message is sent successfully or not
+ */
+ virtual bool SendMessage( int messageDomain, int messageId, const void *data, int size ) = 0;
+
+
+};
+
+} // Adaptor
+} // Internal
+} // Dali
+
+#endif
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/orientation-impl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/window-impl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+Orientation* Orientation::New(Window* window)
+{
+ Orientation* orientation = new Orientation(window);
+
+ return orientation;
+}
+
+Orientation::Orientation(Window* window)
+: mWindow(window),
+ mOrientation(0),
+ mWindowWidth(0),
+ mWindowHeight(0)
+{
+}
+
+Orientation::~Orientation()
+{
+ // Note, there is only one orientation object that's owned by window,
+ // so it will live longer than adaptor. (hence, no need to remove rotation observer)
+}
+
+void Orientation::SetAdaptor(Dali::Adaptor& adaptor)
+{
+ Adaptor& adaptorImpl = Adaptor::GetImplementation(adaptor);
+ adaptorImpl.SetRotationObserver(this);
+}
+
+int Orientation::GetDegrees() const
+{
+ return mOrientation;
+}
+
+float Orientation::GetRadians() const
+{
+ return Math::PI * float(mOrientation) / 180.0f;
+}
+
+Orientation::OrientationSignalType& Orientation::ChangedSignal()
+{
+ return mChangedSignal;
+}
+
+void Orientation::OnRotationPrepare( const RotationEvent& rotation )
+{
+ mOrientation = rotation.angle;
+ mWindowWidth = rotation.width;
+ mWindowHeight = rotation.height;
+}
+
+void Orientation::OnRotationRequest()
+{
+ // Emit signal
+ if( !mChangedSignal.Empty() )
+ {
+ Dali::Orientation handle( this );
+ mChangedSignal.Emit( handle );
+ }
+
+ if( mWindow != NULL )
+ {
+ mWindow->RotationDone( mOrientation, mWindowWidth, mWindowHeight );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ORIENTATION_H__
+#define __DALI_INTERNAL_ORIENTATION_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <cmath>
+#include <dali/public-api/common/constants.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/orientation.h>
+#include <dali/internal/window-system/common/rotation-observer.h>
+
+namespace Dali
+{
+class Adaptor;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class Window;
+class Orientation;
+
+typedef IntrusivePtr<Orientation> OrientationPtr;
+
+class Orientation : public BaseObject, public RotationObserver
+{
+public:
+
+ typedef Dali::Orientation::OrientationSignalType OrientationSignalType;
+
+ static Orientation* New(Window* window);
+
+ /**
+ * Constructor
+ */
+ Orientation(Window* window);
+
+protected:
+ /**
+ * Destructor
+ */
+ virtual ~Orientation();
+
+public:
+ /**
+ * Set the adaptor for basic setup
+ * @param[in] adaptor The adaptor
+ */
+ void SetAdaptor(Dali::Adaptor& adaptor);
+
+ /**
+ * Returns the actual orientation in degrees
+ * @return The device's orientation
+ */
+ int GetDegrees() const;
+
+ /**
+ * Returns the actual orientation in radians
+ * @return The device's orientation
+ */
+ float GetRadians() const;
+
+public: // Signals
+
+ /**
+ * @copydoc Dali::Orientation::ChangedSignal()
+ */
+ OrientationSignalType& ChangedSignal();
+
+private:
+ /**
+ * @copydoc Dali::Internal::Adaptor::RotationObserver::OnRotationPrepare()
+ */
+ virtual void OnRotationPrepare( const RotationEvent& rotation );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::RotationObserver::OnRotationRequest()
+ */
+ virtual void OnRotationRequest( );
+
+ // Undefined
+ Orientation(const Orientation&);
+ Orientation& operator=(Orientation&);
+
+private:
+ /**
+ * Signals and sends event of orientation change.
+ */
+ void EmitOrientationChange();
+
+private:
+
+ Window* mWindow;
+
+ OrientationSignalType mChangedSignal;
+
+ int mOrientation;
+ int mWindowWidth;
+ int mWindowHeight;
+};
+
+inline Orientation& GetImplementation (Dali::Orientation& orientation)
+{
+ DALI_ASSERT_ALWAYS(orientation && "Orientation handle is empty");
+
+ BaseObject& handle = orientation.GetBaseObject();
+
+ return static_cast<Orientation&>(handle);
+}
+
+inline const Orientation& GetImplementation(const Dali::Orientation& orientation)
+{
+ DALI_ASSERT_ALWAYS(orientation && "Orientation handle is empty");
+
+ const BaseObject& handle = orientation.GetBaseObject();
+
+ return static_cast<const Orientation&>(handle);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ORIENTATION_H__
--- /dev/null
+#ifndef __DALI_INTERNAL_WINDOW_H__
+#define __DALI_INTERNAL_WINDOW_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/base-object.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/lifecycle-observer.h>
+#include <dali/internal/window-system/common/indicator-interface.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/public-api/adaptor-framework/window.h>
+#include <dali/devel-api/adaptor-framework/orientation.h>
+#include <dali/devel-api/adaptor-framework/render-surface.h>
+#include <dali/devel-api/adaptor-framework/drag-and-drop-detector.h>
+
+namespace Dali
+{
+class Adaptor;
+class RenderSurface;
+
+namespace Integration
+{
+class SystemOverlay;
+}
+
+namespace Internal
+{
+namespace Adaptor
+{
+class Orientation;
+
+class Window;
+typedef IntrusivePtr<Window> WindowPtr;
+typedef IntrusivePtr<Orientation> OrientationPtr;
+
+/**
+ * Window provides a surface to render onto with orientation & indicator properties.
+ */
+class Window : public Dali::BaseObject, public IndicatorInterface::Observer, public LifeCycleObserver
+{
+public:
+ typedef Dali::Window::IndicatorSignalType IndicatorSignalType;
+ typedef Dali::Window::FocusSignalType FocusSignalType;
+ typedef Dali::Window::ResizedSignalType ResizedSignalType;
+ typedef Signal< void () > SignalType;
+
+ /**
+ * Create a new Window. This should only be called once by the Application class
+ * @param[in] positionSize The position and size of the window
+ * @param[in] name The window title
+ * @param[in] className The window class name
+ * @param[in] isTransparent Whether window is transparent
+ * @return A newly allocated Window
+ */
+ static Window* New(const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent = false);
+
+ /**
+ * Pass the adaptor back to the overlay. This allows the window to access Core's overlay.
+ * @param[in] adaptor An initialized adaptor
+ */
+ void SetAdaptor(Dali::Adaptor& adaptor);
+
+ /**
+ * Get the window surface
+ * @return The render surface
+ */
+ RenderSurface* GetSurface();
+
+ /**
+ * @copydoc Dali::Window::ShowIndicator()
+ */
+ void ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode );
+
+ /**
+ * @copydoc Dali::Window::SetIndicatorBgOpacity()
+ */
+ void SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacity );
+
+ /**
+ * @copydoc Dali::Window::RotateIndicator()
+ */
+ void RotateIndicator( Dali::Window::WindowOrientation orientation );
+
+ /**
+ * @copydoc Dali::Window::SetClass()
+ */
+ void SetClass( std::string name, std::string klass );
+
+ /**
+ * @copydoc Dali::Window::Raise()
+ */
+ void Raise();
+
+ /**
+ * @copydoc Dali::Window::Lower()
+ */
+ void Lower();
+
+ /**
+ * @copydoc Dali::Window::Activate()
+ */
+ void Activate();
+
+ /**
+ * @copydoc Dali::Window::AddAvailableOrientation()
+ */
+ void AddAvailableOrientation(Dali::Window::WindowOrientation orientation);
+
+ /**
+ * @copydoc Dali::Window::RemoveAvailableOrientation()
+ */
+ void RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation);
+
+ /**
+ * @copydoc Dali::Window::SetAvailableOrientations()
+ */
+ void SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations);
+
+ /**
+ * @copydoc Dali::Window::GetAvailableOrientations()
+ */
+ const std::vector<Dali::Window::WindowOrientation>& GetAvailableOrientations();
+
+ /**
+ * @copydoc Dali::Window::SetPreferredOrientation()
+ */
+ void SetPreferredOrientation(Dali::Window::WindowOrientation orientation);
+
+ /**
+ * @copydoc Dali::Window::GetPreferredOrientation()
+ */
+ Dali::Window::WindowOrientation GetPreferredOrientation();
+
+ /**
+ * @copydoc Dali::Window::GetDragAndDropDetector() const
+ */
+ Dali::DragAndDropDetector GetDragAndDropDetector() const;
+
+ /**
+ * @copydoc Dali::Window::GetNativeHandle() const
+ */
+ Dali::Any GetNativeHandle() const;
+
+ /**
+ * @copydoc Dali::Window::SetAcceptFocus()
+ */
+ void SetAcceptFocus( bool accept );
+
+ /**
+ * @copydoc Dali::Window::IsFocusAcceptable()
+ */
+ bool IsFocusAcceptable() const;
+
+ /**
+ * @copydoc Dali::Window::Show()
+ */
+ void Show();
+
+ /**
+ * @copydoc Dali::Window::Hide()
+ */
+ void Hide();
+
+ /**
+ * @copydoc Dali::Window::IsVisible() const
+ */
+ bool IsVisible() const;
+
+ /**
+ * @copydoc Dali::Window::GetSupportedAuxiliaryHintCount()
+ */
+ unsigned int GetSupportedAuxiliaryHintCount() const;
+
+ /**
+ * @copydoc Dali::Window::GetSupportedAuxiliaryHint()
+ */
+ std::string GetSupportedAuxiliaryHint( unsigned int index ) const;
+
+ /**
+ * @copydoc Dali::Window::AddAuxiliaryHint()
+ */
+ unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value );
+
+ /**
+ * @copydoc Dali::Window::RemoveAuxiliaryHint()
+ */
+ bool RemoveAuxiliaryHint( unsigned int id );
+
+ /**
+ * @copydoc Dali::Window::SetAuxiliaryHintValue()
+ */
+ bool SetAuxiliaryHintValue( unsigned int id, const std::string& value );
+
+ /**
+ * @copydoc Dali::Window::GetAuxiliaryHintValue()
+ */
+ std::string GetAuxiliaryHintValue( unsigned int id ) const;
+
+ /**
+ * @copydoc Dali::Window::GetAuxiliaryHintId()
+ */
+ unsigned int GetAuxiliaryHintId( const std::string& hint ) const;
+
+ /**
+ * @copydoc Dali::Window::SetInputRegion()
+ */
+ void SetInputRegion( const Rect< int >& inputRegion );
+
+ /**
+ * @copydoc Dali::Window::SetType()
+ */
+ void SetType( Dali::Window::Type type );
+
+ /**
+ * @copydoc Dali::Window::GetType() const
+ */
+ Dali::Window::Type GetType() const;
+
+ /**
+ * @copydoc Dali::Window::SetNotificationLevel()
+ */
+ bool SetNotificationLevel( Dali::Window::NotificationLevel::Type level );
+
+ /**
+ * @copydoc Dali::Window::GetNotificationLevel()
+ */
+ Dali::Window::NotificationLevel::Type GetNotificationLevel() const;
+
+ /**
+ * @copydoc Dali::Window::SetOpaqueState()
+ */
+ void SetOpaqueState( bool opaque );
+
+ /**
+ * @copydoc Dali::Window::IsOpaqueState()
+ */
+ bool IsOpaqueState() const;
+
+ /**
+ * @copydoc Dali::Window::SetScreenOffMode()
+ */
+ bool SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode);
+
+ /**
+ * @copydoc Dali::Window::GetScreenOffMode()
+ */
+ Dali::Window::ScreenOffMode::Type GetScreenOffMode() const;
+
+ /**
+ * @copydoc Dali::Window::SetBrightness()
+ */
+ bool SetBrightness( int brightness );
+
+ /**
+ * @copydoc Dali::Window::GetBrightness()
+ */
+ int GetBrightness() const;
+
+ /**
+ * @copydoc Dali::Window::SetSize()
+ */
+ void SetSize( Dali::Window::WindowSize size );
+
+ /**
+ * @copydoc Dali::Window::GetSize()
+ */
+ Dali::Window::WindowSize GetSize() const;
+
+ /**
+ * @copydoc Dali::Window::SetPosition()
+ */
+ void SetPosition( Dali::Window::WindowPosition position );
+
+ /**
+ * @copydoc Dali::Window::GetPosition()
+ */
+ Dali::Window::WindowPosition GetPosition() const;
+
+ /**
+ * @copydoc Dali::Window::SetTransparency()
+ */
+ void SetTransparency( bool transparent );
+
+ /**
+ * Called from Orientation after the Change signal has been sent
+ */
+ void RotationDone( int orientation, int width, int height );
+
+ /**
+ * Set the indicator visible mode
+ */
+ void SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode );
+
+private:
+ /**
+ * Private constructor.
+ * @sa Window::New()
+ */
+ Window();
+
+ /**
+ * Destructor
+ */
+ virtual ~Window();
+
+ /**
+ * Second stage initialization
+ */
+ void Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className);
+
+ /**
+ * Shows / hides the indicator bar.
+ * Handles close/open if rotation changes whilst hidden
+ */
+ void DoShowIndicator( Dali::Window::WindowOrientation lastOrientation );
+
+ /**
+ * Close current indicator and open a connection onto the new indicator service.
+ * Effect may not be synchronous if waiting for an indicator update on existing connection.
+ */
+ void DoRotateIndicator( Dali::Window::WindowOrientation orientation );
+
+ /**
+ * Change the indicator actor's rotation to match the current orientation
+ */
+ void SetIndicatorActorRotation();
+
+ /**
+ * Set the indicator properties on the window
+ */
+ void SetIndicatorProperties( bool isShown, Dali::Window::WindowOrientation lastOrientation );
+
+private: // IndicatorInterface::Observer interface
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorTypeChanged()
+ */
+ virtual void IndicatorTypeChanged( IndicatorInterface::Type type );
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorClosed()
+ */
+ virtual void IndicatorClosed( IndicatorInterface* indicator);
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::IndicatorInterface::Observer::IndicatorVisibilityChanged()
+ */
+ virtual void IndicatorVisibilityChanged( bool isVisible );
+
+private: // Adaptor::Observer interface
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnStart()
+ */
+ virtual void OnStart();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnPause()
+ */
+ virtual void OnPause();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnResume()
+ */
+ virtual void OnResume();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnStop()
+ */
+ virtual void OnStop();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::Adaptor::Observer::OnDestroy()
+ */
+ virtual void OnDestroy();
+
+public: // Signals
+
+ /**
+ * The user should connect to this signal to get a timing when indicator was shown / hidden.
+ */
+ IndicatorSignalType& IndicatorVisibilityChangedSignal() { return mIndicatorVisibilityChangedSignal; }
+
+ /**
+ * @copydoc Dali::Window::FocusChangedSignal()
+ */
+ FocusSignalType& FocusChangedSignal() { return mFocusChangedSignal; }
+
+ /**
+ * @copydoc Dali::Window::ResizedSignal()
+ */
+ ResizedSignalType& ResizedSignal() { return mResizedSignal; }
+
+ /**
+ * This signal is emitted when the window is requesting to be deleted
+ */
+ SignalType& DeleteRequestSignal() { return mDeleteRequestSignal; }
+
+private:
+
+ typedef std::vector< std::pair< std::string, std::string > > AuxiliaryHints;
+
+ RenderSurface* mSurface;
+ Dali::Window::IndicatorVisibleMode mIndicatorVisible; ///< public state
+ bool mIndicatorIsShown:1; ///< private state
+ bool mShowRotatedIndicatorOnClose:1;
+ bool mStarted:1;
+ bool mIsTransparent:1;
+ bool mWMRotationAppSet:1;
+ bool mEcoreEventHander:1;
+ bool mIsFocusAcceptable:1;
+ bool mVisible:1;
+ bool mIconified:1;
+ bool mOpaqueState:1;
+ bool mResizeEnabled:1;
+ IndicatorInterface* mIndicator;
+ Dali::Window::WindowOrientation mIndicatorOrientation;
+ Dali::Window::WindowOrientation mNextIndicatorOrientation;
+ Dali::Window::IndicatorBgOpacity mIndicatorOpacityMode;
+ Integration::SystemOverlay* mOverlay;
+ Adaptor* mAdaptor;
+ Dali::DragAndDropDetector mDragAndDropDetector;
+ Dali::Window::Type mType;
+
+ struct EventHandler;
+ EventHandler* mEventHandler;
+
+ OrientationPtr mOrientation;
+ std::vector<Dali::Window::WindowOrientation> mAvailableOrientations;
+ Dali::Window::WindowOrientation mPreferredOrientation;
+
+ std::vector< std::string > mSupportedAuxiliaryHints;
+ AuxiliaryHints mAuxiliaryHints;
+
+ // Signals
+ IndicatorSignalType mIndicatorVisibilityChangedSignal;
+ FocusSignalType mFocusChangedSignal;
+ ResizedSignalType mResizedSignal;
+ SignalType mDeleteRequestSignal;
+};
+
+} // namespace Adaptor
+} // namepsace Internal
+
+// Helpers for public-api forwarding methods
+
+inline Internal::Adaptor::Window& GetImplementation(Dali::Window& window)
+{
+ DALI_ASSERT_ALWAYS( window && "Window handle is empty" );
+ BaseObject& object = window.GetBaseObject();
+ return static_cast<Internal::Adaptor::Window&>(object);
+}
+
+inline const Internal::Adaptor::Window& GetImplementation(const Dali::Window& window)
+{
+ DALI_ASSERT_ALWAYS( window && "Window handle is empty" );
+ const BaseObject& object = window.GetBaseObject();
+ return static_cast<const Internal::Adaptor::Window&>(object);
+}
+
+} // namespace Dali
+
+
+#endif // __DALI_INTERNAL_WINDOW_H__
--- /dev/null
+
+
+# module: window-system, backend: common
+adaptor_window_system_common_src_files=\
+ ${adaptor_window_system_dir}/common/display-connection.cpp \
+ ${adaptor_window_system_dir}/common/display-connection-impl.cpp \
+ ${adaptor_window_system_dir}/common/ecore-indicator-impl.cpp \
+ ${adaptor_window_system_dir}/common/ecore-server-connection.cpp \
+ ${adaptor_window_system_dir}/common/indicator-buffer.cpp \
+ ${adaptor_window_system_dir}/common/orientation-impl.cpp
+
+# module: window-system, backend: tizen
+adaptor_window_system_tizen_src_files=\
+ ${adaptor_window_system_dir}/tizen/display-connection-impl-tizen.cpp
+
+# module: window-system, backend: tizen-mobile
+adaptor_window_system_tizen_mobile_src_files=\
+ ${adaptor_window_system_dir}/tizen-mobile/native-render-surface-factory-mobile.cpp
+
+# module: window-system, backend: tizen
+adaptor_window_system_tizen_src_files=\
+ ${adaptor_window_system_dir}/tizen/native-render-surface-tizen.cpp
+
+# module: window-system, backend: tizen-wayland
+adaptor_window_system_tizen_wayland_src_files=\
+ ${adaptor_window_system_dir}/tizen-wayland/display-connection-factory-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/display-connection-impl-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/event-handler-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/pixmap-render-surface-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/render-surface-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/window-impl-ecore-wl.cpp \
+ ${adaptor_window_system_dir}/tizen-wayland/window-render-surface-ecore-wl.cpp
+
+# module: window-system, backend: tizen-wearable
+adaptor_window_system_tizen_wearable_src_files=\
+ ${adaptor_window_system_dir}/tizen-wearable/native-render-surface-factory-wearable.cpp
+
+# module: window-system, backend: ubuntu-x11
+adaptor_window_system_ubuntu_x11_src_files=\
+ ${adaptor_window_system_dir}/ubuntu-x11/display-connection-factory-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/display-connection-impl-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/event-handler-ecore-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/render-surface-ecore-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/render-surface-factory-ecore-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/window-interface-ecore-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/window-impl-x.cpp \
+ ${adaptor_window_system_dir}/ubuntu-x11/window-render-surface-x.cpp \
+ ${adaptor_window_system_dir}/tizen/pixmap-render-surface-x.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/native-render-surface.h>
+
+namespace Dali
+{
+
+DALI_EXPORT_API NativeRenderSurface* CreateNativeSurface(
+ PositionSize positionSize,
+ const std::string& name,
+ bool isTransparent)
+{
+ return new NativeRenderSurface( positionSize, name, isTransparent );
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.h>
+#include <dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+
+
+std::unique_ptr<Dali::Internal::Adaptor::DisplayConnection> DisplayConnectionFactoryEcoreWl::CreateDisplayConnection()
+{
+ return Utils::MakeUnique<DisplayConnectionEcoreWl>();
+}
+
+// this should be created from somewhere
+std::unique_ptr<DisplayConnectionFactory> GetDisplayConnectionFactory()
+{
+ // returns X display factory
+ return Utils::MakeUnique<DisplayConnectionFactoryEcoreWl>();
+}
+
+void DisplayConnectionFactoryGetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ DisplayConnectionEcoreWl::GetDpi( dpiHorizontal, dpiVertical );
+}
+
+}
+}
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_FACTORY_ECORE_WL_H
+#define DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_FACTORY_ECORE_WL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/window-system/common/display-connection-factory.h>
+#include <dali/internal/window-system/common/display-utils.h>
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+class DisplayConnectionFactoryEcoreWl : public DisplayConnectionFactory
+{
+public:
+ std::unique_ptr<Dali::Internal::Adaptor::DisplayConnection> CreateDisplayConnection() override;
+};
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_FACTORY_ECORE_WL_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h>
+
+// EXTERNAL_HEADERS
+#include <Ecore_Wayland.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL HEADERS
+#include <dali/integration-api/wayland/native-render-surface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+DisplayConnection* DisplayConnectionEcoreWl::New()
+{
+ DisplayConnection* pDisplayConnection(new DisplayConnectionEcoreWl());
+
+ return pDisplayConnection;
+}
+
+DisplayConnectionEcoreWl::DisplayConnectionEcoreWl()
+: mDisplay( NULL ),
+ mSurfaceType( RenderSurface::ECORE_RENDER_SURFACE )
+{
+}
+
+DisplayConnectionEcoreWl::~DisplayConnectionEcoreWl()
+{
+ if( mSurfaceType == RenderSurface::NATIVE_RENDER_SURFACE )
+ {
+ ReleaseNativeDisplay();
+ }
+}
+
+Any DisplayConnectionEcoreWl::GetDisplay()
+{
+ return Any( mDisplay );
+}
+
+void DisplayConnectionEcoreWl::ConsumeEvents()
+{
+}
+
+bool DisplayConnectionEcoreWl::InitializeEgl(EglInterface& egl)
+{
+ EglImplementation& eglImpl = static_cast<EglImplementation&>(egl);
+
+ if( !eglImpl.InitializeGles( mDisplay ) )
+ {
+ DALI_LOG_ERROR("Failed to initialize GLES.\n");
+ return false;
+ }
+
+ return true;
+}
+
+void DisplayConnectionEcoreWl::SetSurfaceType( RenderSurface::Type type )
+{
+ mSurfaceType = type;
+
+ if( mSurfaceType == RenderSurface::NATIVE_RENDER_SURFACE )
+ {
+ mDisplay = GetNativeDisplay();
+ }
+ else
+ {
+ mDisplay = reinterpret_cast< EGLNativeDisplayType >( ecore_wl_display_get() );
+ }
+}
+
+void DisplayConnectionEcoreWl::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ // calculate DPI
+ float xres, yres;
+
+ // 1 inch = 25.4 millimeters
+ xres = ecore_wl_dpi_get();
+ yres = ecore_wl_dpi_get();
+
+ dpiHorizontal = int(xres + 0.5f); // rounding
+ dpiVertical = int(yres + 0.5f);
+}
+
+EGLNativeDisplayType DisplayConnectionEcoreWl::GetNativeDisplay()
+{
+ return EGLNativeDisplayType();
+}
+
+void DisplayConnectionEcoreWl::ReleaseNativeDisplay()
+{
+
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_IMPL_ECORE_WL_H
+#define DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_IMPL_ECORE_WL_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <wayland-egl.h>
+#include <Ecore_Wayland.h>
+#include <dali/integration-api/wayland/wl-types.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection-impl.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class DisplayConnection;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * DisplayConnection implementation
+ */
+class DisplayConnectionEcoreWl : public Dali::Internal::Adaptor::DisplayConnection
+{
+public:
+
+ /**
+ * @brief Default constructor
+ */
+ DisplayConnectionEcoreWl();
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ *
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New();
+
+public:
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDisplay
+ */
+ Any GetDisplay();
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDpi
+ */
+ static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+ /**
+ * @copydoc Dali::DisplayConnection::ConsumeEvents
+ */
+ void ConsumeEvents();
+
+ /**
+ * @copydoc Dali::DisplayConnection::InitializeEgl
+ */
+ bool InitializeEgl(EglInterface& egl);
+
+ /**
+ * @brief Sets surface type
+ */
+ void SetSurfaceType( RenderSurface::Type type );
+
+
+
+public:
+
+ /**
+ * Destructor
+ */
+ virtual ~DisplayConnectionEcoreWl();
+
+protected:
+
+ /**
+ * @brief Gets display connection for native surface
+ */
+ EGLNativeDisplayType GetNativeDisplay();
+
+ /**
+ * @brief Release display connection for native surface
+ */
+ void ReleaseNativeDisplay();
+
+ // Undefined
+ DisplayConnectionEcoreWl(const DisplayConnectionEcoreWl&);
+
+ // Undefined
+ DisplayConnectionEcoreWl& operator=(const DisplayConnectionEcoreWl& rhs);
+
+private:
+ EGLNativeDisplayType mDisplay; ///< Wayland-display for rendering
+ RenderSurface::Type mSurfaceType;
+};
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_IMPL_ECORE_WL_H
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_WAYLAND_DISPLAY_CONNECTION_IMPL_WL_H
+#define DALI_INTERNAL_WINDOWSYSTEM_WAYLAND_DISPLAY_CONNECTION_IMPL_WL_H
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <wayland-egl.h>
+#include <dali/integration-api/wayland/wl-types.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class DisplayConnection;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+/**
+ * DisplayConnection implementation
+ */
+class DisplayConnection : public Dali::BaseObject
+{
+public:
+
+ /**
+ * @brief Default constructor
+ */
+ DisplayConnection();
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ *
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New();
+
+public:
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDisplay
+ */
+ Any GetDisplay();
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDpi
+ */
+ static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+ /**
+ * @copydoc Dali::DisplayConnection::ConsumeEvents
+ */
+ void ConsumeEvents();
+
+ /**
+ * @copydoc Dali::DisplayConnection::InitializeEgl
+ */
+ bool InitializeEgl(EglInterface& egl);
+
+ void SetSurfaceType( RenderSurface::Type type );
+
+public:
+
+ /**
+ * Destructor
+ */
+ virtual ~DisplayConnection();
+
+protected:
+
+ EGLNativeDisplayType GetNativeDisplay();
+
+ void ReleaseNativeDisplay();
+
+ // Undefined
+ DisplayConnection(const DisplayConnection&);
+
+ // Undefined
+ DisplayConnection& operator=(const DisplayConnection& rhs);
+
+private:
+ WlDisplay* mDisplay; ///< Wayland-display for rendering
+};
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_WAYLAND_DISPLAY_CONNECTION_IMPL_WL_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/event-handler.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Ecore_Input.h>
+#include <Ecore_IMF.h>
+#include <dali/integration-api/wayland/ecore-wl-render-surface.h>
+//#include <dali/window-system/tizen-wayland/window-render-surface-ecore-wl.h>
+#include <cstring>
+
+#include <sys/time.h>
+
+#ifndef DALI_PROFILE_UBUNTU
+#include <vconf.h>
+#include <vconf-keys.h>
+#endif // DALI_PROFILE_UBUNTU
+
+#ifdef DALI_ELDBUS_AVAILABLE
+#include <Eldbus.h>
+#endif // DALI_ELDBUS_AVAILABLE
+
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/events/device.h>
+#include <dali/public-api/events/touch-point.h>
+#include <dali/public-api/events/key-event.h>
+#include <dali/public-api/events/wheel-event.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/key-event-integ.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+#include <dali/integration-api/events/hover-event-integ.h>
+#include <dali/integration-api/events/wheel-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-manager.h>
+#include <dali/internal/window-system/tizen-wayland/window-render-surface-ecore-wl.h>
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+#include <dali/internal/input/common/key-impl.h>
+#include <dali/internal/input/common/physical-keyboard-impl.h>
+#include <dali/internal/styling/common/style-monitor-impl.h>
+#include <dali/internal/system/common/core-event-interface.h>
+#include <dali/devel-api/adaptor-framework/virtual-keyboard.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#if defined(DEBUG_ENABLED)
+namespace
+{
+Integration::Log::Filter* gTouchEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_TOUCH");
+Integration::Log::Filter* gDragAndDropLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DND");
+Integration::Log::Filter* gImfLogging = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_IMF");
+Integration::Log::Filter* gSelectionEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_SELECTION");
+} // unnamed namespace
+#endif
+
+
+namespace
+{
+
+// DBUS accessibility
+const char* BUS = "org.enlightenment.wm-screen-reader";
+const char* INTERFACE = "org.tizen.GestureNavigation";
+const char* PATH = "/org/tizen/GestureNavigation";
+
+const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 );
+
+const unsigned int BYTES_PER_CHARACTER_FOR_ATTRIBUTES = 3;
+
+/**
+ * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h.
+ * This function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Modifiers enums.
+ * @param[in] ecoreModifier the Ecore_Event_Modifier input.
+ * @return the Ecore_IMF_Keyboard_Modifiers output.
+ */
+Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier)
+{
+ int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE.
+
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR;
+ }
+
+ return static_cast<Ecore_IMF_Keyboard_Modifiers>( modifier );
+}
+
+
+// Copied from x server
+static unsigned int GetCurrentMilliSeconds(void)
+{
+ struct timeval tv;
+
+ struct timespec tp;
+ static clockid_t clockid;
+
+ if (!clockid)
+ {
+#ifdef CLOCK_MONOTONIC_COARSE
+ if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 &&
+ (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0)
+ {
+ clockid = CLOCK_MONOTONIC_COARSE;
+ }
+ else
+#endif
+ if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
+ {
+ clockid = CLOCK_MONOTONIC;
+ }
+ else
+ {
+ clockid = ~0L;
+ }
+ }
+ if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
+ {
+ return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
+ }
+
+ gettimeofday(&tv, NULL);
+ return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+}
+
+#ifndef DALI_PROFILE_UBUNTU
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced.
+#endif // DALI_PROFILE_UBUNTU
+
+/**
+ * Get the device name from the provided ecore key event
+ */
+void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result )
+{
+ const char* ecoreDeviceName = ecore_device_name_get( keyEvent->dev );
+
+ if ( ecoreDeviceName )
+ {
+ result = ecoreDeviceName;
+ }
+}
+
+/**
+ * Get the device class from the provided ecore event
+ */
+void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass )
+{
+ switch( ecoreDeviceClass )
+ {
+ case ECORE_DEVICE_CLASS_SEAT:
+ {
+ deviceClass = Device::Class::USER;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_KEYBOARD:
+ {
+ deviceClass = Device::Class::KEYBOARD;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_MOUSE:
+ {
+ deviceClass = Device::Class::MOUSE;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_TOUCH:
+ {
+ deviceClass = Device::Class::TOUCH;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_PEN:
+ {
+ deviceClass = Device::Class::PEN;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_POINTER:
+ {
+ deviceClass = Device::Class::POINTER;
+ break;
+ }
+ case ECORE_DEVICE_CLASS_GAMEPAD:
+ {
+ deviceClass = Device::Class::GAMEPAD;
+ break;
+ }
+ default:
+ {
+ deviceClass = Device::Class::NONE;
+ break;
+ }
+ }
+}
+
+void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass )
+{
+ switch( ecoreDeviceSubclass )
+ {
+ case ECORE_DEVICE_SUBCLASS_FINGER:
+ {
+ deviceSubclass = Device::Subclass::FINGER;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_FINGERNAIL:
+ {
+ deviceSubclass = Device::Subclass::FINGERNAIL;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_KNUCKLE:
+ {
+ deviceSubclass = Device::Subclass::KNUCKLE;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_PALM:
+ {
+ deviceSubclass = Device::Subclass::PALM;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_HAND_SIZE:
+ {
+ deviceSubclass = Device::Subclass::HAND_SIDE;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_HAND_FLAT:
+ {
+ deviceSubclass = Device::Subclass::HAND_FLAT;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_PEN_TIP:
+ {
+ deviceSubclass = Device::Subclass::PEN_TIP;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_TRACKPAD:
+ {
+ deviceSubclass = Device::Subclass::TRACKPAD;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_TRACKPOINT:
+ {
+ deviceSubclass = Device::Subclass::TRACKPOINT;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_TRACKBALL:
+ {
+ deviceSubclass = Device::Subclass::TRACKBALL;
+ break;
+ }
+#ifdef OVER_TIZEN_VERSION_4
+ case ECORE_DEVICE_SUBCLASS_REMOCON:
+ {
+ deviceSubclass = Device::Subclass::REMOCON;
+ break;
+ }
+ case ECORE_DEVICE_SUBCLASS_VIRTUAL_KEYBOARD:
+ {
+ deviceSubclass = Device::Subclass::VIRTUAL_KEYBOARD;
+ break;
+ }
+#endif
+ default:
+ {
+ deviceSubclass = Device::Subclass::NONE;
+ break;
+ }
+ }
+}
+
+} // unnamed namespace
+
+// Impl to hide EFL implementation.
+struct EventHandler::Impl
+{
+ // Construction & Destruction
+
+ /**
+ * Constructor
+ */
+ Impl( EventHandler* handler, Ecore_Wl_Window* window )
+ : mHandler( handler ),
+ mEcoreEventHandler(),
+ mWindow( window ),
+ mRotationAngle( 0 ),
+ mWindowWidth( 0 ),
+ mWindowHeight( 0 )
+#ifdef DALI_ELDBUS_AVAILABLE
+ , mSystemConnection( NULL )
+#endif // DALI_ELDBUS_AVAILABLE
+ {
+ // Only register for touch and key events if we have a window
+ if ( window != 0 )
+ {
+ // Register Touch events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, handler ) );
+
+ // Register Mouse wheel events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, handler ) );
+
+ // Register Focus events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, handler ) );
+
+ // Register Key events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, handler ) );
+
+ // Register Selection event - clipboard selection
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, handler ) );
+
+ // Register Rotate event
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ROTATE, EcoreEventRotate, handler) );
+
+ // Register Detent event
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_DETENT_ROTATE, EcoreEventDetent, handler) );
+
+#ifndef DALI_PROFILE_UBUNTU
+ // Register Vconf notify - font name and size
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontNameChanged, handler );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, handler );
+#endif // DALI_PROFILE_UBUNTU
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Initialize ElDBus.
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Starting DBus Initialization\n" );
+
+ // Pass in handler.
+ EcoreElDBusInitialisation( handler );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Finished DBus Initialization\n" );
+#endif // DALI_ELDBUS_AVAILABLE
+ }
+ }
+
+ /**
+ * Destructor
+ */
+ ~Impl()
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontNameChanged );
+#endif // DALI_PROFILE_UBUNTU
+
+ for( std::vector<Ecore_Event_Handler*>::iterator iter = mEcoreEventHandler.begin(), endIter = mEcoreEventHandler.end(); iter != endIter; ++iter )
+ {
+ ecore_event_handler_del( *iter );
+ }
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Close down ElDBus connections.
+ if( mSystemConnection )
+ {
+ eldbus_connection_unref( mSystemConnection );
+ }
+#endif // DALI_ELDBUS_AVAILABLE
+ }
+
+ // Static methods
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Touch Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a touch down is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ PointState::Type state ( PointState::DOWN );
+
+ // Check if the buttons field is set and ensure it's the primary touch button.
+ // If this event was triggered by buttons other than the primary button (used for touch), then
+ // just send an interrupted event to Core.
+ if ( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) )
+ {
+ state = PointState::INTERRUPTED;
+ }
+
+ Device::Class::Type deviceClass;
+ Device::Subclass::Type deviceSubclass;
+
+ GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
+ GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
+
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( state );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ point.SetDeviceClass( deviceClass );
+ point.SetDeviceSubclass( deviceSubclass );
+
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a touch up is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ Device::Class::Type deviceClass;
+ Device::Subclass::Type deviceSubclass;
+
+ GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
+ GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
+
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( PointState::UP );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ point.SetDeviceClass( deviceClass );
+ point.SetDeviceSubclass( deviceSubclass );
+
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a touch motion is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Move *touchEvent( (Ecore_Event_Mouse_Move*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ Device::Class::Type deviceClass;
+ Device::Subclass::Type deviceSubclass;
+
+ GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass );
+ GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass );
+
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( PointState::MOTION );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ point.SetDeviceClass( deviceClass );
+ point.SetDeviceSubclass( deviceSubclass );
+
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a touch is canceled.
+ */
+ static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if( touchEvent->window == (unsigned int)ecore_wl_window_id_get( handler->mImpl->mWindow ) )
+ {
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( PointState::INTERRUPTED );
+ point.SetScreenPosition( Vector2( 0.0f, 0.0f ) );
+ handler->SendEvent( point, touchEvent->timestamp );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventMouseButtonCancel\n" );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a mouse wheel is received.
+ */
+ static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Wheel *mouseWheelEvent( (Ecore_Event_Mouse_Wheel*)event );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT Ecore_Event_Mouse_Wheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z);
+
+ EventHandler* handler( (EventHandler*)data );
+ if ( mouseWheelEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ WheelEvent wheelEvent( WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp );
+ handler->SendWheelEvent( wheelEvent );
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Key Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a key down is received.
+ */
+ static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyDown \n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
+ bool eventHandled( false );
+
+ // If a device key then skip ecore_imf_context_filter_event.
+ if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
+ {
+ Ecore_IMF_Context* imfContext = NULL;
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+ }
+
+ if ( imfContext )
+ {
+ // We're consuming key down event so we have to pass to IMF so that it can parse it as well.
+ Ecore_IMF_Event_Key_Down ecoreKeyDownEvent;
+ ecoreKeyDownEvent.keyname = keyEvent->keyname;
+ ecoreKeyDownEvent.key = keyEvent->key;
+ ecoreKeyDownEvent.string = keyEvent->string;
+ ecoreKeyDownEvent.compose = keyEvent->compose;
+ ecoreKeyDownEvent.timestamp = keyEvent->timestamp;
+ ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
+ ecoreKeyDownEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
+ ecoreKeyDownEvent.dev_name = ecore_device_name_get( keyEvent->dev );
+ ecoreKeyDownEvent.dev_class = static_cast<Ecore_IMF_Device_Class>( ecore_device_class_get( keyEvent->dev ) );
+ ecoreKeyDownEvent.dev_subclass = static_cast<Ecore_IMF_Device_Subclass>( ecore_device_subclass_get( keyEvent->dev ) );
+
+ std::string checkDevice;
+ GetDeviceName( keyEvent, checkDevice );
+
+ // If the device is IME and the focused key is the direction keys, then we should send a key event to move a key cursor.
+ if( ( checkDevice == "ime" ) && ( ( !strncmp( keyEvent->keyname, "Left", 4 ) ) ||
+ ( !strncmp( keyEvent->keyname, "Right", 5 ) ) ||
+ ( !strncmp( keyEvent->keyname, "Up", 2 ) ) ||
+ ( !strncmp( keyEvent->keyname, "Down", 4 ) ) ) )
+ {
+ eventHandled = 0;
+ }
+ else
+ {
+ eventHandled = ecore_imf_context_filter_event( imfContext,
+ ECORE_IMF_EVENT_KEY_DOWN,
+ (Ecore_IMF_Event *) &ecoreKeyDownEvent );
+ }
+
+ // If the event has not been handled by IMF then check if we should reset our IMF context
+ if( !eventHandled )
+ {
+ if ( !strcmp( keyEvent->keyname, "Escape" ) ||
+ !strcmp( keyEvent->keyname, "Return" ) ||
+ !strcmp( keyEvent->keyname, "KP_Enter" ) )
+ {
+ ecore_imf_context_reset( imfContext );
+ }
+ }
+ }
+ }
+
+ // If the event wasn't handled then we should send a key event.
+ if ( !eventHandled )
+ {
+ if ( keyEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ std::string keyName( keyEvent->keyname );
+ std::string keyString( "" );
+ int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname);
+ keyCode = (keyCode == -1) ? 0 : keyCode;
+ int modifier( keyEvent->modifiers );
+ unsigned long time = keyEvent->timestamp;
+ if (!strncmp(keyEvent->keyname, "Keycode-", 8))
+ keyCode = atoi(keyEvent->keyname + 8);
+
+ // Ensure key event string is not NULL as keys like SHIFT have a null string.
+ if ( keyEvent->string )
+ {
+ keyString = keyEvent->string;
+ }
+
+ std::string deviceName;
+ Device::Class::Type deviceClass;
+ Device::Subclass::Type deviceSubclass;
+
+ GetDeviceName( keyEvent, deviceName );
+ GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass );
+ GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass );
+
+ DALI_LOG_INFO( gImfLogging, Debug::Verbose, "EVENT EcoreEventKeyDown - >>EcoreEventKeyDown deviceName(%s) deviceClass(%d)\n", deviceName.c_str(), deviceClass );
+
+ Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Down, deviceName, deviceClass, deviceSubclass );
+ handler->SendEvent( keyEvent );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a key up is received.
+ */
+ static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyUp\n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
+ bool eventHandled( false );
+
+ // Device keys like Menu, home, back button must skip ecore_imf_context_filter_event.
+ if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
+ {
+ Ecore_IMF_Context* imfContext = NULL;
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+ }
+
+ if ( imfContext )
+ {
+ // We're consuming key up event so we have to pass to IMF so that it can parse it as well.
+ Ecore_IMF_Event_Key_Up ecoreKeyUpEvent;
+ ecoreKeyUpEvent.keyname = keyEvent->keyname;
+ ecoreKeyUpEvent.key = keyEvent->key;
+ ecoreKeyUpEvent.string = keyEvent->string;
+ ecoreKeyUpEvent.compose = keyEvent->compose;
+ ecoreKeyUpEvent.timestamp = keyEvent->timestamp;
+ ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
+ ecoreKeyUpEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
+ ecoreKeyUpEvent.dev_name = ecore_device_name_get( keyEvent->dev );
+ ecoreKeyUpEvent.dev_class = static_cast<Ecore_IMF_Device_Class>( ecore_device_class_get( keyEvent->dev ) );
+ ecoreKeyUpEvent.dev_subclass = static_cast<Ecore_IMF_Device_Subclass>( ecore_device_subclass_get( keyEvent->dev ) );
+
+ eventHandled = ecore_imf_context_filter_event( imfContext,
+ ECORE_IMF_EVENT_KEY_UP,
+ (Ecore_IMF_Event *) &ecoreKeyUpEvent );
+ }
+ }
+
+ // If the event wasn't handled then we should send a key event.
+ if ( !eventHandled )
+ {
+ if ( keyEvent->window == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ std::string keyName( keyEvent->keyname );
+ std::string keyString( "" );
+ int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname);
+ keyCode = (keyCode == -1) ? 0 : keyCode;
+ int modifier( keyEvent->modifiers );
+ unsigned long time = keyEvent->timestamp;
+ if (!strncmp(keyEvent->keyname, "Keycode-", 8))
+ keyCode = atoi(keyEvent->keyname + 8);
+
+ // Ensure key event string is not NULL as keys like SHIFT have a null string.
+ if ( keyEvent->string )
+ {
+ keyString = keyEvent->string;
+ }
+
+ std::string deviceName;
+ Device::Class::Type deviceClass;
+ Device::Subclass::Type deviceSubclass;
+
+ GetDeviceName( keyEvent, deviceName );
+ GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass );
+ GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass );
+
+ Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Up, deviceName, deviceClass, deviceSubclass );
+ handler->SendEvent( keyEvent );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Window Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when the window gains focus.
+ */
+ static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Focus_In* focusInEvent( (Ecore_Wl_Event_Focus_In*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusIn \n" );
+
+ // If the window gains focus and we hid the keyboard then show it again.
+ if ( focusInEvent->win == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventWindowFocusIn - >>WindowFocusGained \n" );
+
+ if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
+ {
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
+ if( imfManagerImpl.RestoreAfterFocusLost() )
+ {
+ imfManagerImpl.Activate();
+ }
+ }
+ }
+ Dali::Clipboard clipboard = Clipboard::Get();
+ clipboard.HideClipboard();
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window loses focus.
+ */
+ static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Focus_Out* focusOutEvent( (Ecore_Wl_Event_Focus_Out*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusOut \n" );
+
+ // If the window loses focus then hide the keyboard.
+ if ( focusOutEvent->win == (unsigned int)ecore_wl_window_id_get(handler->mImpl->mWindow) )
+ {
+ if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
+ {
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
+ if( imfManagerImpl.RestoreAfterFocusLost() )
+ {
+ imfManagerImpl.Deactivate();
+ }
+ }
+ }
+
+ // Hiding clipboard event will be ignored once because window focus out event is always received on showing clipboard
+ Dali::Clipboard clipboard = Clipboard::Get();
+ if ( clipboard )
+ {
+ Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
+ clipBoardImpl.HideClipboard(true);
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window is damaged.
+ */
+ static Eina_Bool EcoreEventWindowDamaged(void *data, int type, void *event)
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window properties are changed.
+ * We are only interested in the font change.
+ */
+
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Drag & Drop Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a dragged item enters our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndEnter( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndEnter\n" );
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved within our window.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndPosition( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndPosition\n" );
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item leaves our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndLeave( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndLeave\n" );
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the dragged item is dropped within our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndDrop( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndDrop\n" );
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved from our window and the target window has done processing it.
+ * This is when items are dragged FROM our window.
+ */
+ static Eina_Bool EcoreEventDndFinished( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndFinished\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved from our window and the target window has sent us a status.
+ * This is when items are dragged FROM our window.
+ */
+ static Eina_Bool EcoreEventDndStatus( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndStatus\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the client messages (i.e. the accessibility events) are received.
+ */
+ static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // ElDBus Accessibility Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Callback for Ecore ElDBus accessibility events.
+ static void OnEcoreElDBusAccessibilityNotification( void *context EINA_UNUSED, const Eldbus_Message *message )
+ {
+ EventHandler* handler = static_cast< EventHandler* >( context );
+ // Ignore any accessibility events when paused.
+ if( handler->mPaused )
+ {
+ return;
+ }
+
+ if( !handler->mAccessibilityAdaptor )
+ {
+ DALI_LOG_ERROR( "Invalid accessibility adaptor\n" );
+ return;
+ }
+
+ AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
+ if( !accessibilityAdaptor )
+ {
+ DALI_LOG_ERROR( "Cannot access accessibility adaptor\n" );
+ return;
+ }
+
+ int gestureValue;
+ int xS, yS, xE, yE;
+ int state; // 0 - begin, 1 - ongoing, 2 - ended, 3 - aborted
+ int eventTime;
+
+ // The string defines the arg-list's respective types.
+ if( !eldbus_message_arguments_get( message, "iiiiiiu", &gestureValue, &xS, &yS, &xE, &yE, &state, &eventTime ) )
+ {
+ DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" );
+ }
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Name: %d Args: %d,%d,%d,%d State: %d\n", gestureValue, xS, yS, xE, yE );
+
+ // Create a touch point object.
+ TouchPoint::State touchPointState( TouchPoint::Down );
+ if( state == 0 )
+ {
+ touchPointState = TouchPoint::Down; // Mouse down.
+ }
+ else if( state == 1 )
+ {
+ touchPointState = TouchPoint::Motion; // Mouse move.
+ }
+ else if( state == 2 )
+ {
+ touchPointState = TouchPoint::Up; // Mouse up.
+ }
+ else
+ {
+ touchPointState = TouchPoint::Interrupted; // Error.
+ }
+
+ // Send touch event to accessibility adaptor.
+ TouchPoint point( 0, touchPointState, (float)xS, (float)yS );
+
+ // Perform actions based on received gestures.
+ // Note: This is seperated from the reading so we can have other input readers without changing the below code.
+ switch( gestureValue )
+ {
+ case 0: // OneFingerHover
+ {
+ // Focus, read out.
+ accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
+ break;
+ }
+ case 1: // TwoFingersHover
+ {
+ // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
+ accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
+ break;
+ }
+ case 2: // ThreeFingersHover
+ {
+ // Read from top item on screen continuously.
+ accessibilityAdaptor->HandleActionReadFromTopEvent();
+ break;
+ }
+ case 3: // OneFingerFlickLeft
+ {
+ // Move to previous item.
+ accessibilityAdaptor->HandleActionReadPreviousEvent();
+ break;
+ }
+ case 4: // OneFingerFlickRight
+ {
+ // Move to next item.
+ accessibilityAdaptor->HandleActionReadNextEvent();
+ break;
+ }
+ case 5: // OneFingerFlickUp
+ {
+ // Move to previous item.
+ accessibilityAdaptor->HandleActionPreviousEvent();
+ break;
+ }
+ case 6: // OneFingerFlickDown
+ {
+ // Move to next item.
+ accessibilityAdaptor->HandleActionNextEvent();
+ break;
+ }
+ case 7: // TwoFingersFlickUp
+ {
+ // Scroll up the list.
+ accessibilityAdaptor->HandleActionScrollUpEvent();
+ break;
+ }
+ case 8: // TwoFingersFlickDown
+ {
+ // Scroll down the list.
+ accessibilityAdaptor->HandleActionScrollDownEvent();
+ break;
+ }
+ case 9: // TwoFingersFlickLeft
+ {
+ // Scroll left to the previous page
+ accessibilityAdaptor->HandleActionPageLeftEvent();
+ break;
+ }
+ case 10: // TwoFingersFlickRight
+ {
+ // Scroll right to the next page
+ accessibilityAdaptor->HandleActionPageRightEvent();
+ break;
+ }
+ case 11: // ThreeFingersFlickLeft
+ {
+ // Not exist yet
+ break;
+ }
+ case 12: // ThreeFingersFlickRight
+ {
+ // Not exist yet
+ break;
+ }
+ case 13: // ThreeFingersFlickUp
+ {
+ // Not exist yet
+ break;
+ }
+ case 14: // ThreeFingersFlickDown
+ {
+ // Not exist yet
+ break;
+ }
+ case 15: // OneFingerSingleTap
+ {
+ // Focus, read out.
+ accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
+ break;
+ }
+ case 16: // OneFingerDoubleTap
+ {
+ // Activate selected item / active edit mode.
+ accessibilityAdaptor->HandleActionActivateEvent();
+ break;
+ }
+ case 17: // OneFingerTripleTap
+ {
+ // Zoom
+ accessibilityAdaptor->HandleActionZoomEvent();
+ break;
+ }
+ case 18: // TwoFingersSingleTap
+ {
+ // Pause/Resume current speech
+ accessibilityAdaptor->HandleActionReadPauseResumeEvent();
+ break;
+ }
+ case 19: // TwoFingersDoubleTap
+ {
+ // Start/Stop current action
+ accessibilityAdaptor->HandleActionStartStopEvent();
+ break;
+ }
+ case 20: // TwoFingersTripleTap
+ {
+ // Read information from indicator
+ accessibilityAdaptor->HandleActionReadIndicatorInformationEvent();
+ break;
+ }
+ case 21: // ThreeFingersSingleTap
+ {
+ // Read from top item on screen continuously.
+ accessibilityAdaptor->HandleActionReadFromTopEvent();
+ break;
+ }
+ case 22: // ThreeFingersDoubleTap
+ {
+ // Read from next item continuously.
+ accessibilityAdaptor->HandleActionReadFromNextEvent();
+ break;
+ }
+ case 23: // ThreeFingersTripleTap
+ {
+ // Not exist yet
+ break;
+ }
+ case 24: // OneFingerFlickLeftReturn
+ {
+ // Scroll up to the previous page
+ accessibilityAdaptor->HandleActionPageUpEvent();
+ break;
+ }
+ case 25: // OneFingerFlickRightReturn
+ {
+ // Scroll down to the next page
+ accessibilityAdaptor->HandleActionPageDownEvent();
+ break;
+ }
+ case 26: // OneFingerFlickUpReturn
+ {
+ // Move to the first item on screen
+ accessibilityAdaptor->HandleActionMoveToFirstEvent();
+ break;
+ }
+ case 27: // OneFingerFlickDownReturn
+ {
+ // Move to the last item on screen
+ accessibilityAdaptor->HandleActionMoveToLastEvent();
+ break;
+ }
+ case 28: // TwoFingersFlickLeftReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 29: // TwoFingersFlickRightReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 30: // TwoFingersFlickUpReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 31: // TwoFingersFlickDownReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 32: // ThreeFingersFlickLeftReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 33: // ThreeFingersFlickRightReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 34: // ThreeFingersFlickUpReturn
+ {
+ // Not exist yet
+ break;
+ }
+ case 35: // ThreeFingersFlickDownReturn
+ {
+ // Not exist yet
+ break;
+ }
+ }
+ }
+
+ void EcoreElDBusInitialisation( void *handle )
+ {
+ Eldbus_Object *object;
+ Eldbus_Proxy *manager;
+
+ if( !( mSystemConnection = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SYSTEM) ) )
+ {
+ DALI_LOG_ERROR( "Unable to get system bus\n" );
+ }
+
+ object = eldbus_object_get( mSystemConnection, BUS, PATH );
+ if( !object )
+ {
+ DALI_LOG_ERROR( "Getting object failed\n" );
+ return;
+ }
+
+ manager = eldbus_proxy_get( object, INTERFACE );
+ if( !manager )
+ {
+ DALI_LOG_ERROR( "Getting proxy failed\n" );
+ return;
+ }
+
+ if( !eldbus_proxy_signal_handler_add( manager, "GestureDetected", OnEcoreElDBusAccessibilityNotification, handle ) )
+ {
+ DALI_LOG_ERROR( "No signal handler returned\n" );
+ }
+ }
+#endif // DALI_ELDBUS_AVAILABLE
+
+ /**
+ * Called when the source window notifies us the content in clipboard is selected.
+ */
+ static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionClear\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the source window sends us about the selected content.
+ * For example, when dragged items are dragged INTO our window or when items are selected in the clipboard.
+ */
+ static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionNotify\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the source window notifies us the content in clipboard is selected.
+ */
+ static Eina_Bool EcoreEventDataSend( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDataSend\n" );
+
+ Dali::Clipboard clipboard = Clipboard::Get();
+ if ( clipboard )
+ {
+ Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
+ clipBoardImpl.ExcuteBuffered( true, event );
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the source window sends us about the selected content.
+ * For example, when item is selected in the clipboard.
+ */
+ static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDataReceive\n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Dali::Clipboard clipboard = Clipboard::Get();
+ char *selectionData = NULL;
+ if ( clipboard )
+ {
+ Clipboard& clipBoardImpl( GetImplementation( clipboard ) );
+ selectionData = clipBoardImpl.ExcuteBuffered( false, event );
+ }
+ if ( selectionData && handler->mClipboardEventNotifier )
+ {
+ ClipboardEventNotifier& clipboardEventNotifier( ClipboardEventNotifier::GetImplementation( handler->mClipboardEventNotifier ) );
+ std::string content( selectionData, strlen(selectionData) );
+
+ clipboardEventNotifier.SetContent( content );
+ clipboardEventNotifier.EmitContentSelectedSignal();
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /*
+ * Called when rotate event is recevied
+ */
+ static Eina_Bool EcoreEventRotate( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::Concise, "EcoreEventRotate\n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Wl_Event_Window_Rotate* ev( (Ecore_Wl_Event_Window_Rotate*)event );
+
+ if( ev->win != (unsigned int)ecore_wl_window_id_get( handler->mImpl->mWindow ) )
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ RotationEvent rotationEvent;
+ rotationEvent.angle = ev->angle;
+ rotationEvent.winResize = 0;
+
+ if( ev->angle == 0 || ev->angle == 180 )
+ {
+ rotationEvent.width = ev->w;
+ rotationEvent.height = ev->h;
+ }
+ else
+ {
+ rotationEvent.width = ev->h;
+ rotationEvent.height = ev->w;
+ }
+
+ handler->SendRotationPrepareEvent( rotationEvent );
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /*
+ * Called when detent event is recevied
+ */
+ static Eina_Bool EcoreEventDetent( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventDetent\n" );
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Event_Detent_Rotate *e((Ecore_Event_Detent_Rotate *)event);
+ int direction = (e->direction == ECORE_DETENT_DIRECTION_CLOCKWISE) ? 1 : -1;
+ int timeStamp = e->timestamp;
+
+ WheelEvent wheelEvent( WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2(0.0f, 0.0f), direction, timeStamp );
+ handler->SendWheelEvent( wheelEvent );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Font Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Called when a font name is changed.
+ */
+ static void VconfNotifyFontNameChanged( keynode_t* node, void* data )
+ {
+ EventHandler* handler = static_cast<EventHandler*>( data );
+ handler->SendEvent( StyleChange::DEFAULT_FONT_CHANGE );
+ }
+
+ /**
+ * Called when a font size is changed.
+ */
+ static void VconfNotifyFontSizeChanged( keynode_t* node, void* data )
+ {
+ EventHandler* handler = static_cast<EventHandler*>( data );
+ handler->SendEvent( StyleChange::DEFAULT_FONT_SIZE_CHANGE );
+ }
+
+ void ConvertTouchPosition( Integration::Point& point )
+ {
+ Vector2 position = point.GetScreenPosition();
+ Vector2 convertedPosition;
+
+ switch( mRotationAngle )
+ {
+ case 90:
+ {
+ convertedPosition.x = mWindowWidth - position.y;
+ convertedPosition.y = position.x;
+ break;
+ }
+ case 180:
+ {
+ convertedPosition.x = mWindowWidth - position.x;
+ convertedPosition.y = mWindowHeight - position.y;
+ break;
+ }
+ case 270:
+ {
+ convertedPosition.x = position.y;
+ convertedPosition.y = mWindowHeight - position.x;
+ break;
+ }
+ default:
+ {
+ convertedPosition = position;
+ break;
+ }
+ }
+
+ point.SetScreenPosition( convertedPosition );
+ }
+
+ // Data
+ EventHandler* mHandler;
+ std::vector<Ecore_Event_Handler*> mEcoreEventHandler;
+ Ecore_Wl_Window* mWindow;
+ int mRotationAngle;
+ int mWindowWidth;
+ int mWindowHeight;
+#ifdef DALI_ELDBUS_AVAILABLE
+ Eldbus_Connection* mSystemConnection;
+#endif // DALI_ELDBUS_AVAILABLE
+};
+
+EventHandler::EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector )
+: mCoreEventInterface( coreEventInterface ),
+ mGestureManager( gestureManager ),
+ mStyleMonitor( StyleMonitor::Get() ),
+ mDamageObserver( damageObserver ),
+ mRotationObserver( NULL ),
+ mDragAndDropDetector( dndDetector ),
+ mAccessibilityAdaptor( AccessibilityAdaptor::Get() ),
+ mClipboardEventNotifier( ClipboardEventNotifier::Get() ),
+ mClipboard( Clipboard::Get() ),
+ mImpl( NULL ),
+ mPaused( false )
+{
+ Ecore_Wl_Window* window = 0;
+
+ // this code only works with the Ecore RenderSurface so need to downcast
+ ECore::WindowRenderSurface* ecoreSurface = dynamic_cast< ECore::WindowRenderSurface* >( surface );
+ if( ecoreSurface )
+ {
+ window = ecoreSurface->GetWlWindow();
+ }
+
+ mImpl = new Impl(this, window);
+}
+
+EventHandler::~EventHandler()
+{
+ if(mImpl)
+ {
+ delete mImpl;
+ }
+
+ mGestureManager.Stop();
+}
+
+void EventHandler::SendEvent(Integration::Point& point, unsigned long timeStamp)
+{
+ if(timeStamp < 1)
+ {
+ timeStamp = GetCurrentMilliSeconds();
+ }
+
+ mImpl->ConvertTouchPosition( point );
+
+ Integration::TouchEvent touchEvent;
+ Integration::HoverEvent hoverEvent;
+ Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent(point, timeStamp, touchEvent, hoverEvent);
+ if(type != Integration::TouchEventCombiner::DispatchNone )
+ {
+ DALI_LOG_INFO(gTouchEventLogFilter, Debug::General, "%d: Device %d: Button state %d (%.2f, %.2f)\n", timeStamp, point.GetDeviceId(), point.GetState(), point.GetScreenPosition().x, point.GetScreenPosition().y);
+
+ // First the touch and/or hover event & related gesture events are queued
+ if(type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth)
+ {
+ mCoreEventInterface.QueueCoreEvent( touchEvent );
+ mGestureManager.SendEvent(touchEvent);
+ }
+
+ if(type == Integration::TouchEventCombiner::DispatchHover || type == Integration::TouchEventCombiner::DispatchBoth)
+ {
+ mCoreEventInterface.QueueCoreEvent( hoverEvent );
+ }
+
+ // Next the events are processed with a single call into Core
+ mCoreEventInterface.ProcessCoreEvents();
+ }
+}
+
+void EventHandler::SendEvent(Integration::KeyEvent& keyEvent)
+{
+ Dali::PhysicalKeyboard physicalKeyboard = PhysicalKeyboard::Get();
+ if ( physicalKeyboard )
+ {
+ if ( ! KeyLookup::IsDeviceButton( keyEvent.keyName.c_str() ) )
+ {
+ GetImplementation( physicalKeyboard ).KeyReceived( keyEvent.time > 1 );
+ }
+ }
+
+ // Create send KeyEvent to Core.
+ mCoreEventInterface.QueueCoreEvent( keyEvent );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::SendWheelEvent( WheelEvent& wheelEvent )
+{
+ // Create WheelEvent and send to Core.
+ Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >(wheelEvent.type), wheelEvent.direction, wheelEvent.modifiers, wheelEvent.point, wheelEvent.z, wheelEvent.timeStamp );
+ mCoreEventInterface.QueueCoreEvent( event );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::SendEvent( StyleChange::Type styleChange )
+{
+ DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" );
+ GetImplementation( mStyleMonitor ).StyleChanged(styleChange);
+}
+
+void EventHandler::SendEvent( const DamageArea& area )
+{
+ mDamageObserver.OnDamaged( area );
+}
+
+void EventHandler::SendRotationPrepareEvent( const RotationEvent& event )
+{
+ if( mRotationObserver != NULL )
+ {
+ mImpl->mRotationAngle = event.angle;
+ mImpl->mWindowWidth = event.width;
+ mImpl->mWindowHeight = event.height;
+
+ mRotationObserver->OnRotationPrepare( event );
+ mRotationObserver->OnRotationRequest();
+ }
+}
+
+void EventHandler::SendRotationRequestEvent( )
+{
+ // No need to separate event into prepare and request in wayland
+}
+
+void EventHandler::FeedTouchPoint( TouchPoint& point, int timeStamp)
+{
+ Integration::Point convertedPoint( point );
+ SendEvent(convertedPoint, timeStamp);
+}
+
+void EventHandler::FeedWheelEvent( WheelEvent& wheelEvent )
+{
+ SendWheelEvent( wheelEvent );
+}
+
+void EventHandler::FeedKeyEvent( KeyEvent& event )
+{
+ Integration::KeyEvent convertedEvent( event );
+ SendEvent( convertedEvent );
+}
+
+void EventHandler::FeedEvent( Integration::Event& event )
+{
+ mCoreEventInterface.QueueCoreEvent( event );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::Reset()
+{
+ mCombiner.Reset();
+
+ // Any touch listeners should be told of the interruption.
+ Integration::TouchEvent event;
+ Integration::Point point;
+ point.SetState( PointState::INTERRUPTED );
+ event.AddPoint( point );
+
+ // First the touch event & related gesture events are queued
+ mCoreEventInterface.QueueCoreEvent( event );
+ mGestureManager.SendEvent( event );
+
+ // Next the events are processed with a single call into Core
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::Pause()
+{
+ mPaused = true;
+ Reset();
+}
+
+void EventHandler::Resume()
+{
+ mPaused = false;
+ Reset();
+}
+
+void EventHandler::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
+{
+ mDragAndDropDetector = detector;
+}
+
+void EventHandler::SetRotationObserver( RotationObserver* observer )
+{
+ mRotationObserver = observer;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/wayland/pixmap-render-surface.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/wl-types.h>
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/window-system/common/display-connection.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gRenderSurfaceLogFilter;
+#endif
+
+namespace ECore
+{
+
+PixmapRenderSurface::PixmapRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+: EcoreWlRenderSurface( positionSize, surface, name, isTransparent )
+{
+ Init( surface );
+}
+
+PixmapRenderSurface::~PixmapRenderSurface()
+{
+ // release the surface if we own one
+ if( mOwnSurface )
+ {
+ //TODO: if we did create the pixmap, delete the pixmap
+ }
+}
+
+Ecore_Wl_Window* PixmapRenderSurface::GetDrawable()
+{
+ return NULL;
+}
+
+Any PixmapRenderSurface::GetSurface()
+{
+ return Any( NULL );
+}
+
+void PixmapRenderSurface::InitializeEgl( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ eglImpl.ChooseConfig(false, mColorDepth);
+}
+
+void PixmapRenderSurface::CreateEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ // create the EGL surface
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ // FIXME
+}
+
+void PixmapRenderSurface::DestroyEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ eglImpl.DestroySurface();
+}
+
+bool PixmapRenderSurface::ReplaceEGLSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ // a new surface for the new pixmap
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ // FIXME
+ return false;
+}
+
+void PixmapRenderSurface::StartRender()
+{
+ // FIXME
+}
+
+bool PixmapRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
+{
+ // nothing to do for pixmaps
+ return true;
+}
+
+void PixmapRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
+{
+ // flush gl instruction queue
+ glAbstraction.Flush();
+
+ // create damage for client applications which wish to know the update timing
+ if( mRenderNotification )
+ {
+ // use notification trigger
+ // Tell the event-thread to render the pixmap
+ mRenderNotification->Trigger();
+ }
+ else
+ {
+ // FIXME
+ }
+
+ // Do render synchronisation
+ // AcquireLock( replacingSurface ? SYNC_MODE_NONE : SYNC_MODE_WAIT );
+}
+
+void PixmapRenderSurface::StopRender()
+{
+ // FIXME
+}
+
+void PixmapRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
+{
+ // Nothing to do
+}
+
+void PixmapRenderSurface::CreateWlRenderable()
+{
+ // check we're creating one with a valid size
+ DALI_ASSERT_ALWAYS( mPositionSize.width > 0 && mPositionSize.height > 0 && "Pixmap size is invalid" );
+
+ // FIXME
+}
+
+void PixmapRenderSurface::UseExistingRenderable( unsigned int surfaceId )
+{
+ // FIXME
+}
+
+void PixmapRenderSurface::SetSyncMode( SyncMode syncMode )
+{
+ // FIXME
+}
+
+void PixmapRenderSurface::AcquireLock()
+{
+ // FIXME
+}
+
+void PixmapRenderSurface::ReleaseLock()
+{
+ // FIXME
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/wayland/ecore-wl-render-surface.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/wl-types.h>
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_ECORE_WL_RENDER_SURFACE");
+#endif
+
+namespace ECore
+{
+
+EcoreWlRenderSurface::EcoreWlRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+: mPositionSize( positionSize ),
+ mTitle( name ),
+ mRenderNotification( NULL ),
+ mColorDepth( isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24 ),
+ mOwnSurface( false )
+{
+}
+
+void EcoreWlRenderSurface::Init( Any surface )
+{
+ // see if there is a surface in Any surface
+ unsigned int surfaceId = GetSurfaceId( surface );
+
+ // if the surface is empty, create a new one.
+ if ( surfaceId == 0 )
+ {
+ // we own the surface about to created
+ ecore_wl_init(NULL);
+ mOwnSurface = true;
+ CreateWlRenderable();
+ }
+ else
+ {
+ // XLib should already be initialized so no point in calling XInitThreads
+ UseExistingRenderable( surfaceId );
+ }
+
+#ifdef DEBUG_ENABLED
+ // prints out 'INFO: DALI: new EcoreWlRenderSurface, created display xx, used existing surface xx
+ // we can not use LOG_INFO because the surface can be created before Dali Core is created.
+ // TODO: Overy tizen 3.0, we don't use X anymore. Change this for Tizen 3.0
+ /*
+ printf( "INFO: DALI: new EcoreWlRenderSurface, %s %s surface %X \n",
+ mOwnSurface?"created":"used existing",
+ Dali::RenderSurface::PIXMAP==mType?" pixmap" :"window",
+ AnyCast<Ecore_X_Drawable>( GetSurface() ) );
+ */
+#endif
+}
+
+EcoreWlRenderSurface::~EcoreWlRenderSurface()
+{
+ if( mOwnSurface )
+ {
+ ecore_wl_shutdown();
+ }
+}
+
+void EcoreWlRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification)
+{
+ mRenderNotification = renderNotification;
+}
+
+Ecore_Wl_Window* EcoreWlRenderSurface::GetWlWindow()
+{
+ return 0;
+}
+
+Ecore_Wl_Window* EcoreWlRenderSurface::GetDrawable()
+{
+ return 0;
+}
+
+PositionSize EcoreWlRenderSurface::GetPositionSize() const
+{
+ return mPositionSize;
+}
+
+void EcoreWlRenderSurface::MoveResize( Dali::PositionSize positionSize )
+{
+ // nothing to do in base class
+}
+
+void EcoreWlRenderSurface::SetViewMode( ViewMode viewMode )
+{
+}
+
+unsigned int EcoreWlRenderSurface::GetSurfaceId( Any surface ) const
+{
+ unsigned int surfaceId = 0;
+
+ if ( surface.Empty() == false )
+ {
+ // check we have a valid type
+ DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (Ecore_Wl_Window *) ) )
+ && "Surface type is invalid" );
+
+ surfaceId = AnyCast<unsigned int>( surface );
+ }
+ return surfaceId;
+}
+
+RenderSurface::Type EcoreWlRenderSurface::GetSurfaceType()
+{
+ return RenderSurface::ECORE_RENDER_SURFACE;
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/window-impl.h>
+
+// EXTERNAL HEADERS
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Ecore_Wayland.h>
+#include <tizen-extension-client-protocol.h>
+
+#include <dali/integration-api/core.h>
+#include <dali/integration-api/system-overlay.h>
+#include <dali/public-api/render-tasks/render-task.h>
+#include <dali/public-api/render-tasks/render-task-list.h>
+#include <dali/devel-api/adaptor-framework/orientation.h>
+
+// INTERNAL HEADERS
+#include <dali/internal/window-system/tizen-wayland/window-render-surface-ecore-wl.h>
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+#include <dali/internal/window-system/common/ecore-indicator-impl.h>
+#include <dali/internal/window-system/common/window-visibility-observer.h>
+#include <dali/internal/window-system/common/orientation-impl.h>
+
+namespace
+{
+
+const float INDICATOR_ANIMATION_DURATION( 0.18f ); // 180 milli seconds
+const float INDICATOR_SHOW_Y_POSITION( 0.0f );
+const float INDICATOR_HIDE_Y_POSITION( -52.0f );
+
+const uint32_t MAX_TIZEN_CLIENT_VERSION = 7;
+
+}
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW");
+#endif
+
+/**
+ * TODO: Abstract Window class out and move this into a window implementation for Ecore
+ */
+struct Window::EventHandler
+{
+ /**
+ * Constructor
+ * @param[in] window A pointer to the window class.
+ */
+ EventHandler( Window* window )
+ : mWindow( window ),
+ mEcoreEventHandler(),
+ mEcoreWindow( 0 ),
+ mDisplay( NULL ),
+ mEventQueue( NULL ),
+ mTizenPolicy( NULL ),
+ mTizenDisplayPolicy( NULL ),
+ mNotificationLevel( -1 ),
+ mNotificationChangeState( 0 ),
+ mNotificationLevelChangeDone( true ),
+ mScreenOffMode( 0 ),
+ mScreenOffModeChangeState( 0 ),
+ mScreenOffModeChangeDone( true ),
+ mBrightness( 0 ),
+ mBrightnessChangeState( 0 ),
+ mBrightnessChangeDone( true )
+ {
+ // store ecore window handle
+ ECore::WindowRenderSurface* wlWindow( dynamic_cast< ECore::WindowRenderSurface * >( mWindow->mSurface ) );
+ if( wlWindow )
+ {
+ mEcoreWindow = wlWindow->GetWlWindow();
+ }
+ DALI_ASSERT_ALWAYS( mEcoreWindow != 0 && "There is no ecore Wl window");
+
+ if( mWindow->mEcoreEventHander )
+ {
+ mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this ) );
+ mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this ) );
+ mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this ) );
+ mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this) );
+ mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this) );
+ }
+
+ mDisplay = ecore_wl_display_get();
+
+ if( mDisplay )
+ {
+ wl_display* displayWrapper = static_cast< wl_display* >( wl_proxy_create_wrapper( mDisplay ) );
+ if( displayWrapper )
+ {
+ mEventQueue = wl_display_create_queue( mDisplay );
+ if( mEventQueue )
+ {
+ wl_proxy_set_queue( reinterpret_cast< wl_proxy* >( displayWrapper ), mEventQueue );
+
+ wl_registry* registry = wl_display_get_registry( displayWrapper );
+ wl_registry_add_listener( registry, &mRegistryListener, this );
+ }
+
+ wl_proxy_wrapper_destroy( displayWrapper );
+ }
+ }
+ }
+
+ /**
+ * Destructor
+ */
+ ~EventHandler()
+ {
+ for( Dali::Vector< Ecore_Event_Handler* >::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter )
+ {
+ ecore_event_handler_del( *iter );
+ }
+ mEcoreEventHandler.Clear();
+
+ if( mEventQueue )
+ {
+ wl_event_queue_destroy( mEventQueue );
+ }
+ }
+
+ // Static methods
+
+ /// Called when the window iconify state is changed.
+ static Eina_Bool EcoreEventWindowIconifyStateChanged( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Window_Iconify_State_Change* iconifyChangedEvent( static_cast< Ecore_Wl_Event_Window_Iconify_State_Change* >( event ) );
+ EventHandler* handler( static_cast< EventHandler* >( data ) );
+ Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
+
+ if ( handler && handler->mWindow )
+ {
+ WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
+ if ( observer && ( iconifyChangedEvent->win == static_cast< unsigned int> ( ecore_wl_window_id_get( handler->mEcoreWindow ) ) ) )
+ {
+ if( iconifyChangedEvent->iconified == EINA_TRUE )
+ {
+ handler->mWindow->mIconified = true;
+ if( handler->mWindow->mVisible )
+ {
+ observer->OnWindowHidden();
+ }
+ DALI_LOG_RELEASE_INFO( "Window (%p) Iconified\n", handler->mEcoreWindow);
+ }
+ else
+ {
+ handler->mWindow->mIconified = false;
+ if( handler->mWindow->mVisible )
+ {
+ observer->OnWindowShown();
+ }
+ DALI_LOG_RELEASE_INFO( "Window (%p) Deiconified\n", handler->mEcoreWindow );
+ }
+ handled = ECORE_CALLBACK_DONE;
+ }
+ }
+
+ return handled;
+ }
+
+ /// Called when the window gains focus
+ static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Focus_In* focusInEvent( static_cast< Ecore_Wl_Event_Focus_In* >( event ) );
+ EventHandler* handler( static_cast< EventHandler* >( data ) );
+
+ if ( handler && handler->mWindow && focusInEvent->win == static_cast< unsigned int >( ecore_wl_window_id_get( handler->mEcoreWindow ) ) )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n" );
+
+ handler->mWindow->mFocusChangedSignal.Emit( true );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /// Called when the window loses focus
+ static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Focus_Out* focusOutEvent( static_cast< Ecore_Wl_Event_Focus_Out* >( event ) );
+ EventHandler* handler( static_cast< EventHandler* >( data ) );
+
+ if ( handler && handler->mWindow && focusOutEvent->win == static_cast< unsigned int >(ecore_wl_window_id_get( handler->mEcoreWindow ) ) )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n" );
+
+ handler->mWindow->mFocusChangedSignal.Emit( false );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /// Called when the output is transformed
+ static Eina_Bool EcoreEventOutputTransform( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Output_Transform* transformEvent( static_cast< Ecore_Wl_Event_Output_Transform* >( event ) );
+ EventHandler* handler( static_cast< EventHandler* >( data ) );
+
+ if ( handler && handler->mWindow && transformEvent->output == ecore_wl_window_output_find( handler->mEcoreWindow ) )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", handler->mEcoreWindow );
+
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
+ if( wlSurface )
+ {
+ wlSurface->OutputTransformed();
+
+ PositionSize positionSize = wlSurface->GetPositionSize();
+ handler->mWindow->mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ handler->mWindow->mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /// Called when the output transform should be ignored
+ static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* event )
+ {
+ Ecore_Wl_Event_Ignore_Output_Transform* ignoreTransformEvent( static_cast< Ecore_Wl_Event_Ignore_Output_Transform* >( event ) );
+ EventHandler* handler( static_cast< EventHandler* >( data ) );
+
+ if ( handler && handler->mWindow && ignoreTransformEvent->win == handler->mEcoreWindow )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", handler->mEcoreWindow );
+
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
+ if( wlSurface )
+ {
+ wlSurface->OutputTransformed();
+
+ PositionSize positionSize = wlSurface->GetPositionSize();
+ handler->mWindow->mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ handler->mWindow->mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ static void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version )
+ {
+ Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
+
+ if( strcmp( interface, tizen_policy_interface.name ) == 0 )
+ {
+ uint32_t clientVersion = std::min( version, MAX_TIZEN_CLIENT_VERSION );
+
+ eventHandler->mTizenPolicy = static_cast< tizen_policy* >( wl_registry_bind( registry, name, &tizen_policy_interface, clientVersion ) );
+ if( !eventHandler->mTizenPolicy )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n" );
+ return;
+ }
+
+ tizen_policy_add_listener( eventHandler->mTizenPolicy, &eventHandler->mTizenPolicyListener, data );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: tizen_policy_add_listener is called.\n" );
+ }
+ else if( strcmp( interface, tizen_display_policy_interface.name ) == 0 )
+ {
+ eventHandler->mTizenDisplayPolicy = static_cast< tizen_display_policy* >( wl_registry_bind( registry, name, &tizen_display_policy_interface, version ) );
+ if( !eventHandler->mTizenDisplayPolicy )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n" );
+ return;
+ }
+
+ tizen_display_policy_add_listener( eventHandler->mTizenDisplayPolicy, &eventHandler->mTizenDisplayPolicyListener, data );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n" );
+ }
+ }
+
+ static void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id )
+ {
+ Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
+ eventHandler->mTizenPolicy = NULL;
+ eventHandler->mTizenDisplayPolicy = NULL;
+ }
+
+ static void TizenPolicyConformant( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant )
+ {
+ }
+
+ static void TizenPolicyConformantArea( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h )
+ {
+ }
+
+ static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state )
+ {
+ Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
+
+ eventHandler->mNotificationLevel = level;
+ eventHandler->mNotificationChangeState = state;
+ eventHandler->mNotificationLevelChangeDone = true;
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state );
+ }
+
+ static void TizenPolicyTransientForDone( void* data, struct tizen_policy* tizenPolicy, uint32_t childId )
+ {
+ }
+
+ static void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state )
+ {
+ Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
+
+ eventHandler->mScreenOffMode = mode;
+ eventHandler->mScreenOffModeChangeState = state;
+ eventHandler->mScreenOffModeChangeDone = true;
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state );
+ }
+
+ static void TizenPolicyIconifyStateChanged( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force )
+ {
+ }
+
+ static void TizenPolicySupportedAuxiliaryHints( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints )
+ {
+ }
+
+ static void TizenPolicyAllowedAuxiliaryHint( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id )
+ {
+ }
+
+ static void TizenPolicyAuxiliaryMessage( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options )
+ {
+ }
+
+ static void TizenPolicyConformantRegion( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial )
+ {
+ }
+
+ static void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state )
+ {
+ Window::EventHandler* eventHandler = static_cast< Window::EventHandler* >( data );
+
+ eventHandler->mBrightness = brightness;
+ eventHandler->mBrightnessChangeState = state;
+ eventHandler->mBrightnessChangeDone = true;
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window::EventHandler::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state );
+ }
+
+ const struct wl_registry_listener mRegistryListener =
+ {
+ RegistryGlobalCallback,
+ RegistryGlobalCallbackRemove
+ };
+
+ const struct tizen_policy_listener mTizenPolicyListener =
+ {
+ TizenPolicyConformant,
+ TizenPolicyConformantArea,
+ TizenPolicyNotificationChangeDone,
+ TizenPolicyTransientForDone,
+ TizenPolicyScreenModeChangeDone,
+ TizenPolicyIconifyStateChanged,
+ TizenPolicySupportedAuxiliaryHints,
+ TizenPolicyAllowedAuxiliaryHint,
+ TizenPolicyAuxiliaryMessage,
+ TizenPolicyConformantRegion
+ };
+
+ const struct tizen_display_policy_listener mTizenDisplayPolicyListener =
+ {
+ DisplayPolicyBrightnessChangeDone
+ };
+
+ // Data
+ Window* mWindow;
+ Dali::Vector< Ecore_Event_Handler* > mEcoreEventHandler;
+ Ecore_Wl_Window* mEcoreWindow;
+
+ wl_display* mDisplay;
+ wl_event_queue* mEventQueue;
+ tizen_policy* mTizenPolicy;
+ tizen_display_policy* mTizenDisplayPolicy;
+
+ int mNotificationLevel;
+ uint32_t mNotificationChangeState;
+ bool mNotificationLevelChangeDone;
+
+ int mScreenOffMode;
+ uint32_t mScreenOffModeChangeState;
+ bool mScreenOffModeChangeDone;
+
+ int mBrightness;
+ uint32_t mBrightnessChangeState;
+ bool mBrightnessChangeDone;
+};
+
+Window* Window::New( const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent )
+{
+ Window* window = new Window();
+ window->mIsTransparent = isTransparent;
+ window->Initialize( positionSize, name, className );
+ return window;
+}
+
+void Window::SetAdaptor(Dali::Adaptor& adaptor)
+{
+ DALI_ASSERT_ALWAYS( !mStarted && "Adaptor already started" );
+ mStarted = true;
+
+ // Only create one overlay per window
+ Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor);
+ Integration::Core& core = adaptorImpl.GetCore();
+ mOverlay = &core.GetSystemOverlay();
+
+ Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
+ taskList.CreateTask();
+
+ mAdaptor = &adaptorImpl;
+ mAdaptor->AddObserver( *this );
+
+ // Can only create the detector when we know the Core has been instantiated.
+ mDragAndDropDetector = DragAndDropDetector::New();
+ mAdaptor->SetDragAndDropDetector( &GetImplementation( mDragAndDropDetector ) );
+
+ if( mOrientation )
+ {
+ mOrientation->SetAdaptor(adaptor);
+ }
+
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetAdaptor(mAdaptor);
+ }
+}
+
+RenderSurface* Window::GetSurface()
+{
+ return mSurface;
+}
+
+void Window::ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode )
+{
+ DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "visible : %d\n", visibleMode );
+ DALI_ASSERT_DEBUG(mOverlay);
+
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+ DALI_ASSERT_DEBUG(wlSurface);
+
+ if( wlSurface )
+ {
+ Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
+
+ mIndicatorVisible = visibleMode;
+
+ if ( mIndicatorVisible == Dali::Window::VISIBLE )
+ {
+ // when the indicator is visible, set proper mode for indicator server according to bg mode
+ if ( mIndicatorOpacityMode == Dali::Window::OPAQUE )
+ {
+ ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_OPAQUE);
+ }
+ else if ( mIndicatorOpacityMode == Dali::Window::TRANSLUCENT )
+ {
+ ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_TRANSLUCENT);
+ }
+ else if ( mIndicatorOpacityMode == Dali::Window::TRANSPARENT )
+ {
+ ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_OPAQUE);
+ }
+ }
+ else
+ {
+ // when the indicator is not visible, set TRANSPARENT mode for indicator server
+ ecore_wl_window_indicator_opacity_set(wlWindow, ECORE_WL_INDICATOR_TRANSPARENT); // it means hidden indicator
+ }
+ }
+
+ DoShowIndicator( mIndicatorOrientation );
+}
+
+void Window::RotateIndicator( Dali::Window::WindowOrientation orientation )
+{
+ DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "Orientation: %d\n", orientation );
+
+ DoRotateIndicator( orientation );
+}
+
+void Window::SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacityMode )
+{
+ mIndicatorOpacityMode = opacityMode;
+
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetOpacityMode( opacityMode );
+ }
+}
+
+void Window::SetClass(std::string name, std::string klass)
+{
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+
+ if( wlSurface )
+ {
+ Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
+ ecore_wl_window_title_set( wlWindow, name.c_str() );
+ ecore_wl_window_class_name_set( wlWindow, klass.c_str() );
+ }
+ else
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window has no surface\n" );
+ }
+}
+
+Window::Window()
+: mSurface( NULL ),
+ mIndicatorVisible( Dali::Window::VISIBLE ),
+ mIndicatorIsShown( false ),
+ mShowRotatedIndicatorOnClose( false ),
+ mStarted( false ),
+ mIsTransparent( false ),
+ mWMRotationAppSet( false ),
+ mEcoreEventHander( true ),
+ mIsFocusAcceptable( true ),
+ mVisible( true ),
+ mIconified( false ),
+ mOpaqueState( false ),
+ mResizeEnabled( false ),
+ mIndicator( NULL ),
+ mIndicatorOrientation( Dali::Window::PORTRAIT ),
+ mNextIndicatorOrientation( Dali::Window::PORTRAIT ),
+ mIndicatorOpacityMode( Dali::Window::OPAQUE ),
+ mOverlay( NULL ),
+ mAdaptor( NULL ),
+ mType( Dali::Window::NORMAL ),
+ mEventHandler( NULL ),
+ mPreferredOrientation( Dali::Window::PORTRAIT ),
+ mSupportedAuxiliaryHints(),
+ mAuxiliaryHints(),
+ mIndicatorVisibilityChangedSignal(),
+ mFocusChangedSignal(),
+ mResizedSignal(),
+ mDeleteRequestSignal()
+{
+}
+
+Window::~Window()
+{
+ delete mEventHandler;
+
+ if( mIndicator )
+ {
+ mIndicator->Close();
+ delete mIndicator;
+ }
+
+ if ( mAdaptor )
+ {
+ mAdaptor->RemoveObserver( *this );
+ mAdaptor->SetDragAndDropDetector( NULL );
+ mAdaptor = NULL;
+ }
+
+ delete mSurface;
+
+ mSupportedAuxiliaryHints.clear();
+ mAuxiliaryHints.clear();
+}
+
+void Window::Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className)
+{
+ // create an Wayland window by default
+ Any surface;
+ ECore::WindowRenderSurface* windowSurface = new ECore::WindowRenderSurface( positionSize, surface, name, mIsTransparent );
+
+ mSurface = windowSurface;
+
+ // create event handler for Wayland window
+ mEventHandler = new EventHandler( this );
+
+ // get auxiliary hint
+ Eina_List* hints = ecore_wl_window_aux_hints_supported_get( mEventHandler->mEcoreWindow );
+ if( hints )
+ {
+ Eina_List* l = NULL;
+ char* hint = NULL;
+
+ for( l = hints, ( hint = static_cast< char* >( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( hint = static_cast< char* >( eina_list_data_get(l) ) ) )
+ {
+ mSupportedAuxiliaryHints.push_back( hint );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::Initialize: %s\n", hint );
+ }
+ }
+
+ if( !positionSize.IsEmpty() )
+ {
+ AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
+ mResizeEnabled = true;
+ }
+
+ SetClass( name, className );
+ windowSurface->Map();
+
+ mOrientation = Orientation::New(this);
+}
+
+void Window::DoShowIndicator( Dali::Window::WindowOrientation lastOrientation )
+{
+ if( mIndicator == NULL )
+ {
+ if( mIndicatorVisible != Dali::Window::INVISIBLE )
+ {
+ mIndicator = new Indicator( mAdaptor, mIndicatorOrientation, this );
+ mIndicator->SetOpacityMode( mIndicatorOpacityMode );
+ Dali::Actor actor = mIndicator->GetActor();
+ SetIndicatorActorRotation();
+ mOverlay->Add(actor);
+ }
+ // else don't create a hidden indicator
+ }
+ else // Already have indicator
+ {
+ if( mIndicatorVisible == Dali::Window::VISIBLE )
+ {
+ // If we are resuming, and rotation has changed,
+ if( mIndicatorIsShown == false && mIndicatorOrientation != mNextIndicatorOrientation )
+ {
+ // then close current indicator and open new one
+ mShowRotatedIndicatorOnClose = true;
+ mIndicator->Close(); // May synchronously call IndicatorClosed() callback & 1 level of recursion
+ // Don't show actor - will contain indicator for old orientation.
+ }
+ }
+ }
+
+ // set indicator visible mode
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetVisible( mIndicatorVisible );
+ }
+
+ bool show = (mIndicatorVisible != Dali::Window::INVISIBLE );
+ SetIndicatorProperties( show, lastOrientation );
+ mIndicatorIsShown = show;
+}
+
+void Window::DoRotateIndicator( Dali::Window::WindowOrientation orientation )
+{
+ if( mIndicatorIsShown )
+ {
+ mShowRotatedIndicatorOnClose = true;
+ mNextIndicatorOrientation = orientation;
+ mIndicator->Close(); // May synchronously call IndicatorClosed() callback
+ }
+ else
+ {
+ // Save orientation for when the indicator is next shown
+ mShowRotatedIndicatorOnClose = false;
+ mNextIndicatorOrientation = orientation;
+ }
+}
+
+void Window::SetIndicatorProperties( bool isShow, Dali::Window::WindowOrientation lastOrientation )
+{
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+
+ if( wlSurface )
+ {
+ Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
+ if ( isShow )
+ {
+ ecore_wl_window_indicator_state_set(wlWindow, ECORE_WL_INDICATOR_STATE_ON);
+ }
+ else
+ {
+ ecore_wl_window_indicator_state_set(wlWindow, ECORE_WL_INDICATOR_STATE_OFF);
+ }
+ }
+}
+
+void Window::IndicatorTypeChanged(Indicator::Type type)
+{
+#if defined(DALI_PROFILE_MOBILE)
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+
+ if( wlSurface )
+ {
+ Ecore_Wl_Window* wlWindow = wlSurface->GetWlWindow();
+ switch(type)
+ {
+ case Indicator::INDICATOR_TYPE_1:
+ ecore_wl_indicator_visible_type_set(wlWindow, ECORE_WL_INDICATOR_VISIBLE_TYPE_SHOWN);
+ break;
+
+ case Indicator::INDICATOR_TYPE_2:
+ ecore_wl_indicator_visible_type_set(wlWindow, ECORE_WL_INDICATOR_VISIBLE_TYPE_HIDDEN);
+ break;
+
+ case Indicator::INDICATOR_TYPE_UNKNOWN:
+ default:
+ break;
+ }
+ }
+#endif //MOBILE
+}
+
+void Window::IndicatorClosed( IndicatorInterface* indicator )
+{
+ DALI_LOG_TRACE_METHOD( gWindowLogFilter );
+
+ if( mShowRotatedIndicatorOnClose )
+ {
+ Dali::Window::WindowOrientation currentOrientation = mIndicatorOrientation;
+ mIndicator->Open(mNextIndicatorOrientation);
+ mIndicatorOrientation = mNextIndicatorOrientation;
+ SetIndicatorActorRotation();
+ DoShowIndicator(currentOrientation);
+ }
+}
+
+void Window::IndicatorVisibilityChanged(bool isVisible)
+{
+ mIndicatorVisibilityChangedSignal.Emit(isVisible);
+}
+
+void Window::SetIndicatorActorRotation()
+{
+ DALI_LOG_TRACE_METHOD( gWindowLogFilter );
+ DALI_ASSERT_DEBUG( mIndicator != NULL );
+
+ Dali::Actor actor = mIndicator->GetActor();
+ switch( mIndicatorOrientation )
+ {
+ case Dali::Window::PORTRAIT:
+ actor.SetParentOrigin( ParentOrigin::TOP_CENTER );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(0), Vector3::ZAXIS );
+ break;
+ case Dali::Window::PORTRAIT_INVERSE:
+ actor.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(180), Vector3::ZAXIS );
+ break;
+ case Dali::Window::LANDSCAPE:
+ actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(270), Vector3::ZAXIS );
+ break;
+ case Dali::Window::LANDSCAPE_INVERSE:
+ actor.SetParentOrigin( ParentOrigin::CENTER_RIGHT );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(90), Vector3::ZAXIS );
+ break;
+ }
+}
+
+void Window::Raise()
+{
+ // Use ecore_wl_window_activate to prevent the window shown without rendering
+ ecore_wl_window_activate( mEventHandler->mEcoreWindow );
+}
+
+void Window::Lower()
+{
+ ecore_wl_window_lower( mEventHandler->mEcoreWindow );
+}
+
+void Window::Activate()
+{
+ ecore_wl_window_activate( mEventHandler->mEcoreWindow );
+}
+
+Dali::DragAndDropDetector Window::GetDragAndDropDetector() const
+{
+ return mDragAndDropDetector;
+}
+
+Dali::Any Window::GetNativeHandle() const
+{
+ if(mEventHandler)
+ {
+ return mEventHandler->mEcoreWindow;
+ }
+ else
+ {
+ return Dali::Any();
+ }
+}
+
+void Window::OnStart()
+{
+ DoShowIndicator( mIndicatorOrientation );
+}
+
+void Window::OnPause()
+{
+}
+
+void Window::OnResume()
+{
+ // resume indicator status
+ if( mIndicator != NULL )
+ {
+ // Restore own indicator opacity
+ // Send opacity mode to indicator service when app resumed
+ mIndicator->SetOpacityMode( mIndicatorOpacityMode );
+ }
+}
+
+void Window::OnStop()
+{
+ if( mIndicator )
+ {
+ mIndicator->Close();
+ }
+
+ delete mIndicator;
+ mIndicator = NULL;
+}
+
+void Window::OnDestroy()
+{
+ mAdaptor = NULL;
+}
+
+void Window::AddAvailableOrientation(Dali::Window::WindowOrientation orientation)
+{
+ bool found = false;
+
+ if ( orientation <= Dali::Window::LANDSCAPE_INVERSE )
+ {
+ for( std::size_t i = 0; i < mAvailableOrientations.size(); i++ )
+ {
+ if( mAvailableOrientations[i] == orientation )
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if( ! found )
+ {
+ mAvailableOrientations.push_back(orientation);
+ SetAvailableOrientations( mAvailableOrientations );
+ }
+ }
+}
+
+void Window::RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation)
+{
+ for( std::vector<Dali::Window::WindowOrientation>::iterator iter = mAvailableOrientations.begin();
+ iter != mAvailableOrientations.end(); ++iter )
+ {
+ if( *iter == orientation )
+ {
+ mAvailableOrientations.erase( iter );
+ break;
+ }
+ }
+ SetAvailableOrientations( mAvailableOrientations );
+}
+
+void Window::SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations)
+{
+ int rotations[4];
+ for( std::size_t i = 0; i < mAvailableOrientations.size(); ++i )
+ {
+ rotations[i] = static_cast< int >( mAvailableOrientations[i] );
+ }
+ ecore_wl_window_rotation_available_rotations_set( mEventHandler->mEcoreWindow, rotations, mAvailableOrientations.size() );
+}
+
+const std::vector<Dali::Window::WindowOrientation>& Window::GetAvailableOrientations()
+{
+ return mAvailableOrientations;
+}
+
+void Window::SetPreferredOrientation(Dali::Window::WindowOrientation orientation)
+{
+ mPreferredOrientation = orientation;
+
+ ecore_wl_window_rotation_preferred_rotation_set( mEventHandler->mEcoreWindow, orientation );
+}
+
+Dali::Window::WindowOrientation Window::GetPreferredOrientation()
+{
+ return mPreferredOrientation;
+}
+
+void Window::SetAcceptFocus( bool accept )
+{
+ mIsFocusAcceptable = accept;
+
+ ecore_wl_window_focus_skip_set( mEventHandler->mEcoreWindow, !accept );
+}
+
+bool Window::IsFocusAcceptable() const
+{
+ return mIsFocusAcceptable;
+}
+
+void Window::Show()
+{
+ mVisible = true;
+ ecore_wl_window_show( mEventHandler->mEcoreWindow );
+
+ if( !mIconified )
+ {
+ if( mAdaptor )
+ {
+ WindowVisibilityObserver* observer( mAdaptor );
+ observer->OnWindowShown();
+ DALI_LOG_RELEASE_INFO( "Window (%p) ::Show() \n", mEventHandler->mEcoreWindow);
+ }
+ }
+}
+
+void Window::Hide()
+{
+ mVisible = false;
+ ecore_wl_window_hide( mEventHandler->mEcoreWindow );
+
+ if( !mIconified )
+ {
+ if( mAdaptor )
+ {
+ WindowVisibilityObserver* observer( mAdaptor );
+ observer->OnWindowHidden();
+ DALI_LOG_RELEASE_INFO( "Window (%p) ::Hide() \n", mEventHandler->mEcoreWindow);
+ }
+ }
+}
+
+bool Window::IsVisible() const
+{
+ return mVisible;
+}
+
+void Window::RotationDone( int orientation, int width, int height )
+{
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+ if( wlSurface )
+ {
+ wlSurface->RequestRotation( orientation, width, height );
+ }
+
+ mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( width, height ) );
+
+ // Emit signal
+ mResizedSignal.Emit( Dali::Window::WindowSize( width, height ) );
+
+ mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( width, height ) );
+}
+
+void Window::SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode )
+{
+ mIndicatorVisible = mode;
+}
+
+unsigned int Window::GetSupportedAuxiliaryHintCount() const
+{
+ return mSupportedAuxiliaryHints.size();
+}
+
+std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
+{
+ if( index >= GetSupportedAuxiliaryHintCount() )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index );
+ }
+
+ return mSupportedAuxiliaryHints[index];
+}
+
+unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
+{
+ bool supported = false;
+
+ // Check if the hint is suppported
+ for( std::vector< std::string >::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter )
+ {
+ if( *iter == hint )
+ {
+ supported = true;
+ break;
+ }
+ }
+
+ if( !supported )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str() );
+ return 0;
+ }
+
+ // Check if the hint is already added
+ for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ )
+ {
+ if( mAuxiliaryHints[i].first == hint )
+ {
+ // Just change the value
+ mAuxiliaryHints[i].second = value;
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1 );
+
+ return i + 1; // id is index + 1
+ }
+ }
+
+ // Add the hint
+ mAuxiliaryHints.push_back( std::pair< std::string, std::string >( hint, value ) );
+
+ unsigned int id = mAuxiliaryHints.size();
+
+ ecore_wl_window_aux_hint_add( mEventHandler->mEcoreWindow, static_cast< int >( id ), hint.c_str(), value.c_str() );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id );
+
+ return id;
+}
+
+bool Window::RemoveAuxiliaryHint( unsigned int id )
+{
+ if( id == 0 || id > mAuxiliaryHints.size() )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::RemoveAuxiliaryHint: Invalid id [%d]\n", id );
+ return false;
+ }
+
+ mAuxiliaryHints[id - 1].second = std::string();
+
+ ecore_wl_window_aux_hint_del( mEventHandler->mEcoreWindow, static_cast< int >( id ) );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str() );
+
+ return true;
+}
+
+bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
+{
+ if( id == 0 || id > mAuxiliaryHints.size() )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::SetAuxiliaryHintValue: Invalid id [%d]\n", id );
+ return false;
+ }
+
+ mAuxiliaryHints[id - 1].second = value;
+
+ ecore_wl_window_aux_hint_change( mEventHandler->mEcoreWindow, static_cast< int >( id ), value.c_str() );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() );
+
+ return true;
+}
+
+std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
+{
+ if( id == 0 || id > mAuxiliaryHints.size() )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Concise, "Window::GetAuxiliaryHintValue: Invalid id [%d]\n", id );
+ return std::string();
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() );
+
+ return mAuxiliaryHints[id - 1].second;
+}
+
+unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
+{
+ for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ )
+ {
+ if( mAuxiliaryHints[i].first == hint )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1 );
+ return i + 1;
+ }
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str() );
+
+ return 0;
+}
+
+void Window::SetInputRegion( const Rect< int >& inputRegion )
+{
+ ecore_wl_window_input_region_set( mEventHandler->mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height );
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetInputRegion: x = %d, y = %d, w = %d, h = %d\n", inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height );
+}
+
+void Window::SetType( Dali::Window::Type type )
+{
+ Ecore_Wl_Window_Type windowType;
+
+ if( type != mType )
+ {
+ switch( type )
+ {
+ case Dali::Window::NORMAL:
+ {
+ windowType = ECORE_WL_WINDOW_TYPE_TOPLEVEL;
+ break;
+ }
+ case Dali::Window::NOTIFICATION:
+ {
+ windowType = ECORE_WL_WINDOW_TYPE_NOTIFICATION;
+ break;
+ }
+ case Dali::Window::UTILITY:
+ {
+ windowType = ECORE_WL_WINDOW_TYPE_UTILITY;
+ break;
+ }
+ case Dali::Window::DIALOG:
+ {
+ windowType = ECORE_WL_WINDOW_TYPE_DIALOG;
+ break;
+ }
+ default:
+ {
+ windowType = ECORE_WL_WINDOW_TYPE_TOPLEVEL;
+ break;
+ }
+ }
+
+ ecore_wl_window_type_set( mEventHandler->mEcoreWindow, windowType );
+ }
+
+ mType = type;
+}
+
+Dali::Window::Type Window::GetType() const
+{
+ return mType;
+}
+
+bool Window::SetNotificationLevel( Dali::Window::NotificationLevel::Type level )
+{
+ if( mType != Dali::Window::NOTIFICATION )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Not supported window type [%d]\n", mType );
+ return false;
+ }
+
+ while( !mEventHandler->mTizenPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ int notificationLevel;
+
+ switch( level )
+ {
+ case Dali::Window::NotificationLevel::NONE:
+ {
+ notificationLevel = TIZEN_POLICY_LEVEL_NONE;
+ break;
+ }
+ case Dali::Window::NotificationLevel::BASE:
+ {
+ notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT;
+ break;
+ }
+ case Dali::Window::NotificationLevel::MEDIUM:
+ {
+ notificationLevel = TIZEN_POLICY_LEVEL_MEDIUM;
+ break;
+ }
+ case Dali::Window::NotificationLevel::HIGH:
+ {
+ notificationLevel = TIZEN_POLICY_LEVEL_HIGH;
+ break;
+ }
+ case Dali::Window::NotificationLevel::TOP:
+ {
+ notificationLevel = TIZEN_POLICY_LEVEL_TOP;
+ break;
+ }
+ default:
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: invalid level [%d]\n", level );
+ notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT;
+ break;
+ }
+ }
+
+ mEventHandler->mNotificationLevelChangeDone = false;
+ mEventHandler->mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
+
+ tizen_policy_set_notification_level( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), notificationLevel );
+
+ int count = 0;
+
+ while( !mEventHandler->mNotificationLevelChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mNotificationLevelChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mEventHandler->mNotificationChangeState );
+ return false;
+ }
+ else if( mEventHandler->mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Permission denied! [%d]\n", level );
+ return false;
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Level is changed [%d]\n", mEventHandler->mNotificationLevel );
+
+ return true;
+}
+
+Dali::Window::NotificationLevel::Type Window::GetNotificationLevel() const
+{
+ if( mType != Dali::Window::NOTIFICATION )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Not supported window type [%d]\n", mType );
+ return Dali::Window::NotificationLevel::NONE;
+ }
+
+ while( !mEventHandler->mTizenPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ int count = 0;
+
+ while( !mEventHandler->mNotificationLevelChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mNotificationLevelChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Error! [%d]\n", mEventHandler->mNotificationChangeState );
+ return Dali::Window::NotificationLevel::NONE;
+ }
+
+ Dali::Window::NotificationLevel::Type level;
+
+ switch( mEventHandler->mNotificationLevel )
+ {
+ case TIZEN_POLICY_LEVEL_NONE:
+ {
+ level = Dali::Window::NotificationLevel::NONE;
+ break;
+ }
+ case TIZEN_POLICY_LEVEL_DEFAULT:
+ {
+ level = Dali::Window::NotificationLevel::BASE;
+ break;
+ }
+ case TIZEN_POLICY_LEVEL_MEDIUM:
+ {
+ level = Dali::Window::NotificationLevel::MEDIUM;
+ break;
+ }
+ case TIZEN_POLICY_LEVEL_HIGH:
+ {
+ level = Dali::Window::NotificationLevel::HIGH;
+ break;
+ }
+ case TIZEN_POLICY_LEVEL_TOP:
+ {
+ level = Dali::Window::NotificationLevel::TOP;
+ break;
+ }
+ default:
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: invalid level [%d]\n", mEventHandler->mNotificationLevel );
+ level = Dali::Window::NotificationLevel::NONE;
+ break;
+ }
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: level [%d]\n", mEventHandler->mNotificationLevel );
+
+ return level;
+}
+
+void Window::SetOpaqueState( bool opaque )
+{
+ while( !mEventHandler->mTizenPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ tizen_policy_set_opaque_state( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), ( opaque ? 1 : 0 ) );
+
+ mOpaqueState = opaque;
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetOpaqueState: opaque = %d\n", opaque );
+}
+
+bool Window::IsOpaqueState() const
+{
+ return mOpaqueState;
+}
+
+bool Window::SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode)
+{
+ while( !mEventHandler->mTizenPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ mEventHandler->mScreenOffModeChangeDone = false;
+ mEventHandler->mScreenOffModeChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
+
+ unsigned int mode = 0;
+
+ switch( screenOffMode )
+ {
+ case Dali::Window::ScreenOffMode::TIMEOUT:
+ {
+ mode = 0;
+ break;
+ }
+ case Dali::Window::ScreenOffMode::NEVER:
+ {
+ mode = 1;
+ break;
+ }
+ }
+
+ tizen_policy_set_window_screen_mode( mEventHandler->mTizenPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), mode );
+
+ int count = 0;
+
+ while( !mEventHandler->mScreenOffModeChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mScreenOffModeChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mEventHandler->mScreenOffModeChangeState );
+ return false;
+ }
+ else if( mEventHandler->mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode );
+ return false;
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetScreenOffMode: Screen mode is changed [%d]\n", mEventHandler->mScreenOffMode );
+
+ return true;
+}
+
+Dali::Window::ScreenOffMode::Type Window::GetScreenOffMode() const
+{
+ while( !mEventHandler->mTizenPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ int count = 0;
+
+ while( !mEventHandler->mScreenOffModeChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mScreenOffModeChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetScreenOffMode: Error! [%d]\n", mEventHandler->mScreenOffModeChangeState );
+ return Dali::Window::ScreenOffMode::TIMEOUT;
+ }
+
+ Dali::Window::ScreenOffMode::Type screenMode = Dali::Window::ScreenOffMode::TIMEOUT;
+
+ switch( mEventHandler->mScreenOffMode )
+ {
+ case 0:
+ {
+ screenMode = Dali::Window::ScreenOffMode::TIMEOUT;
+ break;
+ }
+ case 1:
+ {
+ screenMode = Dali::Window::ScreenOffMode::NEVER;
+ break;
+ }
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetScreenOffMode: screen mode [%d]\n", mEventHandler->mScreenOffMode );
+
+ return screenMode;
+}
+
+bool Window::SetBrightness( int brightness )
+{
+ if( brightness < 0 || brightness > 100 )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Invalid brightness value [%d]\n", brightness );
+ return false;
+ }
+
+ while( !mEventHandler->mTizenDisplayPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ mEventHandler->mBrightnessChangeDone = false;
+ mEventHandler->mBrightnessChangeState = TIZEN_POLICY_ERROR_STATE_NONE;
+
+ tizen_display_policy_set_window_brightness( mEventHandler->mTizenDisplayPolicy, ecore_wl_window_surface_get( mEventHandler->mEcoreWindow ), brightness );
+
+ int count = 0;
+
+ while( !mEventHandler->mBrightnessChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mBrightnessChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mEventHandler->mBrightnessChangeState );
+ return false;
+ }
+ else if( mEventHandler->mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Permission denied! [%d]\n", brightness );
+ return false;
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Brightness is changed [%d]\n", mEventHandler->mBrightness );
+
+ return true;
+}
+
+int Window::GetBrightness() const
+{
+ while( !mEventHandler->mTizenDisplayPolicy )
+ {
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ }
+
+ int count = 0;
+
+ while( !mEventHandler->mBrightnessChangeDone && count < 3 )
+ {
+ ecore_wl_flush();
+ wl_display_dispatch_queue( mEventHandler->mDisplay, mEventHandler->mEventQueue );
+ count++;
+ }
+
+ if( !mEventHandler->mBrightnessChangeDone )
+ {
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetBrightness: Error! [%d]\n", mEventHandler->mBrightnessChangeState );
+ return 0;
+ }
+
+ DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetBrightness: Brightness [%d]\n", mEventHandler->mBrightness );
+
+ return mEventHandler->mBrightness;
+}
+
+void Window::SetSize( Dali::Window::WindowSize size )
+{
+ if( !mResizeEnabled )
+ {
+ AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
+ mResizeEnabled = true;
+ }
+
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ if( positionSize.width != size.GetWidth() || positionSize.height != size.GetHeight() )
+ {
+ positionSize.width = size.GetWidth();
+ positionSize.height = size.GetHeight();
+
+ mSurface->MoveResize( positionSize );
+
+ mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+
+ // Emit signal
+ mResizedSignal.Emit( Dali::Window::WindowSize( positionSize.width, positionSize.height ) );
+
+ mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ }
+}
+
+Dali::Window::WindowSize Window::GetSize() const
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ return Dali::Window::WindowSize( positionSize.width, positionSize.height );
+}
+
+void Window::SetPosition( Dali::Window::WindowPosition position )
+{
+ if( !mResizeEnabled )
+ {
+ AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" );
+ mResizeEnabled = true;
+ }
+
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ if( positionSize.x != position.GetX() || positionSize.y != position.GetY() )
+ {
+ positionSize.x = position.GetX();
+ positionSize.y = position.GetY();
+
+ mSurface->MoveResize( positionSize );
+ }
+}
+
+Dali::Window::WindowPosition Window::GetPosition() const
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ return Dali::Window::WindowPosition( positionSize.x, positionSize.y );
+}
+
+void Window::SetTransparency( bool transparent )
+{
+ ECore::WindowRenderSurface* wlSurface( dynamic_cast< ECore::WindowRenderSurface * >( mSurface ) );
+ if( wlSurface )
+ {
+ wlSurface->SetTransparency( transparent );
+ }
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/tizen-wayland/window-render-surface-ecore-wl.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/wl-types.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+#include <dali/integration-api/trigger-event-factory-interface.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gRenderSurfaceLogFilter;
+#endif
+
+namespace ECore
+{
+
+namespace
+{
+
+const int MINIMUM_DIMENSION_CHANGE( 1 ); ///< Minimum change for window to be considered to have moved
+
+} // unnamed namespace
+
+WindowRenderSurface::WindowRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+: EcoreWlRenderSurface( positionSize, surface, name, isTransparent ),
+ mWlWindow( NULL ),
+ mWlSurface( NULL ),
+ mEglWindow( NULL ),
+ mThreadSynchronization( NULL ),
+ mRotationTrigger( NULL ),
+ mRotationAngle( 0 ),
+ mScreenRotationAngle( 0 ),
+ mRotationSupported( false ),
+ mRotationFinished( true ),
+ mScreenRotationFinished( true ),
+ mResizeFinished( true )
+{
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n" );
+ Init( surface );
+}
+
+WindowRenderSurface::~WindowRenderSurface()
+{
+ if( mEglWindow != NULL )
+ {
+ wl_egl_window_destroy(mEglWindow);
+ mEglWindow = NULL;
+ }
+
+ if( mOwnSurface )
+ {
+ ecore_wl_window_free( mWlWindow );
+ }
+
+ if( mRotationTrigger )
+ {
+ delete mRotationTrigger;
+ }
+
+}
+
+Ecore_Wl_Window* WindowRenderSurface::GetDrawable()
+{
+ // already an e-core type
+ return mWlWindow;
+}
+
+Any WindowRenderSurface::GetSurface()
+{
+ // already an e-core type
+ return Any( mWlWindow );
+}
+
+Ecore_Wl_Window* WindowRenderSurface::GetWlWindow()
+{
+ return mWlWindow;
+}
+
+void WindowRenderSurface::RequestRotation( int angle, int width, int height )
+{
+ if( !mRotationSupported )
+ {
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::Rotate: Rotation is not supported!\n" );
+ return;
+ }
+
+ if( !mRotationTrigger )
+ {
+ TriggerEventFactoryInterface& triggerFactory = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetTriggerEventFactoryInterface();
+ mRotationTrigger = triggerFactory.CreateTriggerEvent( MakeCallback( this, &WindowRenderSurface::ProcessRotationRequest ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
+ }
+
+ mPositionSize.width = width;
+ mPositionSize.height = height;
+
+ mRotationAngle = angle;
+ mRotationFinished = false;
+
+ ecore_wl_window_rotation_set( mWlWindow, mRotationAngle );
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::Rotate: angle = %d screen rotation = %d\n", mRotationAngle, mScreenRotationAngle );
+}
+
+void WindowRenderSurface::OutputTransformed()
+{
+ int transform;
+
+ if( ecore_wl_window_ignore_output_transform_get( mWlWindow ) )
+ {
+ transform = 0;
+ }
+ else
+ {
+ transform = ecore_wl_output_transform_get( ecore_wl_window_output_find( mWlWindow ) );
+ }
+
+ mScreenRotationAngle = transform * 90;
+ mScreenRotationFinished = false;
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::OutputTransformed: angle = %d screen rotation = %d\n", mRotationAngle, mScreenRotationAngle );
+}
+
+void WindowRenderSurface::SetTransparency( bool transparent )
+{
+ ecore_wl_window_alpha_set( mWlWindow, transparent );
+}
+
+void WindowRenderSurface::InitializeEgl( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+
+ eglImpl.ChooseConfig(true, mColorDepth);
+}
+
+void WindowRenderSurface::CreateEglSurface( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+
+ // create the EGL window
+ if( mScreenRotationAngle == 0 || mScreenRotationAngle == 180 )
+ {
+ mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.width, mPositionSize.height );
+ }
+ else
+ {
+ mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.height, mPositionSize.width );
+ }
+
+ EGLNativeWindowType windowType( mEglWindow );
+ eglImpl.CreateSurfaceWindow( windowType, mColorDepth );
+
+ // Check capability
+ wl_egl_window_capability capability = static_cast< wl_egl_window_capability >( wl_egl_window_get_capabilities( mEglWindow ) );
+ if( capability == WL_EGL_WINDOW_CAPABILITY_ROTATION_SUPPORTED )
+ {
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::CreateEglSurface: capability = %d\n", capability );
+ mRotationSupported = true;
+ }
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::CreateEglSurface: w = %d h = %d angle = %d screen rotation = %d\n", mPositionSize.width, mPositionSize.height, mRotationAngle, mScreenRotationAngle );
+}
+
+void WindowRenderSurface::DestroyEglSurface( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+ eglImpl.DestroySurface();
+
+ if( mEglWindow != NULL )
+ {
+ wl_egl_window_destroy(mEglWindow);
+ mEglWindow = NULL;
+ }
+}
+
+bool WindowRenderSurface::ReplaceEGLSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ if( mEglWindow != NULL )
+ {
+ wl_egl_window_destroy(mEglWindow);
+ mEglWindow = NULL;
+ }
+
+ if( mScreenRotationAngle == 0 || mScreenRotationAngle == 180 )
+ {
+ mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.width, mPositionSize.height );
+ }
+ else
+ {
+ mEglWindow = wl_egl_window_create( mWlSurface, mPositionSize.height, mPositionSize.width );
+ }
+
+ // Set screen rotation
+ mScreenRotationFinished = false;
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ EGLNativeWindowType windowType( mEglWindow );
+ return eglImpl.ReplaceSurfaceWindow( windowType );
+}
+
+void WindowRenderSurface::MoveResize( Dali::PositionSize positionSize )
+{
+ bool needToMove = false;
+ bool needToResize = false;
+
+ // check moving
+ if( (fabs(positionSize.x - mPositionSize.x) > MINIMUM_DIMENSION_CHANGE) ||
+ (fabs(positionSize.y - mPositionSize.y) > MINIMUM_DIMENSION_CHANGE) )
+ {
+ needToMove = true;
+ }
+
+ // check resizing
+ if( (fabs(positionSize.width - mPositionSize.width) > MINIMUM_DIMENSION_CHANGE) ||
+ (fabs(positionSize.height - mPositionSize.height) > MINIMUM_DIMENSION_CHANGE) )
+ {
+ needToResize = true;
+ }
+
+ if( needToMove )
+ {
+ ecore_wl_window_position_set( mWlWindow, positionSize.x, positionSize.y );
+ }
+ if( needToResize )
+ {
+ ecore_wl_window_update_size( mWlWindow, positionSize.width, positionSize.height );
+ mResizeFinished = false;
+ }
+
+ mPositionSize = positionSize;
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::MoveResize: %d, %d, %d, %d\n", mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height );
+}
+
+void WindowRenderSurface::Map()
+{
+ ecore_wl_window_show(mWlWindow);
+}
+
+void WindowRenderSurface::StartRender()
+{
+}
+
+bool WindowRenderSurface::PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface )
+{
+ if( resizingSurface )
+ {
+#ifdef OVER_TIZEN_VERSION_4
+ // Window rotate or screen rotate
+ if( !mRotationFinished || !mScreenRotationFinished )
+ {
+ wl_egl_window_rotation rotation;
+ wl_output_transform bufferTransform;
+ int totalAngle = (mRotationAngle + mScreenRotationAngle) % 360;
+
+ switch( totalAngle )
+ {
+ case 0:
+ {
+ rotation = ROTATION_0;
+ bufferTransform = WL_OUTPUT_TRANSFORM_NORMAL;
+ break;
+ }
+ case 90:
+ {
+ rotation = ROTATION_270;
+ bufferTransform = WL_OUTPUT_TRANSFORM_90;
+ break;
+ }
+ case 180:
+ {
+ rotation = ROTATION_180;
+ bufferTransform = WL_OUTPUT_TRANSFORM_180;
+ break;
+ }
+ case 270:
+ {
+ rotation = ROTATION_90;
+ bufferTransform = WL_OUTPUT_TRANSFORM_270;
+ break;
+ }
+ default:
+ {
+ rotation = ROTATION_0;
+ bufferTransform = WL_OUTPUT_TRANSFORM_NORMAL;
+ break;
+ }
+ }
+
+ wl_egl_window_set_rotation( mEglWindow, rotation );
+
+ wl_egl_window_set_buffer_transform( mEglWindow, bufferTransform );
+
+ // Reset only screen rotation flag
+ mScreenRotationFinished = true;
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PreRender: Set rotation [%d] [%d]\n", mRotationAngle, mScreenRotationAngle );
+ }
+
+ // Only window rotate
+ if( !mRotationFinished )
+ {
+ wl_output_transform windowTransform;
+
+ switch( mRotationAngle )
+ {
+ case 0:
+ {
+ windowTransform = WL_OUTPUT_TRANSFORM_NORMAL;
+ break;
+ }
+ case 90:
+ {
+ windowTransform = WL_OUTPUT_TRANSFORM_90;
+ break;
+ }
+ case 180:
+ {
+ windowTransform = WL_OUTPUT_TRANSFORM_180;
+ break;
+ }
+ case 270:
+ {
+ windowTransform = WL_OUTPUT_TRANSFORM_270;
+ break;
+ }
+ default:
+ {
+ windowTransform = WL_OUTPUT_TRANSFORM_NORMAL;
+ break;
+ }
+ }
+
+ wl_egl_window_set_window_transform( mEglWindow, windowTransform );
+ }
+#endif
+
+ // Resize case
+ if( !mResizeFinished )
+ {
+ wl_egl_window_resize( mEglWindow, mPositionSize.width, mPositionSize.height, mPositionSize.x, mPositionSize.y );
+ mResizeFinished = true;
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PreRender: Set resize\n" );
+ }
+ }
+
+ return true;
+}
+
+void WindowRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
+{
+ if( resizingSurface )
+ {
+ if( !mRotationFinished )
+ {
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::PostRender: Trigger rotation event\n" );
+
+ mRotationTrigger->Trigger();
+
+ if( mThreadSynchronization )
+ {
+ // Wait until the event-thread complete the rotation event processing
+ mThreadSynchronization->PostRenderWaitForCompletion();
+ }
+ }
+ }
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ eglImpl.SwapBuffers();
+
+ if( mRenderNotification )
+ {
+ mRenderNotification->Trigger();
+ }
+}
+
+void WindowRenderSurface::StopRender()
+{
+}
+
+void WindowRenderSurface::SetViewMode( ViewMode viewMode )
+{
+ //FIXME
+}
+
+void WindowRenderSurface::CreateWlRenderable()
+{
+ // if width or height are zero, go full screen.
+ if ( (mPositionSize.width == 0) || (mPositionSize.height == 0) )
+ {
+ // Default window size == screen size
+ mPositionSize.x = 0;
+ mPositionSize.y = 0;
+
+ ecore_wl_screen_size_get( &mPositionSize.width, &mPositionSize.height );
+ }
+
+ mWlWindow = ecore_wl_window_new( 0, mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height, ECORE_WL_WINDOW_BUFFER_TYPE_EGL_WINDOW );
+
+ if ( mWlWindow == 0 )
+ {
+ DALI_ASSERT_ALWAYS(0 && "Failed to create Wayland window");
+ }
+
+ mWlSurface = ecore_wl_window_surface_create( mWlWindow );
+
+ if( mColorDepth == COLOR_DEPTH_32 )
+ {
+ ecore_wl_window_alpha_set( mWlWindow, true );
+ }
+ else
+ {
+ ecore_wl_window_alpha_set( mWlWindow, false );
+ }
+
+ // Get output transform
+ if( !ecore_wl_window_ignore_output_transform_get( mWlWindow ) )
+ {
+ Ecore_Wl_Output* output = ecore_wl_window_output_find( mWlWindow );
+
+ int transform = ecore_wl_output_transform_get( output );
+
+ mScreenRotationAngle = transform * 90;
+ mScreenRotationFinished = false;
+ }
+}
+
+void WindowRenderSurface::UseExistingRenderable( unsigned int surfaceId )
+{
+ mWlWindow = AnyCast< Ecore_Wl_Window* >( surfaceId );
+}
+
+void WindowRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
+{
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::SetThreadSynchronization: called\n" );
+
+ mThreadSynchronization = &threadSynchronization;
+}
+
+void WindowRenderSurface::ReleaseLock()
+{
+ // Nothing to do.
+}
+
+void WindowRenderSurface::ProcessRotationRequest()
+{
+ mRotationFinished = true;
+
+ ecore_wl_window_rotation_change_done_send( mWlWindow );
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::ProcessRotationRequest: Rotation Done\n" );
+
+ if( mThreadSynchronization )
+ {
+ mThreadSynchronization->PostRenderComplete();
+ }
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
+#define __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <wayland-egl.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/ecore-wl-render-surface.h>
+#include <dali/integration-api/thread-synchronization-interface.h>
+
+namespace Dali
+{
+
+namespace ECore
+{
+
+/**
+ * @copydoc Dali::ECore::EcoreWlRenderSurface.
+ * Window specialization.
+ */
+class WindowRenderSurface : public EcoreWlRenderSurface
+{
+public:
+
+ /**
+ * Uses an Wayland surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a Wayland-window or Wayland-pixmap (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ WindowRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent = false );
+
+ /**
+ * @copydoc Dali::ECore::EcoreWlRenderSurface::~EcoreWlRenderSurface
+ */
+ virtual ~WindowRenderSurface();
+
+public: // API
+
+ /**
+ * @copydoc Dali::RenderSurface::GetDrawable()
+ */
+ virtual Ecore_Wl_Window* GetDrawable();
+
+ /**
+ * Map window
+ */
+ virtual void Map();
+
+ /**
+ * @copydoc Dali::ECore::EcoreWlRenderSurface::GetSurface()
+ */
+ virtual Any GetSurface();
+
+ /**
+ * @copydoc Dali::ECore::EcoreWlRenderSurface::GetWlWindow()
+ */
+ virtual Ecore_Wl_Window* GetWlWindow();
+
+ /**
+ * Request surface rotation
+ * @param[in] angle A new angle of the surface
+ * @param[in] width A new width of the surface
+ * @param[in] height A new height of the surface
+ */
+ void RequestRotation( int angle, int width, int height );
+
+ /**
+ * Notify output is transformed.
+ */
+ void OutputTransformed();
+
+ /**
+ * @brief Sets whether the surface is transparent or not.
+ *
+ * @param[in] transparent Whether the surface is transparent
+ */
+ void SetTransparency( bool transparent );
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::MoveResize()
+ */
+ virtual void MoveResize( Dali::PositionSize positionSize);
+
+ /**
+ * @copydoc Dali::RenderSurface::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::StopRender()
+ */
+ virtual void StopRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::SetThreadSynchronization
+ */
+ virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReleaseLock()
+ */
+ virtual void ReleaseLock();
+
+protected:
+
+ /**
+ * Create WlWindow
+ */
+ virtual void CreateWlRenderable();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::ECore::EcoreWlRenderSurface::UseExistingRenderable
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId );
+
+private:
+
+ /**
+ * Used as the callback for the rotation-trigger.
+ */
+ void ProcessRotationRequest();
+
+private: // Data
+
+ Ecore_Wl_Window* mWlWindow; ///< Wayland-Window
+ wl_surface* mWlSurface;
+ wl_egl_window* mEglWindow;
+ ThreadSynchronizationInterface* mThreadSynchronization;
+ TriggerEventInterface* mRotationTrigger;
+ int mRotationAngle;
+ int mScreenRotationAngle;
+ bool mRotationSupported;
+ bool mRotationFinished;
+ bool mScreenRotationFinished;
+ bool mResizeFinished;
+
+}; // class WindowRenderSurface
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ECORE_WL_WINDOW_RENDER_SURFACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/wayland/native-render-surface.h>
+
+namespace Dali
+{
+
+DALI_EXPORT_API NativeRenderSurface* CreateNativeSurface(
+ PositionSize positionSize,
+ const std::string& name,
+ bool isTransparent)
+{
+ return new NativeRenderSurface( positionSize, name, isTransparent );
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/display-connection-impl.h>
+
+// EXTERNAL_HEADERS
+#include <tbm_bufmgr.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL HEADERS
+#include <dali/integration-api/wayland/native-render-surface.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+EGLNativeDisplayType DisplayConnection::GetNativeDisplay()
+{
+ return reinterpret_cast< EGLNativeDisplayType >( tbm_bufmgr_init( -1 ) );
+}
+
+void DisplayConnection::ReleaseNativeDisplay()
+{
+ if( mDisplay )
+ {
+ tbm_bufmgr_deinit( reinterpret_cast< tbm_bufmgr >( mDisplay ) );
+ }
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/wayland/native-render-surface.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/threading/conditional-wait.h>
+
+#include <Ecore_Wayland.h>
+#include <tbm_bufmgr.h>
+#include <tbm_surface_queue.h>
+#include <tbm_surface_internal.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/window-system/common/display-connection.h>
+#include <dali/integration-api/thread-synchronization-interface.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gRenderSurfaceLogFilter;
+#endif
+
+struct NativeRenderSurface::Impl
+{
+ Impl( Dali::PositionSize positionSize, const std::string& name, bool isTransparent )
+ : mPosition( positionSize ),
+ mTitle( name ),
+ mRenderNotification( NULL ),
+ mColorDepth( isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24 ),
+ mTbmFormat( isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888 ),
+ mOwnSurface( false ),
+ mDrawableCompleted( false ),
+ mTbmQueue( NULL ),
+ mConsumeSurface( NULL ),
+ mThreadSynchronization( NULL )
+ {
+ }
+
+ PositionSize mPosition;
+ std::string mTitle;
+ TriggerEventInterface* mRenderNotification;
+ ColorDepth mColorDepth;
+ tbm_format mTbmFormat;
+ bool mOwnSurface;
+ bool mDrawableCompleted;
+
+ tbm_surface_queue_h mTbmQueue;
+ tbm_surface_h mConsumeSurface;
+ ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization
+ ConditionalWait mTbmSurfaceCondition;
+};
+
+NativeRenderSurface::NativeRenderSurface(Dali::PositionSize positionSize,
+ const std::string& name,
+ bool isTransparent)
+: mImpl( new Impl( positionSize, name, isTransparent ) )
+{
+ ecore_wl_init(NULL);
+ CreateNativeRenderable();
+ setenv( "EGL_PLATFORM", "tbm", 1 );
+}
+
+NativeRenderSurface::~NativeRenderSurface()
+{
+ // release the surface if we own one
+ if( mImpl->mOwnSurface )
+ {
+ ReleaseDrawable();
+
+ if( mImpl->mTbmQueue )
+ {
+ tbm_surface_queue_destroy( mImpl->mTbmQueue );
+ }
+
+ delete mImpl;
+
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n" );
+ }
+}
+
+void NativeRenderSurface::SetRenderNotification( TriggerEventInterface* renderNotification )
+{
+ mImpl->mRenderNotification = renderNotification;
+}
+
+tbm_surface_h NativeRenderSurface::GetDrawable()
+{
+ return mImpl->mConsumeSurface;
+}
+
+Any NativeRenderSurface::GetSurface()
+{
+ return Any( NULL );
+}
+
+void NativeRenderSurface::InitializeEgl( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+ unsetenv( "EGL_PLATFORM" );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ eglImpl.ChooseConfig( true, mImpl->mColorDepth );
+}
+
+void NativeRenderSurface::CreateEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ eglImpl.CreateSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mImpl->mTbmQueue ), mImpl->mColorDepth );
+}
+
+void NativeRenderSurface::DestroyEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ eglImpl.DestroySurface();
+}
+
+bool NativeRenderSurface::ReplaceEGLSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ if( !mImpl->mTbmQueue )
+ {
+ return false;
+ }
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ return eglImpl.ReplaceSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mImpl->mTbmQueue ) );
+}
+
+void NativeRenderSurface::StartRender()
+{
+}
+
+bool NativeRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
+{
+ // nothing to do for pixmaps
+ return true;
+}
+
+void NativeRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
+{
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ eglImpl.SwapBuffers();
+
+ if( mImpl->mThreadSynchronization )
+ {
+ mImpl->mThreadSynchronization->PostRenderStarted();
+ }
+
+ if( tbm_surface_queue_can_acquire( mImpl->mTbmQueue, 1 ) )
+ {
+ if( tbm_surface_queue_acquire( mImpl->mTbmQueue, &mImpl->mConsumeSurface ) != TBM_SURFACE_QUEUE_ERROR_NONE )
+ {
+ DALI_LOG_ERROR( "Failed to aquire a tbm_surface\n" );
+ return;
+ }
+ }
+
+ tbm_surface_internal_ref( mImpl->mConsumeSurface );
+
+ if( replacingSurface )
+ {
+ ConditionalWait::ScopedLock lock( mImpl->mTbmSurfaceCondition );
+ mImpl->mDrawableCompleted = true;
+ mImpl->mTbmSurfaceCondition.Notify( lock );
+ }
+
+ // create damage for client applications which wish to know the update timing
+ if( !replacingSurface && mImpl->mRenderNotification )
+ {
+ // use notification trigger
+ // Tell the event-thread to render the tbm_surface
+ mImpl->mRenderNotification->Trigger();
+ }
+
+ if( mImpl->mThreadSynchronization )
+ {
+ // wait until the event-thread completed to use the tbm_surface
+ mImpl->mThreadSynchronization->PostRenderWaitForCompletion();
+ }
+
+ // release the consumed surface after post render was completed
+ ReleaseDrawable();
+}
+
+void NativeRenderSurface::StopRender()
+{
+ ReleaseLock();
+}
+
+PositionSize NativeRenderSurface::GetPositionSize() const
+{
+ return mImpl->mPosition;
+}
+
+void NativeRenderSurface::MoveResize( Dali::PositionSize positionSize )
+{
+}
+
+void NativeRenderSurface::SetViewMode( ViewMode viewMode )
+{
+}
+
+void NativeRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
+{
+ mImpl->mThreadSynchronization = &threadSynchronization;
+}
+
+RenderSurface::Type NativeRenderSurface::GetSurfaceType()
+{
+ return RenderSurface::NATIVE_RENDER_SURFACE;
+}
+
+void NativeRenderSurface::CreateNativeRenderable()
+{
+ // check we're creating one with a valid size
+ DALI_ASSERT_ALWAYS( mImpl->mPosition.width > 0 && mImpl->mPosition.height > 0 && "tbm_surface size is invalid" );
+
+ mImpl->mTbmQueue = tbm_surface_queue_create( 3, mImpl->mPosition.width, mImpl->mPosition.height, mImpl->mTbmFormat, TBM_BO_DEFAULT );
+
+ if( mImpl->mTbmQueue )
+ {
+ mImpl->mOwnSurface = true;
+ }
+ else
+ {
+ mImpl->mOwnSurface = false;
+ }
+}
+
+void NativeRenderSurface::ReleaseLock()
+{
+ if( mImpl->mThreadSynchronization )
+ {
+ mImpl->mThreadSynchronization->PostRenderComplete();
+ }
+}
+
+void NativeRenderSurface::WaitUntilSurfaceReplaced()
+{
+ ConditionalWait::ScopedLock lock( mImpl->mTbmSurfaceCondition );
+ while( !mImpl->mDrawableCompleted )
+ {
+ mImpl->mTbmSurfaceCondition.Wait( lock );
+ }
+
+ mImpl->mDrawableCompleted = false;
+}
+
+void NativeRenderSurface::ReleaseDrawable()
+{
+ if( mImpl->mConsumeSurface )
+ {
+ tbm_surface_internal_unref( mImpl->mConsumeSurface );
+
+ if( tbm_surface_internal_is_valid( mImpl->mConsumeSurface ) )
+ {
+ tbm_surface_queue_release( mImpl->mTbmQueue, mImpl->mConsumeSurface );
+ }
+ mImpl->mConsumeSurface = NULL;
+ }
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/x11/pixmap-render-surface.h>
+
+// EXTERNAL INCLUDES
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#include <X11/extensions/Xfixes.h> // for damage notify
+#include <X11/extensions/Xdamage.h> // for damage notify
+
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+#include <dali/devel-api/threading/mutex.h>
+#include <dali/devel-api/threading/conditional-wait.h>
+
+// INTERNAL INCLUDES
+
+#include <dali/integration-api/thread-synchronization-interface.h>
+#include <dali/integration-api/x11/ecore-x-types.h>
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/window-system/common/display-connection.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gRenderSurfaceLogFilter;
+#endif
+
+namespace ECore
+{
+
+namespace
+{
+static const int INITIAL_PRODUCE_BUFFER_INDEX = 0;
+static const int INITIAL_CONSUME_BUFFER_INDEX = 1;
+static const int BUFFER_COUNT = 2;
+}
+
+struct PixmapRenderSurface::Impl
+{
+ Impl()
+ : mProduceBufferIndex( INITIAL_PRODUCE_BUFFER_INDEX ),
+ mConsumeBufferIndex( INITIAL_CONSUME_BUFFER_INDEX ),
+ mThreadSynchronization(NULL)
+ {
+ for (int i = 0; i != BUFFER_COUNT; ++i)
+ {
+ mX11Pixmaps[i] = 0;
+ mEglSurfaces[i] = 0;
+ }
+ }
+
+ int mProduceBufferIndex;
+ int mConsumeBufferIndex;
+ XPixmap mX11Pixmaps[BUFFER_COUNT]; ///< X-Pixmap
+ EGLSurface mEglSurfaces[BUFFER_COUNT];
+ ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization
+ ConditionalWait mPixmapCondition; ///< condition to share pixmap
+};
+
+PixmapRenderSurface::PixmapRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+: EcoreXRenderSurface( positionSize, surface, name, isTransparent ),
+ mImpl( new Impl )
+{
+ Init( surface );
+}
+
+PixmapRenderSurface::~PixmapRenderSurface()
+{
+ // release the surface if we own one
+ if( mOwnSurface )
+ {
+ for (int i = 0; i < BUFFER_COUNT; ++i)
+ {
+ Ecore_X_Pixmap pixmap = mImpl->mX11Pixmaps[i];
+
+ // if we did create the pixmap, delete the pixmap
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::General, "Own pixmap (%x) freed\n", pixmap );
+ ecore_x_pixmap_free( pixmap );
+ }
+ }
+
+ delete mImpl;
+}
+
+Ecore_X_Drawable PixmapRenderSurface::GetDrawable()
+{
+ Ecore_X_Pixmap pixmap = 0;
+ {
+ ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
+ pixmap = mImpl->mX11Pixmaps[mImpl->mConsumeBufferIndex];
+ }
+
+ return Ecore_X_Drawable( pixmap );
+}
+
+Any PixmapRenderSurface::GetSurface()
+{
+ Ecore_X_Pixmap pixmap = 0;
+ {
+ ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
+ pixmap = mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex];
+ }
+
+ return Any( pixmap );
+}
+
+void PixmapRenderSurface::InitializeEgl( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ eglImpl.ChooseConfig(false, mColorDepth);
+}
+
+void PixmapRenderSurface::CreateEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ for (int i = 0; i < BUFFER_COUNT; ++i)
+ {
+ // create the EGL surface
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
+ mImpl->mEglSurfaces[i] = eglImpl.CreateSurfacePixmap( EGLNativePixmapType( pixmap ), mColorDepth ); // reinterpret_cast does not compile
+ }
+}
+
+void PixmapRenderSurface::DestroyEglSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ for (int i = 0; i < BUFFER_COUNT; ++i)
+ {
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
+ eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[i] );
+ eglImpl.DestroySurface();
+ }
+}
+
+bool PixmapRenderSurface::ReplaceEGLSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ bool contextLost = false;
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ for (int i = 0; i < BUFFER_COUNT; ++i)
+ {
+ // a new surface for the new pixmap
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[i] );
+ contextLost = eglImpl.ReplaceSurfacePixmap( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[i] ); // reinterpret_cast does not compile
+ }
+
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
+ eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[mImpl->mProduceBufferIndex] );
+
+ return contextLost;
+}
+
+void PixmapRenderSurface::StartRender()
+{
+}
+
+bool PixmapRenderSurface::PreRender( EglInterface& egl, Integration::GlAbstraction&, bool )
+{
+ // Nothing to do for pixmaps
+ return true;
+}
+
+void PixmapRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
+{
+ // flush gl instruction queue
+ glAbstraction.Flush();
+
+ if( mImpl->mThreadSynchronization )
+ {
+ mImpl->mThreadSynchronization->PostRenderStarted();
+ }
+
+ {
+ ConditionalWait::ScopedLock lock( mImpl->mPixmapCondition );
+ mImpl->mConsumeBufferIndex = __sync_fetch_and_xor( &mImpl->mProduceBufferIndex, 1 ); // Swap buffer indexes.
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XPixmap pixmap = static_cast<XPixmap>( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
+ eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mImpl->mEglSurfaces[mImpl->mProduceBufferIndex] );
+ }
+
+ // create damage for client applications which wish to know the update timing
+ if( mRenderNotification )
+ {
+ // use notification trigger
+ // Tell the event-thread to render the pixmap
+ mRenderNotification->Trigger();
+ }
+ else
+ {
+ // as a fallback, send damage event.
+ Ecore_X_Drawable drawable = Ecore_X_Drawable( mImpl->mX11Pixmaps[mImpl->mProduceBufferIndex] );
+
+ if( drawable )
+ {
+ XRectangle rect;
+ XserverRegion region;
+
+ rect.x = 0;
+ rect.y = 0;
+ rect.width = mPosition.width;
+ rect.height = mPosition.height;
+
+ XDisplay* display = AnyCast<XDisplay*>(displayConnection->GetDisplay());
+
+ // make a fixes region as updated area
+ region = XFixesCreateRegion( display, &rect, 1 );
+ // add damage event to updated drawable
+ Drawable xdrawable( drawable ); // ecore type is unsigned int whereas in 64bit linux Drawable is long unsigned int
+ XDamageAdd( display, xdrawable, region );
+ XFixesDestroyRegion( display, region );
+
+ XFlush( display );
+ }
+ }
+
+ if( mImpl->mThreadSynchronization )
+ {
+ mImpl->mThreadSynchronization->PostRenderWaitForCompletion();
+ }
+}
+
+void PixmapRenderSurface::StopRender()
+{
+ ReleaseLock();
+}
+
+void PixmapRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )
+{
+ mImpl->mThreadSynchronization = &threadSynchronization;
+}
+
+void PixmapRenderSurface::CreateXRenderable()
+{
+ // check we're creating one with a valid size
+ DALI_ASSERT_ALWAYS( mPosition.width > 0 && mPosition.height > 0 && "Pixmap size is invalid" );
+
+ for (int i = 0; i < BUFFER_COUNT; ++i)
+ {
+ // create the pixmap
+ mImpl->mX11Pixmaps[i] = ecore_x_pixmap_new(0, mPosition.width, mPosition.height, mColorDepth);
+
+ // clear the pixmap
+ unsigned int foreground;
+ Ecore_X_GC gc;
+ foreground = 0;
+ gc = ecore_x_gc_new( mImpl->mX11Pixmaps[i],
+ ECORE_X_GC_VALUE_MASK_FOREGROUND,
+ &foreground );
+
+ DALI_ASSERT_ALWAYS( gc && "CreateXRenderable(): failed to get gc" );
+
+ ecore_x_drawable_rectangle_fill( mImpl->mX11Pixmaps[i], gc, 0, 0, mPosition.width, mPosition.height );
+
+ DALI_ASSERT_ALWAYS( mImpl->mX11Pixmaps[i] && "Failed to create X pixmap" );
+
+ // we SHOULD guarantee the xpixmap/x11 window was created in x server.
+ ecore_x_sync();
+
+ ecore_x_gc_free(gc);
+ }
+}
+
+void PixmapRenderSurface::UseExistingRenderable( unsigned int surfaceId )
+{
+}
+
+void PixmapRenderSurface::ReleaseLock()
+{
+ if( mImpl->mThreadSynchronization )
+ {
+ mImpl->mThreadSynchronization->PostRenderComplete();
+ }
+}
+
+RenderSurface::Type PixmapRenderSurface::GetSurfaceType()
+{
+ return RenderSurface::ECORE_RENDER_SURFACE;
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/window-system/ubuntu-x11/display-connection-factory-x.h>
+#include <dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h>
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+
+
+
+std::unique_ptr<Dali::Internal::Adaptor::DisplayConnection> DisplayConnectionFactoryX::CreateDisplayConnection()
+{
+ return Utils::MakeUnique<DisplayConnectionX11>();
+}
+
+// this should be created from somewhere
+std::unique_ptr<DisplayConnectionFactory> GetDisplayConnectionFactory()
+{
+ // returns X display factory
+ return Utils::MakeUnique<DisplayConnectionFactoryX>();
+}
+
+void DisplayConnectionFactoryGetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ DisplayConnectionX11::GetDpi( dpiHorizontal, dpiVertical );
+}
+
+}
+}
+}
\ No newline at end of file
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_FACTORY_ECORE_X_H
+#define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_FACTORY_ECORE_X_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/internal/window-system/common/display-connection-factory.h>
+#include <dali/internal/window-system/common/display-utils.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+class DisplayConnectionFactoryX : public DisplayConnectionFactory
+{
+public:
+ std::unique_ptr<Dali::Internal::Adaptor::DisplayConnection> CreateDisplayConnection() override;
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_FACTORY_ECORE_X_H
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h>
+
+// EXTERNAL_HEADERS
+#include <Ecore_X.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL HEADERS
+#include <dali/integration-api/x11/pixmap-render-surface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+DisplayConnection* DisplayConnectionX11::New()
+{
+ //DisplayConnection* pDisplayConnection(new DisplayConnection());
+
+ //return pDisplayConnection;
+ return nullptr;
+}
+
+DisplayConnectionX11::DisplayConnectionX11()
+: mDisplay(NULL)
+{
+}
+
+DisplayConnectionX11::~DisplayConnectionX11()
+{
+ if(mDisplay)
+ {
+ XCloseDisplay(mDisplay);
+ }
+}
+
+Any DisplayConnectionX11::GetDisplay()
+{
+ return Any(mDisplay);
+}
+
+void DisplayConnectionX11::ConsumeEvents()
+{
+ // check events so that we can flush the queue and avoid any potential memory leaks in X
+ // looping if events remain
+ int events(0);
+ do
+ {
+ // Check if there are any events in the queue
+ events = XEventsQueued(mDisplay, QueuedAfterFlush);
+
+ if (events > 0)
+ {
+ // Just flush event to prevent memory leak from event queue as the events get built up in
+ // memory but are only deleted when we retrieve them
+ XEvent ev;
+ XNextEvent(mDisplay, &ev);
+ }
+ }
+ while (events > 0);
+}
+
+bool DisplayConnectionX11::InitializeEgl(EglInterface& egl)
+{
+ EglImplementation& eglImpl = static_cast<EglImplementation&>(egl);
+
+ if (!eglImpl.InitializeGles(reinterpret_cast<EGLNativeDisplayType>(mDisplay)))
+ {
+ DALI_LOG_ERROR("Failed to initialize GLES.\n");
+ return false;
+ }
+
+ return true;
+}
+
+void DisplayConnectionX11::SetSurfaceType( RenderSurface::Type type )
+{
+ if( type == RenderSurface::ECORE_RENDER_SURFACE )
+ {
+ // Because of DDK issue, we need to use separated x display instead of ecore default display
+ mDisplay = XOpenDisplay(0);
+ }
+}
+
+void DisplayConnectionX11::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
+{
+ // calculate DPI
+ float xres, yres;
+
+ // 1 inch = 25.4 millimeters
+ xres = ecore_x_dpi_get();
+ yres = ecore_x_dpi_get();
+
+ dpiHorizontal = int(xres + 0.5f); // rounding
+ dpiVertical = int(yres + 0.5f);
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_IMPL_ECORE_X_H
+#define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_IMPL_ECORE_X_H
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/x11/ecore-x-types.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/display-connection-impl.h>
+#include <dali/public-api/object/base-object.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+class RenderSurface;
+class DisplayConnection;
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+
+class Impl
+{
+public:
+
+ XDisplay* mDisplay; ///< X-display for rendering
+};
+
+
+/**
+ * DisplayConnection implementation
+ */
+class DisplayConnectionX11 : public Dali::Internal::Adaptor::DisplayConnection
+{
+public:
+
+ /**
+ * @brief Default constructor
+ */
+ DisplayConnectionX11();
+
+ /**
+ * @brief Create an initialized DisplayConnection.
+ *
+ * @return A handle to a newly allocated DisplayConnection resource.
+ */
+ static DisplayConnection* New();
+
+public:
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDisplay
+ */
+ Any GetDisplay();
+
+ /**
+ * @copydoc Dali::DisplayConnection::GetDpi
+ */
+ static void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical);
+
+ /**
+ * @copydoc Dali::DisplayConnection::ConsumeEvents
+ */
+ void ConsumeEvents();
+
+ /**
+ * @copydoc Dali::DisplayConnection::InitializeEgl
+ */
+ bool InitializeEgl(EglInterface& egl);
+
+ void SetSurfaceType( RenderSurface::Type type );
+
+public:
+
+ /**
+ * Destructor
+ */
+ virtual ~DisplayConnectionX11();
+
+protected:
+
+ // Undefined
+ DisplayConnectionX11(const DisplayConnectionX11&) = delete;
+
+ // Undefined
+ DisplayConnectionX11& operator=(const DisplayConnectionX11& rhs) = delete;
+
+private:
+
+public:
+
+ XDisplay* mDisplay; ///< X-display for rendering
+
+};
+
+} // namespace Adaptor
+
+} // namespace internal
+
+} // namespace Dali
+
+#endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_IMPL_ECORE_X_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/event-handler.h>
+
+// EXTERNAL INCLUDES
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Ecore_Input.h>
+#include <Ecore_IMF.h>
+
+#include <X11/Xlib.h>
+#include <X11/extensions/XInput2.h>
+#include <X11/extensions/XI2.h>
+
+#include <cstring>
+
+#include <sys/time.h>
+
+#ifndef DALI_PROFILE_UBUNTU
+#include <vconf.h>
+#include <vconf-keys.h>
+#endif // DALI_PROFILE_UBUNTU
+
+#ifdef DALI_ELDBUS_AVAILABLE
+#include <Eldbus.h>
+#endif // DALI_ELDBUS_AVAILABLE
+
+#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/public-api/events/touch-point.h>
+#include <dali/public-api/events/key-event.h>
+#include <dali/public-api/events/wheel-event.h>
+#include <dali/integration-api/debug.h>
+#include <dali/integration-api/events/key-event-integ.h>
+#include <dali/integration-api/events/touch-event-integ.h>
+#include <dali/integration-api/events/hover-event-integ.h>
+#include <dali/integration-api/events/wheel-event-integ.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/gesture-manager.h>
+#include <dali/internal/window-system/ubuntu-x11/window-render-surface-x.h>
+#include <dali/internal/clipboard/common/clipboard-impl.h>
+#include <dali/internal/input/common/key-impl.h>
+#include <dali/internal/input/common/physical-keyboard-impl.h>
+#include <dali/internal/styling/common/style-monitor-impl.h>
+#include <dali/internal/system/common/core-event-interface.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+#if defined(DEBUG_ENABLED)
+namespace
+{
+Integration::Log::Filter* gTouchEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_TOUCH");
+Integration::Log::Filter* gClientMessageLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_CLIENT_MESSAGE");
+Integration::Log::Filter* gDragAndDropLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DND");
+Integration::Log::Filter* gImfLogging = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_IMF");
+Integration::Log::Filter* gSelectionEventLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_SELECTION");
+} // unnamed namespace
+#endif
+
+
+namespace
+{
+
+const char * DETENT_DEVICE_NAME = "tizen_detent";
+const std::string DEFAULT_DEVICE_NAME = "";
+const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE;
+const Device::Subclass::Type DEFAULT_DEVICE_SUBCLASS = Device::Subclass::NONE;
+
+// DBUS accessibility
+#define A11Y_BUS "org.a11y.Bus"
+#define A11Y_INTERFACE "org.a11y.Bus"
+#define A11Y_PATH "/org/a11y/bus"
+#define A11Y_GET_ADDRESS "GetAddress"
+#define BUS "com.samsung.EModule"
+#define INTERFACE "com.samsung.GestureNavigation"
+#define PATH "/com/samsung/GestureNavigation"
+#define SIGNAL "GestureDetected"
+
+#ifndef DALI_PROFILE_UBUNTU
+const char * DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced.
+#endif // DALI_PROFILE_UBUNTU
+
+const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 );
+
+#ifndef DALI_PROFILE_UBUNTU
+const char * CLIPBOARD_ATOM = "CBHM_MSG";
+const char * CLIPBOARD_SET_OWNER_MESSAGE = "SET_OWNER";
+#endif // DALI_PROFILE_UBUNTU
+
+/// The atoms required by Ecore for Drag & Drop behaviour.
+Ecore_X_Atom DRAG_AND_DROP_ATOMS[] =
+{
+ ECORE_X_ATOM_XDND_ACTION_COPY,
+};
+
+/// The types that we support.
+const char * DRAG_AND_DROP_TYPES[] =
+{
+ ECORE_X_SELECTION_TARGET_UTF8_STRING,
+};
+
+const unsigned int DRAG_AND_DROP_ATOMS_NUMBER = sizeof( DRAG_AND_DROP_ATOMS ) / sizeof( Ecore_X_Atom );
+const unsigned int DRAG_AND_DROP_TYPES_NUMBER = sizeof( DRAG_AND_DROP_TYPES ) / sizeof( const char * );
+
+const unsigned int BYTES_PER_CHARACTER_FOR_ATTRIBUTES = 3;
+
+#ifdef DALI_ELDBUS_AVAILABLE
+// DBus gesture string matching lists.
+// TODO: This needs moving to its own module.
+const char * ElDBusAccessibilityFingerCountStrings[] =
+{
+ "OneFinger",
+ "TwoFingers",
+ "ThreeFingers"
+};
+const unsigned int FingerCountStringsTotal = sizeof( ElDBusAccessibilityFingerCountStrings ) / sizeof( ElDBusAccessibilityFingerCountStrings[0] );
+enum GestureType
+{
+ GESTURE_TYPE_NONE,
+ GESTURE_TYPE_HOVER,
+ GESTURE_TYPE_SINGLE_TAP,
+ GESTURE_TYPE_DOUBLE_TAP,
+ GESTURE_TYPE_TRIPLE_TAP
+};
+struct GestureTypeTable
+{
+ const char* name;
+ const GestureType type;
+};
+GestureTypeTable ElDBusAccessibilityFullEventTypeStrings[] =
+{
+ { "Hover", GESTURE_TYPE_HOVER },
+ { "SingleTap", GESTURE_TYPE_SINGLE_TAP },
+ { "DoubleTap", GESTURE_TYPE_DOUBLE_TAP },
+ { "TripleTap", GESTURE_TYPE_TRIPLE_TAP }
+};
+const unsigned int FullEventTypeStringsTotal = sizeof( ElDBusAccessibilityFullEventTypeStrings ) / sizeof( ElDBusAccessibilityFullEventTypeStrings[0] );
+enum SubGestureType
+{
+ SUB_GESTURE_TYPE_NONE,
+ SUB_GESTURE_TYPE_FLICK
+};
+struct SubGestureTypeTable
+{
+ const char* name;
+ const SubGestureType type;
+};
+SubGestureTypeTable ElDBusAccessibilityDirectionalEventTypeStrings[] =
+{
+ { "Flick", SUB_GESTURE_TYPE_FLICK }
+};
+const unsigned int DirectionalEventTypeStringsTotal = sizeof( ElDBusAccessibilityDirectionalEventTypeStrings ) / sizeof( ElDBusAccessibilityDirectionalEventTypeStrings[0] );
+enum GestureDirection
+{
+ GESTURE_DIRECTION_NONE,
+ GESTURE_DIRECTION_UP,
+ GESTURE_DIRECTION_DOWN,
+ GESTURE_DIRECTION_LEFT,
+ GESTURE_DIRECTION_RIGHT,
+ GESTURE_DIRECTION_UP_RETURN,
+ GESTURE_DIRECTION_DOWN_RETURN,
+ GESTURE_DIRECTION_LEFT_RETURN,
+ GESTURE_DIRECTION_RIGHT_RETURN
+};
+struct GestureDirectionTable
+{
+ const char* name;
+ const GestureDirection direction;
+};
+GestureDirectionTable ElDBusAccessibilityDirectionStrings[] =
+{
+ { "Up", GESTURE_DIRECTION_UP },
+ { "Down", GESTURE_DIRECTION_DOWN },
+ { "Left", GESTURE_DIRECTION_LEFT },
+ { "Right", GESTURE_DIRECTION_RIGHT },
+ { "UpReturn", GESTURE_DIRECTION_UP_RETURN },
+ { "DownReturn", GESTURE_DIRECTION_DOWN_RETURN },
+ { "LeftReturn", GESTURE_DIRECTION_LEFT_RETURN },
+ { "RightReturn", GESTURE_DIRECTION_RIGHT_RETURN }
+};
+const unsigned int DirectionStringsTotal = sizeof( ElDBusAccessibilityDirectionStrings ) / sizeof( ElDBusAccessibilityDirectionStrings[0] );
+#endif // DALI_ELDBUS_AVAILABLE
+
+/**
+ * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h.
+ * This function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Modifiers enums.
+ * @param[in] ecoreModifier the Ecore_Event_Modifier input.
+ * @return the Ecore_IMF_Keyboard_Modifiers output.
+ */
+Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier)
+{
+ int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE.
+
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN;
+ }
+
+ if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR )
+ {
+ modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR;
+ }
+
+ return static_cast<Ecore_IMF_Keyboard_Modifiers>( modifier );
+}
+
+
+// Copied from x server
+static unsigned int GetCurrentMilliSeconds(void)
+{
+ struct timeval tv;
+
+ struct timespec tp;
+ static clockid_t clockid;
+
+ if (!clockid)
+ {
+#ifdef CLOCK_MONOTONIC_COARSE
+ if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 &&
+ (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0)
+ {
+ clockid = CLOCK_MONOTONIC_COARSE;
+ }
+ else
+#endif
+ if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0)
+ {
+ clockid = CLOCK_MONOTONIC;
+ }
+ else
+ {
+ clockid = ~0L;
+ }
+ }
+ if (clockid != ~0L && clock_gettime(clockid, &tp) == 0)
+ {
+ return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
+ }
+
+ gettimeofday(&tv, NULL);
+ return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+}
+
+} // unnamed namespace
+
+// Impl to hide EFL implementation.
+struct EventHandler::Impl
+{
+ // Construction & Destruction
+
+ /**
+ * Constructor
+ */
+ Impl( EventHandler* handler, Ecore_X_Window window )
+ : mHandler( handler ),
+ mEcoreEventHandler(),
+ mWindow( window ),
+ mXiDeviceId( 0 )
+#ifdef DALI_ELDBUS_AVAILABLE
+ , mSessionConnection( NULL ),
+ mA11yConnection( NULL )
+#endif
+ {
+ // Only register for touch and key events if we have a window
+ if ( window != 0 )
+ {
+ // Register Touch events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_OUT, EcoreEventMouseButtonUp, handler ) ); // process mouse out event like up event
+
+ // Register Mouse wheel events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, handler ) );
+
+ // Register Key events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, handler ) );
+
+ // Register Focus events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_IN, EcoreEventWindowFocusIn, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_OUT, EcoreEventWindowFocusOut, handler ) );
+
+ // Register Window damage events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DAMAGE, EcoreEventWindowDamaged, handler ) );
+
+ // Enable Drag & Drop and register DnD events
+ ecore_x_dnd_aware_set( window, EINA_TRUE );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_ENTER, EcoreEventDndEnter, handler) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_POSITION, EcoreEventDndPosition, handler) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_LEAVE, EcoreEventDndLeave, handler) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_DROP, EcoreEventDndDrop, handler) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_FINISHED, EcoreEventDndFinished, handler) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_XDND_STATUS, EcoreEventDndStatus, handler) );
+
+ // Register Client message events - accessibility etc.
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, handler ) );
+
+ // Register Selection event - clipboard selection, Drag & Drop selection etc.
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_CLEAR, EcoreEventSelectionClear, handler ) );
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_NOTIFY, EcoreEventSelectionNotify, handler ) );
+
+ // Initialize Xi2 system
+ Display* display = static_cast< Display* >(ecore_x_display_get());
+ Ecore_X_Window rootWindow = ecore_x_window_root_first_get();
+ int opcode = 0, event = 0, error = 0;
+ int major = XI_2_Major;
+ int minor = XI_2_Minor;
+ int deviceCount = 0;
+ XIEventMask xiEventMask;
+
+ // Check if X input extension available
+ if( XQueryExtension( display, "XInputExtension", &opcode, &event, &error ) )
+ {
+ // We support version 2.0
+ if( XIQueryVersion( display, &major, &minor ) != BadRequest )
+ {
+ xiEventMask.deviceid = XIAllDevices;
+
+ // Check device id
+ bool match = false;
+ XIDeviceInfo* deviceInfo = NULL;
+ deviceInfo = XIQueryDevice( display, XIAllDevices, &deviceCount );
+
+ for( int i = 0; i < deviceCount; i++ )
+ {
+ if( !strncmp( deviceInfo[i].name, DETENT_DEVICE_NAME, strlen( DETENT_DEVICE_NAME ) ) )
+ {
+ xiEventMask.deviceid = deviceInfo[i].deviceid;
+ match = true;
+ break;
+ }
+ }
+
+ if( match )
+ {
+ mXiDeviceId = xiEventMask.deviceid;
+
+ // SelectXi2Event
+ Dali::Vector< unsigned char > mask;
+ std::size_t xiMaskLen = XIMaskLen( XI_LASTEVENT );
+ mask.Reserve( xiMaskLen );
+ xiEventMask.mask = mask.Begin();
+
+ XISetMask( xiEventMask.mask, XI_RawMotion );
+
+ xiEventMask.mask_len = xiMaskLen * sizeof( unsigned char );
+
+ int ret = XISelectEvents( display, rootWindow, &xiEventMask, 1 );
+ if( ret == 0 )
+ {
+ // Register custom wheel events
+ mEcoreEventHandler.push_back( ecore_event_handler_add( ECORE_X_EVENT_GENERIC, EcoreEventCustomWheel, handler ) );
+ }
+ else
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to Select Events\n" );
+ }
+ }
+
+ if( deviceInfo != NULL )
+ {
+ XIFreeDeviceInfo( deviceInfo );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to query XI Version\n" );
+ }
+ }
+ else
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Failed to query XInputExtension\n" );
+ }
+
+#ifndef DALI_PROFILE_UBUNTU
+ // Register Vconf notify - font name, font size and style
+ vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, handler );
+ vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, handler );
+#endif // DALI_PROFILE_UBUNTU
+
+#ifdef DALI_ELDBUS_AVAILABLE
+
+ // Initialize ElDBus.
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Starting DBus Initialization\n" );
+ eldbus_init();
+
+ mSessionConnection = eldbus_connection_get( ELDBUS_CONNECTION_TYPE_SESSION );
+
+ Eldbus_Object *a11yObject = eldbus_object_get( mSessionConnection, A11Y_BUS, A11Y_PATH );
+ Eldbus_Proxy *elDBusManager = eldbus_proxy_get( a11yObject, A11Y_INTERFACE );
+
+ // Pass in handler in the cb_data field so we can access the accessibility adaptor within the callback.
+ eldbus_proxy_call( elDBusManager, A11Y_GET_ADDRESS, EcoreElDBusInitialisation, handler, -1, "" );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Finished DBus Initialization\n" );
+
+#endif // DALI_ELDBUS_AVAILABLE
+ }
+ }
+
+ /**
+ * Destructor
+ */
+ ~Impl()
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged );
+ vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged );
+#endif // DALI_PROFILE_UBUNTU
+
+ for( std::vector<Ecore_Event_Handler*>::iterator iter = mEcoreEventHandler.begin(), endIter = mEcoreEventHandler.end(); iter != endIter; ++iter )
+ {
+ ecore_event_handler_del( *iter );
+ }
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Close down ElDBus
+ if( mA11yConnection )
+ {
+ eldbus_connection_unref( mA11yConnection );
+ }
+
+ if( mSessionConnection )
+ {
+ eldbus_connection_unref( mSessionConnection );
+ }
+
+ eldbus_shutdown();
+#endif // DALI_ELDBUS_AVAILABLE
+ }
+
+ // Static methods
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Touch Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a touch down is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == handler->mImpl->mWindow )
+ {
+ PointState::Type state ( PointState::DOWN );
+
+ // Check if the buttons field is set and ensure it's the primary touch button.
+ // If this event was triggered by buttons other than the primary button (used for touch), then
+ // just send an interrupted event to Core.
+ if ( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) )
+ {
+ state = PointState::INTERRUPTED;
+ }
+
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( state );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a touch up is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Button *touchEvent( (Ecore_Event_Mouse_Button*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == handler->mImpl->mWindow )
+ {
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( PointState::UP );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a touch motion is received.
+ */
+ static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Move *touchEvent( (Ecore_Event_Mouse_Move*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( touchEvent->window == handler->mImpl->mWindow )
+ {
+ Integration::Point point;
+ point.SetDeviceId( touchEvent->multi.device );
+ point.SetState( PointState::MOTION );
+ point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) );
+ point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) );
+ point.SetPressure( touchEvent->multi.pressure );
+ point.SetAngle( Degree( touchEvent->multi.angle ) );
+ handler->SendEvent( point, touchEvent->timestamp );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Wheel Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a mouse wheel is received.
+ */
+ static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event )
+ {
+ Ecore_Event_Mouse_Wheel *mouseWheelEvent( (Ecore_Event_Mouse_Wheel*)event );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT Ecore_Event_Mouse_Wheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z );
+
+ EventHandler* handler( (EventHandler*)data );
+ if ( mouseWheelEvent->window == handler->mImpl->mWindow )
+ {
+ WheelEvent wheelEvent( WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp );
+ handler->SendWheelEvent( wheelEvent );
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a custom wheel is received.
+ */
+ static Eina_Bool EcoreEventCustomWheel( void* data, int type, void* event )
+ {
+ Ecore_X_Event_Generic *genericEvent( (Ecore_X_Event_Generic*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ switch( genericEvent->evtype )
+ {
+ case XI_RawMotion:
+ {
+ XIRawEvent* xiRawEvent = static_cast< XIRawEvent* >( genericEvent->data );
+ unsigned int timeStamp = 0;
+
+ if( xiRawEvent->deviceid != handler->mImpl->mXiDeviceId )
+ {
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ // X(0): rotate: NOT USED
+ // Y(1): timestamp
+ // Z(2): direction
+
+ double* value = xiRawEvent->raw_values;
+
+ if( XIMaskIsSet( xiRawEvent->valuators.mask, 1) )
+ {
+ timeStamp = static_cast< unsigned int >( *(value + 1) );
+ }
+
+ if( XIMaskIsSet( xiRawEvent->valuators.mask, 2) )
+ {
+ // if z == 1, clockwise
+ // otherwise counter-clockwise
+ int z = static_cast< int >( *(value + 2) );
+
+ // In DALi, positive value means clockwise, and negative value means counter-clockwise
+ if( z == 0 )
+ {
+ z = -1;
+ }
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventCustomWheel: z: %d\n", z );
+
+ WheelEvent wheelEvent( WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2(0.0f, 0.0f), z, timeStamp );
+ handler->SendWheelEvent( wheelEvent );
+ }
+ break;
+ }
+ default:
+ {
+ break;
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Key Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a key down is received.
+ */
+ static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyDown \n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
+ bool eventHandled( false );
+
+ // If a device key then skip ecore_imf_context_filter_event.
+ if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
+ {
+ Ecore_IMF_Context* imfContext = NULL;
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+ }
+
+ if ( imfContext )
+ {
+ // We're consuming key down event so we have to pass to IMF so that it can parse it as well.
+ Ecore_IMF_Event_Key_Down ecoreKeyDownEvent;
+ ecoreKeyDownEvent.keyname = keyEvent->keyname;
+ ecoreKeyDownEvent.key = keyEvent->key;
+ ecoreKeyDownEvent.string = keyEvent->string;
+ ecoreKeyDownEvent.compose = keyEvent->compose;
+ ecoreKeyDownEvent.timestamp = keyEvent->timestamp;
+ ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
+ ecoreKeyDownEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
+#ifdef ECORE_IMF_1_13
+ ecoreKeyDownEvent.dev_name = "";
+ ecoreKeyDownEvent.dev_class = ECORE_IMF_DEVICE_CLASS_KEYBOARD;
+ ecoreKeyDownEvent.dev_subclass = ECORE_IMF_DEVICE_SUBCLASS_NONE;
+#endif // ECORE_IMF_1_13
+
+ eventHandled = ecore_imf_context_filter_event( imfContext,
+ ECORE_IMF_EVENT_KEY_DOWN,
+ (Ecore_IMF_Event *) &ecoreKeyDownEvent );
+
+ // If the event has not been handled by IMF then check if we should reset our IMF context
+ if( !eventHandled )
+ {
+ if ( !strcmp( keyEvent->keyname, "Escape" ) ||
+ !strcmp( keyEvent->keyname, "Return" ) ||
+ !strcmp( keyEvent->keyname, "KP_Enter" ) )
+ {
+ ecore_imf_context_reset( imfContext );
+ }
+ }
+ }
+ }
+
+ // If the event wasn't handled then we should send a key event.
+ if ( !eventHandled )
+ {
+ if ( keyEvent->window == handler->mImpl->mWindow )
+ {
+ std::string keyName( keyEvent->keyname );
+ std::string keyString( "" );
+ int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
+ int modifier( keyEvent->modifiers );
+ unsigned long time = keyEvent->timestamp;
+
+ // Ensure key event string is not NULL as keys like SHIFT have a null string.
+ if ( keyEvent->string )
+ {
+ keyString = keyEvent->string;
+ }
+
+ Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Down, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS );
+ handler->SendEvent( keyEvent );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a key up is received.
+ */
+ static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventKeyUp \n" );
+
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_Event_Key *keyEvent( (Ecore_Event_Key*)event );
+ bool eventHandled( false );
+
+ // Device keys like Menu, home, back button must skip ecore_imf_context_filter_event.
+ if ( ! KeyLookup::IsDeviceButton( keyEvent->keyname ) )
+ {
+ Ecore_IMF_Context* imfContext = NULL;
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ imfContext = reinterpret_cast<Ecore_IMF_Context*>(ImfManager::GetImplementation( imfManager ).GetContext());
+ }
+
+ if ( imfContext )
+ {
+ // We're consuming key up event so we have to pass to IMF so that it can parse it as well.
+ Ecore_IMF_Event_Key_Up ecoreKeyUpEvent;
+ ecoreKeyUpEvent.keyname = keyEvent->keyname;
+ ecoreKeyUpEvent.key = keyEvent->key;
+ ecoreKeyUpEvent.string = keyEvent->string;
+ ecoreKeyUpEvent.compose = keyEvent->compose;
+ ecoreKeyUpEvent.timestamp = keyEvent->timestamp;
+ ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier ( keyEvent->modifiers );
+ ecoreKeyUpEvent.locks = (Ecore_IMF_Keyboard_Locks) ECORE_IMF_KEYBOARD_LOCK_NONE;
+#ifdef ECORE_IMF_1_13
+ ecoreKeyUpEvent.dev_name = "";
+#endif // ECORE_IMF_1_13
+
+ eventHandled = ecore_imf_context_filter_event( imfContext,
+ ECORE_IMF_EVENT_KEY_UP,
+ (Ecore_IMF_Event *) &ecoreKeyUpEvent );
+ }
+ }
+
+ // If the event wasn't handled then we should send a key event.
+ if ( !eventHandled )
+ {
+ if ( keyEvent->window == handler->mImpl->mWindow )
+ {
+ std::string keyName( keyEvent->keyname );
+ std::string keyString( "" );
+ int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname);
+ int modifier( keyEvent->modifiers );
+ unsigned long time( keyEvent->timestamp );
+
+ // Ensure key event string is not NULL as keys like SHIFT have a null string.
+ if ( keyEvent->string )
+ {
+ keyString = keyEvent->string;
+ }
+
+ Integration::KeyEvent keyEvent(keyName, keyString, keyCode, modifier, time, Integration::KeyEvent::Up, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS );
+
+ handler->SendEvent( keyEvent );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Window Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when the window gains focus.
+ */
+ static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event )
+ {
+ Ecore_X_Event_Window_Focus_In* focusInEvent( (Ecore_X_Event_Window_Focus_In*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusIn \n" );
+
+ // If the window gains focus and we hid the keyboard then show it again.
+ if ( focusInEvent->win == handler->mImpl->mWindow )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT EcoreEventWindowFocusIn - >>WindowFocusGained \n" );
+
+ if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
+ {
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
+ if( imfManagerImpl.RestoreAfterFocusLost() )
+ {
+ imfManagerImpl.Activate();
+ }
+ }
+ }
+ // No need to connect callbacks as KeyboardStatusChanged will be called.
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window loses focus.
+ */
+ static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event )
+ {
+ Ecore_X_Event_Window_Focus_Out* focusOutEvent( (Ecore_X_Event_Window_Focus_Out*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "EVENT >>EcoreEventWindowFocusOut \n" );
+
+ // If the window loses focus then hide the keyboard.
+ if ( focusOutEvent->win == handler->mImpl->mWindow )
+ {
+ if ( ImfManager::IsAvailable() /* Only get the ImfManager if it's available as we do not want to create it */ )
+ {
+ Dali::ImfManager imfManager( ImfManager::Get() );
+ if ( imfManager )
+ {
+ ImfManager& imfManagerImpl( ImfManager::GetImplementation( imfManager ) );
+ if( imfManagerImpl.RestoreAfterFocusLost() )
+ {
+ imfManagerImpl.Deactivate();
+ }
+ }
+ }
+
+ // Clipboard don't support that whether clipboard is shown or not. Hide clipboard.
+ Dali::Clipboard clipboard = Clipboard::Get();
+ clipboard.HideClipboard();
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window is damaged.
+ */
+ static Eina_Bool EcoreEventWindowDamaged(void *data, int type, void *event)
+ {
+ Ecore_X_Event_Window_Damage* windowDamagedEvent( (Ecore_X_Event_Window_Damage*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if( windowDamagedEvent->win == handler->mImpl->mWindow )
+ {
+ DamageArea area;
+ area.x = windowDamagedEvent->x;
+ area.y = windowDamagedEvent->y;
+ area.width = windowDamagedEvent->w;
+ area.height = windowDamagedEvent->h;
+
+ handler->SendEvent( area );
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the window properties are changed.
+ * We are only interested in the font change.
+ */
+
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Drag & Drop Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Called when a dragged item enters our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndEnter( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO( gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndEnter\n" );
+
+ Ecore_X_Event_Xdnd_Enter* enterEvent( (Ecore_X_Event_Xdnd_Enter*) event );
+ EventHandler* handler( (EventHandler*)data );
+ Ecore_X_Window window ( handler->mImpl->mWindow );
+
+ if ( enterEvent->win == window )
+ {
+ DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
+
+ // Check whether the Drag & Drop detector has Drag & Drop behaviour enabled before we accept.
+ if ( dndDetector && dndDetector->IsEnabled() )
+ {
+ // Tell Ecore that we want to enable drop in the entire window.
+ Ecore_X_Rectangle rect;
+ rect.x = rect.y = 0;
+ ecore_x_window_geometry_get( window, NULL, NULL, (int*)&rect.width, (int*)&rect.height );
+
+ // Tell Ecore that we are able to process a drop.
+ ecore_x_dnd_send_status( EINA_TRUE, EINA_FALSE, rect, ECORE_X_ATOM_XDND_DROP );
+
+ // Register the required atoms and types.
+ ecore_x_dnd_actions_set( window, DRAG_AND_DROP_ATOMS, DRAG_AND_DROP_ATOMS_NUMBER );
+ ecore_x_dnd_types_set( window, DRAG_AND_DROP_TYPES, DRAG_AND_DROP_TYPES_NUMBER );
+
+ // Request to get the content from Ecore.
+ ecore_x_selection_xdnd_request( window, ECORE_X_SELECTION_TARGET_UTF8_STRING );
+
+ DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndEnter: Requesting Drag & Drop\n" );
+
+ // Clear the previous content
+ dndDetector->ClearContent();
+
+ // Emit the entered signal
+ dndDetector->EmitEnteredSignal();
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved within our window.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndPosition( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndPosition\n" );
+
+ Ecore_X_Event_Xdnd_Position* positionEvent( (Ecore_X_Event_Xdnd_Position*) event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( positionEvent->win == handler->mImpl->mWindow )
+ {
+ DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
+
+ // If we have a detector then update its latest position.
+ if ( dndDetector )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::General, "EcoreEventDndPosition: position ( %d x %d )\n", positionEvent->position.x, positionEvent->position.y );
+ dndDetector->SetPosition( Vector2( positionEvent->position.x, positionEvent->position.y ));
+ dndDetector->EmitMovedSignal();
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item leaves our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndLeave( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndLeave\n" );
+
+ Ecore_X_Event_Xdnd_Leave* leaveEvent( (Ecore_X_Event_Xdnd_Leave*) event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( leaveEvent->win == handler->mImpl->mWindow )
+ {
+ DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
+
+ // If we have a detector then clear its content and emit the exited-signal. Also tell Ecore that we have finished.
+ if ( dndDetector )
+ {
+ dndDetector->ClearContent();
+ dndDetector->EmitExitedSignal();
+
+ ecore_x_dnd_send_finished();
+
+ DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndLeave: Finished\n" );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the dragged item is dropped within our window's bounds.
+ * This is when items are dragged INTO our window.
+ */
+ static Eina_Bool EcoreEventDndDrop( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndDrop\n" );
+
+ Ecore_X_Event_Xdnd_Drop* dropEvent ( (Ecore_X_Event_Xdnd_Drop*) event);
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( dropEvent->win == handler->mImpl->mWindow )
+ {
+ DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
+
+ // Something has been dropped, inform the detector (if we have one) and tell Ecore that we have finished.
+ if ( dndDetector )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::General, "EcoreEventDndDrop: position ( %d x %d )\n", dropEvent->position.x, dropEvent->position.y );
+
+ dndDetector->SetPosition( Vector2( dropEvent->position.x, dropEvent->position.y ) );
+ dndDetector->EmitDroppedSignal();
+ ecore_x_dnd_send_finished();
+
+ DALI_LOG_INFO( gDragAndDropLogFilter, Debug::General, "EcoreEventDndDrop: Finished\n" );
+ }
+ }
+
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved from our window and the target window has done processing it.
+ * This is when items are dragged FROM our window.
+ */
+ static Eina_Bool EcoreEventDndFinished( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndFinished\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when a dragged item is moved from our window and the target window has sent us a status.
+ * This is when items are dragged FROM our window.
+ */
+ static Eina_Bool EcoreEventDndStatus( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gDragAndDropLogFilter, Debug::Concise, "EcoreEventDndStatus\n" );
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the client messages (i.e. the accessibility events) are received.
+ */
+ static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Event_Client_Message* clientMessageEvent( (Ecore_X_Event_Client_Message*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if (clientMessageEvent->message_type == ECORE_X_ATOM_E_ILLUME_ACCESS_CONTROL)
+ {
+ if ( ( (unsigned int)clientMessageEvent->data.l[0] == handler->mImpl->mWindow ) && handler->mAccessibilityAdaptor )
+ {
+ AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
+
+ if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_SCROLL)
+ {
+ // 2 finger touch & move, 2 finger flick
+
+ // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
+ // x : e->data.l[3]
+ // y : e->data.l[4]
+ TouchPoint::State state(TouchPoint::Down);
+
+ if ((unsigned int)clientMessageEvent->data.l[2] == 0)
+ {
+ state = TouchPoint::Down; // mouse down
+ }
+ else if ((unsigned int)clientMessageEvent->data.l[2] == 1)
+ {
+ state = TouchPoint::Motion; // mouse move
+ }
+ else if ((unsigned int)clientMessageEvent->data.l[2] == 2)
+ {
+ state = TouchPoint::Up; // mouse up
+ }
+ else
+ {
+ state = TouchPoint::Interrupted; // error
+ }
+
+ DALI_LOG_INFO(gClientMessageLogFilter, Debug::General,
+ "[%s:%d] [%d] %d, %d\n", __FUNCTION__, __LINE__,
+ (unsigned int)clientMessageEvent->data.l[2],
+ (unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4]);
+
+ // Send touch event to accessibility adaptor.
+ TouchPoint point( 0, state, (float)clientMessageEvent->data.l[3], (float)clientMessageEvent->data.l[4] );
+
+ // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
+ accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_MOUSE)
+ {
+ // 1 finger double tap and hold
+
+ // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
+ // x : e->data.l[3]
+ // y : e->data.l[4]
+ TouchPoint::State state(TouchPoint::Down);
+
+ if ((unsigned int)clientMessageEvent->data.l[2] == 0)
+ {
+ state = TouchPoint::Down; // mouse down
+ }
+ else if ((unsigned int)clientMessageEvent->data.l[2] == 1)
+ {
+ state = TouchPoint::Motion; // mouse move
+ }
+ else if ((unsigned int)clientMessageEvent->data.l[2] == 2)
+ {
+ state = TouchPoint::Up; // mouse up
+ }
+ else
+ {
+ state = TouchPoint::Interrupted; // error
+ }
+
+ DALI_LOG_INFO(gClientMessageLogFilter, Debug::General,
+ "[%s:%d] [%d] %d, %d\n", __FUNCTION__, __LINE__,
+ (unsigned int)clientMessageEvent->data.l[2],
+ (unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4]);
+
+ // Send touch event to accessibility adaptor.
+ TouchPoint point( 0, state, (float)clientMessageEvent->data.l[3], (float)clientMessageEvent->data.l[4] );
+
+ // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
+ accessibilityAdaptor->HandleActionTouchEvent( point, GetCurrentMilliSeconds() );
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_BACK)
+ {
+ // 2 finger circle draw, do back
+ accessibilityAdaptor->HandleActionBackEvent();
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_NEXT)
+ {
+ // one finger flick down
+ // focus next object
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionNextEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_PREV)
+ {
+ // one finger flick up
+ // focus previous object
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionPreviousEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_ACTIVATE)
+ {
+ // one finger double tap
+ // same as one finger tap in normal mode (i.e. execute focused actor)
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionActivateEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ)
+ {
+ // one finger tap
+ // focus & read an actor at ( e->data.l[2], e->data.l[3] ) position according to finger
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionReadEvent((unsigned int)clientMessageEvent->data.l[2], (unsigned int)clientMessageEvent->data.l[3], true /* allow read again*/);
+ }
+ }
+#if defined(DALI_PROFILE_MOBILE)
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_OVER)
+ {
+ // one finger tap & move
+ // mouse state : e->data.l[2] (0: mouse down, 1: mouse move, 2: mouse up)
+ // x : e->data.l[3]
+ // y : e->data.l[4]
+ // focus & read an actor at (x, y) position according to finger
+ if(accessibilityAdaptor && (unsigned int)clientMessageEvent->data.l[2] == 1 /*only work for move event*/)
+ {
+ accessibilityAdaptor->HandleActionReadEvent((unsigned int)clientMessageEvent->data.l[3], (unsigned int)clientMessageEvent->data.l[4], false /* not allow read again*/);
+ }
+ }
+#endif
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ_NEXT)
+ {
+ // one finger flick right
+ // focus next object
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionReadNextEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_READ_PREV)
+ {
+ // one finger flick left
+ // focus previous object
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionReadPreviousEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_UP)
+ {
+ // double down and move (right, up)
+ // change slider value
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionUpEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_DOWN)
+ {
+ // double down and move (left, down)
+ // change slider value
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionDownEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_ENABLE)
+ {
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionEnableEvent();
+ }
+ }
+ else if((unsigned int)clientMessageEvent->data.l[1] == ECORE_X_ATOM_E_ILLUME_ACCESS_ACTION_DISABLE)
+ {
+ if(accessibilityAdaptor)
+ {
+ accessibilityAdaptor->HandleActionDisableEvent();
+ }
+ }
+ // TODO: some more actions could be added later
+ }
+ }
+ else if(clientMessageEvent->message_type == ecore_x_atom_get(CLIPBOARD_ATOM))
+ {
+ std::string message(clientMessageEvent->data.b);
+ if( message == CLIPBOARD_SET_OWNER_MESSAGE)
+ {
+ // Claim the ownership of the SECONDARY selection.
+ ecore_x_selection_secondary_set(handler->mImpl->mWindow, "", 1);
+
+ // Show the clipboard window
+ Dali::Clipboard clipboard = Dali::Clipboard::Get();
+ clipboard.ShowClipboard();
+ }
+ }
+ else if( clientMessageEvent->message_type == ECORE_X_ATOM_E_WINDOW_ROTATION_CHANGE_PREPARE )
+ {
+ RotationEvent rotationEvent;
+ rotationEvent.angle = static_cast<int>(clientMessageEvent->data.l[1]);
+ rotationEvent.winResize = static_cast<int>(clientMessageEvent->data.l[2]);
+ rotationEvent.width = static_cast<int>(clientMessageEvent->data.l[3]);
+ rotationEvent.height = static_cast<int>(clientMessageEvent->data.l[4]);
+ handler->SendRotationPrepareEvent( rotationEvent );
+ }
+ else if( clientMessageEvent->message_type == ECORE_X_ATOM_E_WINDOW_ROTATION_CHANGE_REQUEST )
+ {
+ handler->SendRotationRequestEvent();
+ }
+
+#endif // DALI_PROFILE_UBUNTU
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // ElDBus Accessibility Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ // Callback for Ecore ElDBus accessibility events.
+ static void OnEcoreElDBusAccessibilityNotification( void *context EINA_UNUSED, const Eldbus_Message *message )
+ {
+ EventHandler* handler = static_cast< EventHandler* >( context );
+ // Ignore any accessibility events when paused.
+ if( handler->mPaused )
+ {
+ return;
+ }
+
+ if ( !handler->mAccessibilityAdaptor )
+ {
+ DALI_LOG_ERROR( "Invalid accessibility adaptor\n" );
+ return;
+ }
+
+ AccessibilityAdaptor* accessibilityAdaptor( &AccessibilityAdaptor::GetImplementation( handler->mAccessibilityAdaptor ) );
+ if ( !accessibilityAdaptor )
+ {
+ DALI_LOG_ERROR( "Cannot access accessibility adaptor\n" );
+ return;
+ }
+
+ const char *gestureName;
+ int xS, yS, xE, yE;
+ unsigned int state;
+
+ // The string defines the arg-list's respective types.
+ if( !eldbus_message_arguments_get( message, "siiiiu", &gestureName, &xS, &yS, &xE, &yE, &state ) )
+ {
+ DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" );
+ }
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Name: %s Args: %d,%d,%d,%d State: %d\n", gestureName, xS, yS, xE, yE );
+
+ unsigned int fingers = 0;
+ char* stringPosition = ( char* )gestureName;
+
+ // Check how many fingers the gesture uses.
+ for( unsigned int i = 0; i < FingerCountStringsTotal; ++i )
+ {
+ unsigned int matchLength = strlen( ElDBusAccessibilityFingerCountStrings[ i ] );
+ if( strncmp( gestureName, ElDBusAccessibilityFingerCountStrings[ i ], matchLength ) == 0 )
+ {
+ fingers = i + 1;
+ stringPosition += matchLength;
+ break;
+ }
+ }
+
+ if( fingers == 0 )
+ {
+ // Error: invalid gesture.
+ return;
+ }
+
+ GestureType gestureType = GESTURE_TYPE_NONE;
+ SubGestureType subGestureType = SUB_GESTURE_TYPE_NONE;
+ GestureDirection direction = GESTURE_DIRECTION_NONE;
+
+ // Check for full gesture type names first.
+ for( unsigned int i = 0; i < FullEventTypeStringsTotal; ++i )
+ {
+ unsigned int matchLength = strlen( ElDBusAccessibilityFullEventTypeStrings[ i ].name );
+ if( strncmp( stringPosition, ElDBusAccessibilityFullEventTypeStrings[ i ].name, matchLength ) == 0 )
+ {
+ gestureType = ElDBusAccessibilityFullEventTypeStrings[ i ].type;
+ break;
+ }
+ }
+
+ // If we didn't find a full gesture, check for sub gesture type names.
+ if( gestureType == GESTURE_TYPE_NONE )
+ {
+ // No full gesture name found, look for partial types.
+ for( unsigned int i = 0; i < DirectionalEventTypeStringsTotal; ++i )
+ {
+ unsigned int matchLength = strlen( ElDBusAccessibilityDirectionalEventTypeStrings[ i ].name );
+ if( strncmp( stringPosition, ElDBusAccessibilityDirectionalEventTypeStrings[ i ].name, matchLength ) == 0 )
+ {
+ subGestureType = ElDBusAccessibilityDirectionalEventTypeStrings[ i ].type;
+ stringPosition += matchLength;
+ break;
+ }
+ }
+
+ if( subGestureType == SUB_GESTURE_TYPE_NONE )
+ {
+ // ERROR: Gesture not recognised.
+ return;
+ }
+
+ // If the gesture was a sub type, get it's respective direction.
+ for( unsigned int i = 0; i < DirectionStringsTotal; ++i )
+ {
+ unsigned int matchLength = strlen( ElDBusAccessibilityDirectionStrings[ i ].name );
+ if( strncmp( stringPosition, ElDBusAccessibilityDirectionStrings[ i ].name, matchLength ) == 0 )
+ {
+ direction = ElDBusAccessibilityDirectionStrings[ i ].direction;
+ stringPosition += matchLength;
+ break;
+ }
+ }
+
+ if( direction == GESTURE_DIRECTION_NONE )
+ {
+ // ERROR: Gesture not recognised.
+ return;
+ }
+ }
+
+ // Action the detected gesture here.
+ if( gestureType != GESTURE_TYPE_NONE )
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Fingers: %d Gesture type: %d\n", fingers, gestureType );
+ }
+ else
+ {
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Got gesture: Fingers: %d Gesture sub type: %d Gesture direction: %d\n",
+ fingers, subGestureType, direction );
+ }
+
+ // Create a touch point object.
+ TouchPoint::State touchPointState( TouchPoint::Down );
+ if ( state == 0 )
+ {
+ touchPointState = TouchPoint::Down; // Mouse down.
+ }
+ else if ( state == 1 )
+ {
+ touchPointState = TouchPoint::Motion; // Mouse move.
+ }
+ else if ( state == 2 )
+ {
+ touchPointState = TouchPoint::Up; // Mouse up.
+ }
+ else
+ {
+ touchPointState = TouchPoint::Interrupted; // Error.
+ }
+
+ // Send touch event to accessibility adaptor.
+ TouchPoint point( 0, touchPointState, (float)xS, (float)yS );
+
+ // Perform actions based on received gestures.
+ // Note: This is seperated from the reading so we can (in future)
+ // have other input readers without changing the below code.
+ switch( fingers )
+ {
+ case 1:
+ {
+ if( gestureType == GESTURE_TYPE_SINGLE_TAP || ( gestureType == GESTURE_TYPE_HOVER && touchPointState == TouchPoint::Motion ) )
+ {
+ // Focus, read out.
+ accessibilityAdaptor->HandleActionReadEvent( (unsigned int)xS, (unsigned int)yS, true /* allow read again */ );
+ }
+ else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
+ {
+ if( false ) // TODO: how to detect double tap + hold?
+ {
+ // Move or drag icon / view more options for selected items.
+ // accessibilityAdaptor->HandleActionTouchEvent( point, GetCurrentMilliSeconds() );
+ }
+ else
+ {
+ // Activate selected item / active edit mode.
+ accessibilityAdaptor->HandleActionActivateEvent();
+ }
+ }
+ else if( gestureType == GESTURE_TYPE_TRIPLE_TAP )
+ {
+ // Zoom
+ accessibilityAdaptor->HandleActionZoomEvent();
+ }
+ else if( subGestureType == SUB_GESTURE_TYPE_FLICK )
+ {
+ if( direction == GESTURE_DIRECTION_LEFT )
+ {
+ // Move to previous item.
+ accessibilityAdaptor->HandleActionReadPreviousEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_RIGHT )
+ {
+ // Move to next item.
+ accessibilityAdaptor->HandleActionReadNextEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_UP )
+ {
+ // Move to next item.
+ accessibilityAdaptor->HandleActionPreviousEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_DOWN )
+ {
+ // Move to next item.
+ accessibilityAdaptor->HandleActionNextEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_LEFT_RETURN )
+ {
+ // Scroll up to the previous page
+ accessibilityAdaptor->HandleActionPageUpEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_RIGHT_RETURN )
+ {
+ // Scroll down to the next page
+ accessibilityAdaptor->HandleActionPageDownEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_UP_RETURN )
+ {
+ // Move to the first item on screen
+ accessibilityAdaptor->HandleActionMoveToFirstEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_DOWN_RETURN )
+ {
+ // Move to the last item on screen
+ accessibilityAdaptor->HandleActionMoveToLastEvent();
+ }
+ }
+ break;
+ }
+
+ case 2:
+ {
+ if( gestureType == GESTURE_TYPE_HOVER )
+ {
+ // In accessibility mode, scroll action should be handled when the currently focused actor is contained in scrollable control
+ accessibilityAdaptor->HandleActionScrollEvent( point, GetCurrentMilliSeconds() );
+ }
+ else if( gestureType == GESTURE_TYPE_SINGLE_TAP )
+ {
+ // Pause/Resume current speech
+ accessibilityAdaptor->HandleActionReadPauseResumeEvent();
+ }
+ else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
+ {
+ // Start/Stop current action
+ accessibilityAdaptor->HandleActionStartStopEvent();
+ }
+ else if( gestureType == GESTURE_TYPE_TRIPLE_TAP )
+ {
+ // Read information from indicator
+ accessibilityAdaptor->HandleActionReadIndicatorInformationEvent();
+ }
+ else if( subGestureType == SUB_GESTURE_TYPE_FLICK )
+ {
+ if( direction == GESTURE_DIRECTION_LEFT )
+ {
+ // Scroll left to the previous page
+ accessibilityAdaptor->HandleActionPageLeftEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_RIGHT )
+ {
+ // Scroll right to the next page
+ accessibilityAdaptor->HandleActionPageRightEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_UP )
+ {
+ // Scroll up the list.
+ accessibilityAdaptor->HandleActionScrollUpEvent();
+ }
+ else if( direction == GESTURE_DIRECTION_DOWN )
+ {
+ // Scroll down the list.
+ accessibilityAdaptor->HandleActionScrollDownEvent();
+ }
+ }
+ break;
+ }
+
+ case 3:
+ {
+ if( gestureType == GESTURE_TYPE_SINGLE_TAP )
+ {
+ // Read from top item on screen continuously.
+ accessibilityAdaptor->HandleActionReadFromTopEvent();
+ }
+ else if( gestureType == GESTURE_TYPE_DOUBLE_TAP )
+ {
+ // Read from next item continuously.
+ accessibilityAdaptor->HandleActionReadFromNextEvent();
+ }
+ break;
+ }
+ }
+ }
+
+ // Callback for to set up Ecore ElDBus for accessibility callbacks.
+ static void EcoreElDBusInitialisation( void *handle, const Eldbus_Message *message, Eldbus_Pending *pending EINA_UNUSED )
+ {
+ Eldbus_Object *object;
+ Eldbus_Proxy *manager;
+ const char *a11yBusAddress = NULL;
+ EventHandler* handler = static_cast< EventHandler* >( handle );
+
+ // The string defines the arg-list's respective types.
+ if( !eldbus_message_arguments_get( message, "s", &a11yBusAddress ) )
+ {
+ DALI_LOG_ERROR( "EcoreElDBusInitialisation: Error getting arguments\n" );
+ }
+
+ DALI_LOG_INFO( gImfLogging, Debug::General, "Ecore ElDBus Accessibility address: %s\n", a11yBusAddress );
+
+ handler->mImpl->mA11yConnection = eldbus_address_connection_get( a11yBusAddress );
+
+ object = eldbus_object_get( handler->mImpl->mA11yConnection, BUS, PATH );
+ manager = eldbus_proxy_get( object, INTERFACE );
+
+ // Pass the callback data through to the signal handler.
+ eldbus_proxy_signal_handler_add( manager, SIGNAL, OnEcoreElDBusAccessibilityNotification, handle );
+ }
+#endif // DALI_ELDBUS_AVAILABLE
+
+ /**
+ * Called when the source window notifies us the content in clipboard is selected.
+ */
+ static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionClear\n" );
+ Ecore_X_Event_Selection_Clear* selectionClearEvent( (Ecore_X_Event_Selection_Clear*) event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( selectionClearEvent->win == handler->mImpl->mWindow )
+ {
+ if ( selectionClearEvent->selection == ECORE_X_SELECTION_SECONDARY )
+ {
+ // Request to get the content from Ecore.
+ ecore_x_selection_secondary_request(selectionClearEvent->win, ECORE_X_SELECTION_TARGET_TEXT);
+ }
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+ /**
+ * Called when the source window sends us about the selected content.
+ * For example, when dragged items are dragged INTO our window or when items are selected in the clipboard.
+ */
+ static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event )
+ {
+ DALI_LOG_INFO(gSelectionEventLogFilter, Debug::Concise, "EcoreEventSelectionNotify\n" );
+
+ Ecore_X_Event_Selection_Notify* selectionNotifyEvent( (Ecore_X_Event_Selection_Notify*) event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if ( selectionNotifyEvent->win == handler->mImpl->mWindow )
+ {
+ Ecore_X_Selection_Data* selectionData( (Ecore_X_Selection_Data*) selectionNotifyEvent->data );
+ if ( selectionData->data )
+ {
+ if ( selectionNotifyEvent->selection == ECORE_X_SELECTION_XDND )
+ {
+ DragAndDropDetectorPtr dndDetector( handler->mDragAndDropDetector );
+
+ // We have got the content that is to be dropped, inform the DndListener (if we have one).
+ if ( dndDetector )
+ {
+ std::string content( (char*) selectionData->data, selectionData->length );
+ dndDetector->SetContent( content );
+
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d):\n" , selectionData->length );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "%s\n", selectionData->data );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
+ }
+ }
+ else if ( selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY )
+ {
+ // We have got the selected content, inform the clipboard event listener (if we have one).
+ if ( handler->mClipboardEventNotifier )
+ {
+ ClipboardEventNotifier& clipboardEventNotifier( ClipboardEventNotifier::GetImplementation( handler->mClipboardEventNotifier ) );
+ std::string content( (char*) selectionData->data, selectionData->length );
+ clipboardEventNotifier.SetContent( content );
+ clipboardEventNotifier.EmitContentSelectedSignal();
+ }
+
+ // Claim the ownership of the SECONDARY selection.
+ ecore_x_selection_secondary_set(handler->mImpl->mWindow, "", 1);
+
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d):\n" , selectionData->length );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "%s\n", selectionData->data );
+ DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "======================================\n" );
+ }
+ }
+ }
+ return ECORE_CALLBACK_PASS_ON;
+ }
+
+
+#ifndef DALI_PROFILE_UBUNTU
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ // Font Callbacks
+ /////////////////////////////////////////////////////////////////////////////////////////////////
+ /**
+ * Called when a font name is changed.
+ */
+ static void VconfNotifyFontNameChanged( keynode_t* node, void* data )
+ {
+ EventHandler* handler = static_cast<EventHandler*>( data );
+ handler->SendEvent( StyleChange::DEFAULT_FONT_CHANGE );
+ }
+
+ /**
+ * Called when a font size is changed.
+ */
+ static void VconfNotifyFontSizeChanged( keynode_t* node, void* data )
+ {
+ DALI_LOG_INFO(gTouchEventLogFilter, Debug::Verbose, "VconfNotifyFontSizeChanged\n" );
+ EventHandler* handler = static_cast<EventHandler*>( data );
+ handler->SendEvent( StyleChange::DEFAULT_FONT_SIZE_CHANGE );
+ }
+#endif // DALI_PROFILE_UBUNTU
+
+ // Data
+ EventHandler* mHandler;
+ std::vector<Ecore_Event_Handler*> mEcoreEventHandler;
+ Ecore_X_Window mWindow;
+ int mXiDeviceId;
+
+#ifdef DALI_ELDBUS_AVAILABLE
+ Eldbus_Connection* mSessionConnection;
+ Eldbus_Connection* mA11yConnection;
+#endif
+};
+
+EventHandler::EventHandler( RenderSurface* surface, CoreEventInterface& coreEventInterface, GestureManager& gestureManager, DamageObserver& damageObserver, DragAndDropDetectorPtr dndDetector )
+: mCoreEventInterface( coreEventInterface ),
+ mGestureManager( gestureManager ),
+ mStyleMonitor( StyleMonitor::Get() ),
+ mDamageObserver( damageObserver ),
+ mRotationObserver( NULL ),
+ mDragAndDropDetector( dndDetector ),
+ mAccessibilityAdaptor( AccessibilityAdaptor::Get() ),
+ mClipboardEventNotifier( ClipboardEventNotifier::Get() ),
+ mClipboard( Clipboard::Get() ),
+ mImpl( NULL ),
+ mPaused( false )
+{
+ Ecore_X_Window window = 0;
+
+ // this code only works with the EcoreX11 RenderSurface so need to downcast
+ ECore::WindowRenderSurface* ecoreSurface = dynamic_cast< ECore::WindowRenderSurface* >( surface );
+ if( ecoreSurface )
+ {
+ // enable multi touch
+ window = ecoreSurface->GetXWindow();
+ }
+
+ mImpl = new Impl(this, window);
+}
+
+EventHandler::~EventHandler()
+{
+ delete mImpl;
+
+ mGestureManager.Stop();
+}
+
+void EventHandler::SendEvent(Integration::Point& point, unsigned long timeStamp)
+{
+ if(timeStamp < 1)
+ {
+ timeStamp = GetCurrentMilliSeconds();
+ }
+
+ Integration::TouchEvent touchEvent;
+ Integration::HoverEvent hoverEvent;
+ Integration::TouchEventCombiner::EventDispatchType type = mCombiner.GetNextTouchEvent(point, timeStamp, touchEvent, hoverEvent);
+ if(type != Integration::TouchEventCombiner::DispatchNone )
+ {
+ DALI_LOG_INFO(gTouchEventLogFilter, Debug::General, "%d: Device %d: Button state %d (%.2f, %.2f)\n", timeStamp, point.GetDeviceId(), point.GetState(), point.GetScreenPosition().x, point.GetScreenPosition().y);
+
+ // First the touch and/or hover event & related gesture events are queued
+ if(type == Integration::TouchEventCombiner::DispatchTouch || type == Integration::TouchEventCombiner::DispatchBoth)
+ {
+ mCoreEventInterface.QueueCoreEvent( touchEvent );
+ mGestureManager.SendEvent(touchEvent);
+ }
+
+ if(type == Integration::TouchEventCombiner::DispatchHover || type == Integration::TouchEventCombiner::DispatchBoth)
+ {
+ mCoreEventInterface.QueueCoreEvent( hoverEvent );
+ }
+
+ // Next the events are processed with a single call into Core
+ mCoreEventInterface.ProcessCoreEvents();
+ }
+}
+
+void EventHandler::SendEvent(Integration::KeyEvent& keyEvent)
+{
+ Dali::PhysicalKeyboard physicalKeyboard = PhysicalKeyboard::Get();
+ if ( physicalKeyboard )
+ {
+ if ( ! KeyLookup::IsDeviceButton( keyEvent.keyName.c_str() ) )
+ {
+ GetImplementation( physicalKeyboard ).KeyReceived( keyEvent.time > 1 );
+ }
+ }
+
+ // Send to KeyEvent Core.
+ mCoreEventInterface.QueueCoreEvent( keyEvent );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::SendWheelEvent( WheelEvent& wheelEvent )
+{
+ // Create WheelEvent and send to Core.
+ Integration::WheelEvent event( static_cast< Integration::WheelEvent::Type >(wheelEvent.type), wheelEvent.direction, wheelEvent.modifiers, wheelEvent.point, wheelEvent.z, wheelEvent.timeStamp );
+ mCoreEventInterface.QueueCoreEvent( event );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::SendEvent( StyleChange::Type styleChange )
+{
+ DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" );
+ GetImplementation( mStyleMonitor ).StyleChanged(styleChange);
+}
+
+void EventHandler::SendEvent( const DamageArea& area )
+{
+ mDamageObserver.OnDamaged( area );
+}
+
+void EventHandler::SendRotationPrepareEvent( const RotationEvent& event )
+{
+ if( mRotationObserver != NULL )
+ {
+ mRotationObserver->OnRotationPrepare( event );
+ }
+}
+
+void EventHandler::SendRotationRequestEvent( )
+{
+ if( mRotationObserver != NULL )
+ {
+ mRotationObserver->OnRotationRequest( );
+ }
+}
+
+void EventHandler::FeedTouchPoint( TouchPoint& point, int timeStamp)
+{
+ Integration::Point convertedPoint( point );
+
+ SendEvent(convertedPoint, timeStamp);
+}
+
+void EventHandler::FeedWheelEvent( WheelEvent& wheelEvent )
+{
+ SendWheelEvent( wheelEvent );
+}
+
+void EventHandler::FeedKeyEvent( KeyEvent& event )
+{
+ Integration::KeyEvent convertedEvent( event );
+ SendEvent( convertedEvent );
+}
+
+void EventHandler::FeedEvent( Integration::Event& event )
+{
+ mCoreEventInterface.QueueCoreEvent( event );
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::Reset()
+{
+ mCombiner.Reset();
+
+ // Any touch listeners should be told of the interruption.
+ Integration::TouchEvent event;
+ Integration::Point point;
+ point.SetState( PointState::INTERRUPTED );
+ event.AddPoint( point );
+
+ // First the touch event & related gesture events are queued
+ mCoreEventInterface.QueueCoreEvent( event );
+ mGestureManager.SendEvent( event );
+
+ // Next the events are processed with a single call into Core
+ mCoreEventInterface.ProcessCoreEvents();
+}
+
+void EventHandler::Pause()
+{
+ mPaused = true;
+ Reset();
+}
+
+void EventHandler::Resume()
+{
+ mPaused = false;
+ Reset();
+}
+
+void EventHandler::SetDragAndDropDetector( DragAndDropDetectorPtr detector )
+{
+ mDragAndDropDetector = detector;
+}
+
+void EventHandler::SetRotationObserver( RotationObserver* observer )
+{
+ mRotationObserver = observer;
+}
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+#ifndef __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+#define __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <Ecore_X.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+class EglImageExtensions;
+
+/**
+ * Dali internal NativeImageSource.
+ */
+class NativeImageSource
+{
+public:
+
+ /**
+ * Create a new NativeImageSource internally.
+ * Depending on hardware the width and height may have to be a power of two.
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] depth color depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return A smart-pointer to a newly allocated image.
+ */
+ static NativeImageSource* New(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+ /**
+ * @copydoc Dali::NativeImageSource::GetNativeImageSource()
+ */
+ Any GetNativeImageSource() const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetPixels()
+ */
+ bool GetPixels(std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& )
+ */
+ bool EncodeToFile(const std::string& filename) const;
+
+ /**
+ * @copydoc Dali::NativeImageSource::SetSource( Any source )
+ */
+ void SetSource( Any source );
+
+ /**
+ * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
+ */
+ bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth );
+
+ /**
+ * destructor
+ */
+ ~NativeImageSource();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionCreate()
+ */
+ bool GlExtensionCreate();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GlExtensionDestroy()
+ */
+ void GlExtensionDestroy();
+
+ /**
+ * @copydoc Dali::NativeImageSource::TargetTexture()
+ */
+ unsigned int TargetTexture();
+
+ /**
+ * @copydoc Dali::NativeImageSource::PrepareTexture()
+ */
+ void PrepareTexture();
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetWidth()
+ */
+ unsigned int GetWidth() const
+ {
+ return mWidth;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::GetHeight()
+ */
+ unsigned int GetHeight() const
+ {
+ return mHeight;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageSource::RequiresBlending()
+ */
+ bool RequiresBlending() const
+ {
+ return mBlendingRequired;
+ }
+
+ /**
+ * @copydoc Dali::NativeImageInterface::GetExtension()
+ */
+ NativeImageInterface::Extension* GetNativeImageInterfaceExtension()
+ {
+ return NULL;
+ }
+
+private:
+
+ /**
+ * Private constructor; @see NativeImageSource::New()
+ * @param[in] width The width of the image.
+ * @param[in] height The height of the image.
+ * @param[in] colour depth of the image.
+ * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ */
+ NativeImageSource(unsigned int width,
+ unsigned int height,
+ Dali::NativeImageSource::ColorDepth depth,
+ Any nativeImageSource);
+
+ /**
+ * 2nd phase construction.
+ */
+ void Initialize();
+
+ /**
+ * Uses X11 to get the default depth.
+ * @param depth the PixelImage depth enum
+ * @return default x11 pixel depth
+ */
+ int GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const;
+
+ /**
+ * Gets the pixmap from the Any parameter
+ * @param pixmap contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty
+ * @return pixmap x11 pixmap
+ */
+ Ecore_X_Pixmap GetPixmapFromAny(Any pixmap) const;
+
+ /**
+ * Given an existing pixmap, the function uses X to find out
+ * the width, heigth and depth of that pixmap.
+ */
+ void GetPixmapDetails();
+
+private:
+
+ unsigned int mWidth; ///< image width
+ unsigned int mHeight; ///< image heights
+ bool mOwnPixmap; ///< Whether we created pixmap or not
+ Ecore_X_Pixmap mPixmap; ///< From Xlib
+ bool mBlendingRequired; ///< Whether blending is required
+ Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image
+ void* mEglImageKHR; ///< From EGL extension
+ EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions
+};
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H__
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/integration-api/x11/ecore-x-render-surface.h>
+
+// EXTERNAL INCLUDES
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#include <X11/extensions/Xfixes.h> // for damage notify
+#include <X11/extensions/Xdamage.h> // for damage notify
+
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/x11/ecore-x-types.h>
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_ECORE_X_RENDER_SURFACE");
+#endif
+
+namespace ECore
+{
+
+EcoreXRenderSurface::EcoreXRenderSurface(Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+: mPosition(positionSize),
+ mTitle(name),
+ mRenderNotification(NULL),
+ mColorDepth(isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24),
+ mOwnSurface(false)
+{
+}
+
+void EcoreXRenderSurface::Init( Any surface )
+{
+ // see if there is a surface in Any surface
+ unsigned int surfaceId = GetSurfaceId( surface );
+
+ // if the surface is empty, create a new one.
+ if ( surfaceId == 0 )
+ {
+ // we own the surface about to created
+ mOwnSurface = true;
+ CreateXRenderable();
+ }
+ else
+ {
+ // XLib should already be initialized so no point in calling XInitThreads
+ UseExistingRenderable( surfaceId );
+ }
+}
+
+EcoreXRenderSurface::~EcoreXRenderSurface()
+{
+}
+
+void EcoreXRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification)
+{
+ mRenderNotification = renderNotification;
+}
+
+Ecore_X_Window EcoreXRenderSurface::GetXWindow()
+{
+ return 0;
+}
+
+Ecore_X_Drawable EcoreXRenderSurface::GetDrawable()
+{
+ return 0;
+}
+
+PositionSize EcoreXRenderSurface::GetPositionSize() const
+{
+ return mPosition;
+}
+
+void EcoreXRenderSurface::MoveResize( Dali::PositionSize positionSize )
+{
+ // nothing to do in base class
+}
+
+void EcoreXRenderSurface::SetViewMode( ViewMode viewMode )
+{
+}
+
+unsigned int EcoreXRenderSurface::GetSurfaceId( Any surface ) const
+{
+ unsigned int surfaceId = 0;
+
+ if ( surface.Empty() == false )
+ {
+ // check we have a valid type
+ DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (XWindow) ) ||
+ (surface.GetType() == typeid (Ecore_X_Window) ) )
+ && "Surface type is invalid" );
+
+ if ( surface.GetType() == typeid (Ecore_X_Window) )
+ {
+ surfaceId = AnyCast<Ecore_X_Window>( surface );
+ }
+ else
+ {
+ surfaceId = AnyCast<XWindow>( surface );
+ }
+ }
+ return surfaceId;
+}
+
+RenderSurface::Type EcoreXRenderSurface::GetSurfaceType()
+{
+ return RenderSurface::ECORE_RENDER_SURFACE;
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/x11/pixmap-render-surface.h>
+
+namespace Dali
+{
+
+namespace ECore
+{
+
+DALI_EXPORT_API PixmapRenderSurface* CreatePixmapSurface(
+ PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ bool isTransparent)
+{
+ return new PixmapRenderSurface(positionSize, surface, name, isTransparent);
+}
+
+
+} // namespace ECore
+
+} // namespace Dali
+
+
+
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/common/window-impl.h>
+
+// EXTERNAL HEADERS
+// Ecore is littered with C style cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Ecore.h>
+#include <Ecore_X.h>
+
+#include <dali/integration-api/core.h>
+#include <dali/integration-api/system-overlay.h>
+#include <dali/public-api/render-tasks/render-task.h>
+#include <dali/public-api/render-tasks/render-task-list.h>
+
+// INTERNAL HEADERS
+#include <dali/internal/window-system/ubuntu-x11/window-render-surface-x.h>
+#include <dali/internal/input/common/drag-and-drop-detector-impl.h>
+#include <dali/internal/window-system/common/ecore-indicator-impl.h>
+#include <dali/internal/window-system/common/window-visibility-observer.h>
+#include <dali/devel-api/adaptor-framework/orientation.h>
+#include <dali/internal/window-system/common/orientation-impl.h>
+
+namespace
+{
+const float INDICATOR_ANIMATION_DURATION( 0.18f ); // 180 milli seconds
+const float INDICATOR_SHOW_Y_POSITION( 0.0f );
+const float INDICATOR_HIDE_Y_POSITION( -52.0f );
+}
+
+namespace Dali
+{
+namespace Internal
+{
+namespace Adaptor
+{
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_WINDOW");
+#endif
+
+/**
+ * TODO: Abstract Window class out and move this into a window implementation for Ecore
+ */
+struct Window::EventHandler
+{
+ /**
+ * Constructor
+ * @param[in] window A pointer to the window class.
+ */
+ EventHandler( Window* window )
+ : mWindow( window ),
+ mWindowPropertyHandler( NULL ),
+ mClientMessagehandler( NULL ),
+ mWindowDeleteRequestHandler( NULL ),
+ mEcoreWindow( 0 )
+ {
+ // store ecore window handle
+ ECore::WindowRenderSurface* x11Window( dynamic_cast< ECore::WindowRenderSurface * >( mWindow->mSurface ) );
+ if( x11Window )
+ {
+ mEcoreWindow = x11Window->GetXWindow();
+ }
+ DALI_ASSERT_ALWAYS( mEcoreWindow != 0 && "There is no ecore x window");
+
+#ifndef DALI_PROFILE_UBUNTU
+ // set property on window to get deiconify approve client message
+ unsigned int tmp = 1;
+ ecore_x_window_prop_card32_set(mEcoreWindow,
+ ECORE_X_ATOM_E_DEICONIFY_APPROVE,
+ &tmp, 1);
+#endif // DALI_PROFILE_UBUNTU
+
+ if( mWindow->mEcoreEventHander )
+ {
+ ecore_x_input_multi_select( mEcoreWindow );
+
+ // This ensures that we catch the window close (or delete) request
+ ecore_x_icccm_protocol_set( mEcoreWindow, ECORE_X_WM_PROTOCOL_DELETE_REQUEST, EINA_TRUE );
+
+ mWindowPropertyHandler= ecore_event_handler_add( ECORE_X_EVENT_WINDOW_PROPERTY, EcoreEventWindowPropertyChanged, this );
+ mClientMessagehandler = ecore_event_handler_add( ECORE_X_EVENT_CLIENT_MESSAGE, EcoreEventClientMessage, this );
+ mWindowDeleteRequestHandler = ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DELETE_REQUEST, EcoreEventWindowDeleteRequest, this );
+ }
+ }
+
+ /**
+ * Destructor
+ */
+ ~EventHandler()
+ {
+ if ( mWindowPropertyHandler )
+ {
+ ecore_event_handler_del( mWindowPropertyHandler );
+ }
+ if ( mClientMessagehandler )
+ {
+ ecore_event_handler_del( mClientMessagehandler );
+ }
+ if ( mWindowDeleteRequestHandler )
+ {
+ ecore_event_handler_del( mWindowDeleteRequestHandler );
+ }
+ }
+
+ // Static methods
+
+ /// Called when the window properties are changed.
+ static Eina_Bool EcoreEventWindowPropertyChanged( void* data, int type, void* event )
+ {
+ Ecore_X_Event_Window_Property* propertyChangedEvent( (Ecore_X_Event_Window_Property*)event );
+ EventHandler* handler( (EventHandler*)data );
+ Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
+
+ if ( handler && handler->mWindow )
+ {
+ WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
+ if ( observer && ( propertyChangedEvent->win == handler->mEcoreWindow ) )
+ {
+ Ecore_X_Window_State_Hint state( ecore_x_icccm_state_get( propertyChangedEvent->win ) );
+
+ switch ( state )
+ {
+ case ECORE_X_WINDOW_STATE_HINT_WITHDRAWN:
+ {
+ // Window was hidden.
+ observer->OnWindowHidden();
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Withdrawn\n", handler->mEcoreWindow );
+ handled = ECORE_CALLBACK_DONE;
+ }
+ break;
+
+ case ECORE_X_WINDOW_STATE_HINT_ICONIC:
+ {
+ // Window was iconified (minimised).
+ observer->OnWindowHidden();
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Iconfied\n", handler->mEcoreWindow );
+ handled = ECORE_CALLBACK_DONE;
+ }
+ break;
+
+ case ECORE_X_WINDOW_STATE_HINT_NORMAL:
+ {
+ // Window was shown.
+ observer->OnWindowShown();
+ DALI_LOG_INFO( gWindowLogFilter, Debug::General, "Window (%d) Shown\n", handler->mEcoreWindow );
+ handled = ECORE_CALLBACK_DONE;
+ }
+ break;
+
+ default:
+ // Ignore
+ break;
+ }
+ }
+ }
+
+ return handled;
+ }
+
+ /// Called when the window properties are changed.
+ static Eina_Bool EcoreEventClientMessage( void* data, int type, void* event )
+ {
+ Eina_Bool handled( ECORE_CALLBACK_PASS_ON );
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Event_Client_Message* clientMessageEvent( (Ecore_X_Event_Client_Message*)event );
+ EventHandler* handler( (EventHandler*)data );
+
+ if (clientMessageEvent->message_type == ECORE_X_ATOM_E_DEICONIFY_APPROVE)
+ {
+ ECore::WindowRenderSurface* x11Window( dynamic_cast< ECore::WindowRenderSurface * >( handler->mWindow->mSurface ) );
+ WindowVisibilityObserver* observer( handler->mWindow->mAdaptor );
+
+ if ( observer && ( (unsigned int)clientMessageEvent->data.l[0] == handler->mEcoreWindow ) )
+ {
+ if (clientMessageEvent->data.l[1] == 0) //wm sends request message using value 0
+ {
+ observer->OnWindowShown();
+
+ // request to approve the deiconify. render-surface should send proper event after real rendering
+ if(x11Window)
+ {
+ x11Window->RequestToApproveDeiconify();
+ }
+
+ handled = ECORE_CALLBACK_DONE;
+ }
+ }
+ }
+#endif // DALI_PROFILE_UBUNTU
+
+ return handled;
+ }
+
+ /// Called when the window receives a delete request
+ static Eina_Bool EcoreEventWindowDeleteRequest( void* data, int type, void* event )
+ {
+ EventHandler* handler( (EventHandler*)data );
+ handler->mWindow->mDeleteRequestSignal.Emit();
+ return ECORE_CALLBACK_DONE;
+ }
+
+ // Data
+ Window* mWindow;
+ Ecore_Event_Handler* mWindowPropertyHandler;
+ Ecore_Event_Handler* mClientMessagehandler;
+ Ecore_Event_Handler* mWindowDeleteRequestHandler;
+ Ecore_X_Window mEcoreWindow;
+};
+
+
+Window* Window::New( const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent )
+{
+ Window* window = new Window();
+ window->mIsTransparent = isTransparent;
+ window->Initialize( positionSize, name, className );
+ return window;
+}
+
+void Window::SetAdaptor(Dali::Adaptor& adaptor)
+{
+ DALI_ASSERT_ALWAYS( !mStarted && "Adaptor already started" );
+ mStarted = true;
+
+ // Only create one overlay per window
+ Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor);
+ Integration::Core& core = adaptorImpl.GetCore();
+ mOverlay = &core.GetSystemOverlay();
+
+ Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
+ taskList.CreateTask();
+
+ mAdaptor = &adaptorImpl;
+ mAdaptor->AddObserver( *this );
+
+ // Can only create the detector when we know the Core has been instantiated.
+ mDragAndDropDetector = DragAndDropDetector::New();
+ mAdaptor->SetDragAndDropDetector( &GetImplementation( mDragAndDropDetector ) );
+
+ if( mOrientation )
+ {
+ mOrientation->SetAdaptor(adaptor);
+ }
+
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetAdaptor(mAdaptor);
+ }
+}
+
+RenderSurface* Window::GetSurface()
+{
+ return mSurface;
+}
+
+void Window::ShowIndicator( Dali::Window::IndicatorVisibleMode visibleMode )
+{
+ DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "visible : %d\n", visibleMode );
+ DALI_ASSERT_DEBUG(mOverlay);
+
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ DALI_ASSERT_DEBUG(x11Window);
+ Ecore_X_Window xWinId = x11Window->GetXWindow();
+
+ mIndicatorVisible = visibleMode;
+
+ if ( mIndicatorVisible == Dali::Window::VISIBLE )
+ {
+ // when the indicator is visible, set proper mode for indicator server according to bg mode
+ if ( mIndicatorOpacityMode == Dali::Window::OPAQUE )
+ {
+ ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_OPAQUE);
+ }
+ else if ( mIndicatorOpacityMode == Dali::Window::TRANSLUCENT )
+ {
+ ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_TRANSLUCENT);
+ }
+#if defined(DALI_PROFILE_MOBILE)
+ else if ( mIndicatorOpacityMode == Dali::Window::TRANSPARENT )
+ {
+ ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_OPAQUE);
+ }
+#endif
+ }
+ else
+ {
+ // when the indicator is not visible, set TRANSPARENT mode for indicator server
+ ecore_x_e_illume_indicator_opacity_set(xWinId, ECORE_X_ILLUME_INDICATOR_TRANSPARENT); // it means hidden indicator
+ }
+
+ DoShowIndicator( mIndicatorOrientation );
+}
+
+void Window::RotateIndicator(Dali::Window::WindowOrientation orientation)
+{
+ DALI_LOG_TRACE_METHOD_FMT( gWindowLogFilter, "Orientation: %d\n", orientation );
+
+ DoRotateIndicator( orientation );
+}
+
+void Window::SetIndicatorBgOpacity( Dali::Window::IndicatorBgOpacity opacityMode )
+{
+ mIndicatorOpacityMode = opacityMode;
+
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetOpacityMode( opacityMode );
+ }
+}
+
+void Window::SetClass(std::string name, std::string klass)
+{
+ // Get render surface's x11 window
+ if( mSurface )
+ {
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ ecore_x_icccm_name_class_set( x11Window->GetXWindow(), name.c_str(), klass.c_str() );
+ }
+ }
+}
+
+Window::Window()
+: mSurface( NULL ),
+ mIndicatorVisible( Dali::Window::INVISIBLE ),
+ mIndicatorIsShown( false ),
+ mShowRotatedIndicatorOnClose( false ),
+ mStarted( false ),
+ mIsTransparent( false ),
+ mWMRotationAppSet( false ),
+ mEcoreEventHander( true ),
+ mIsFocusAcceptable( true ),
+ mVisible( true ),
+ mIconified( false ),
+ mOpaqueState( false ),
+ mResizeEnabled( true ),
+ mIndicator( NULL ),
+ mIndicatorOrientation( Dali::Window::PORTRAIT ),
+ mNextIndicatorOrientation( Dali::Window::PORTRAIT ),
+ mIndicatorOpacityMode( Dali::Window::OPAQUE ),
+ mOverlay( NULL ),
+ mAdaptor( NULL ),
+ mType( Dali::Window::NORMAL ),
+ mEventHandler( NULL ),
+ mPreferredOrientation( Dali::Window::PORTRAIT ),
+ mSupportedAuxiliaryHints(),
+ mAuxiliaryHints(),
+ mIndicatorVisibilityChangedSignal(),
+ mFocusChangedSignal(),
+ mResizedSignal(),
+ mDeleteRequestSignal()
+{
+}
+
+Window::~Window()
+{
+ delete mEventHandler;
+
+ if( mIndicator )
+ {
+ mOverlay->Remove( mIndicator->GetActor() );
+ Dali::RenderTaskList taskList = mOverlay->GetOverlayRenderTasks();
+ Dali::RenderTask indicatorTask = taskList.GetTask(0);
+ mOverlay->GetOverlayRenderTasks().RemoveTask(indicatorTask);
+ mIndicator->Close();
+ delete mIndicator;
+ }
+
+ if( mAdaptor )
+ {
+ mAdaptor->RemoveObserver( *this );
+ mAdaptor->SetDragAndDropDetector( NULL );
+ mAdaptor = NULL;
+ }
+
+ delete mSurface;
+}
+
+void Window::Initialize(const PositionSize& positionSize, const std::string& name, const std::string& className)
+{
+ // create an X11 window by default
+ Any surface;
+ ECore::WindowRenderSurface* windowSurface = new ECore::WindowRenderSurface( positionSize, surface, name, className, mIsTransparent );
+ windowSurface->Map();
+
+ mSurface = windowSurface;
+
+ mOrientation = Orientation::New(this);
+
+ // create event handler for X11 window
+ mEventHandler = new EventHandler( this );
+}
+
+void Window::DoShowIndicator( Dali::Window::WindowOrientation lastOrientation )
+{
+ if( mIndicator == NULL )
+ {
+ if( mIndicatorVisible != Dali::Window::INVISIBLE )
+ {
+ mIndicator = new Indicator( mAdaptor, mIndicatorOrientation, this );
+ mIndicator->SetOpacityMode( mIndicatorOpacityMode );
+ Dali::Actor actor = mIndicator->GetActor();
+ SetIndicatorActorRotation();
+ mOverlay->Add(actor);
+ }
+ // else don't create a hidden indicator
+ }
+ else // Already have indicator
+ {
+ if( mIndicatorVisible == Dali::Window::VISIBLE )
+ {
+ // If we are resuming, and rotation has changed,
+ if( mIndicatorIsShown == false && mIndicatorOrientation != mNextIndicatorOrientation )
+ {
+ // then close current indicator and open new one
+ mShowRotatedIndicatorOnClose = true;
+ mIndicator->Close(); // May synchronously call IndicatorClosed() callback & 1 level of recursion
+ // Don't show actor - will contain indicator for old orientation.
+ }
+ }
+ }
+
+ // set indicator visible mode
+ if( mIndicator != NULL )
+ {
+ mIndicator->SetVisible( mIndicatorVisible );
+ }
+
+ bool show = (mIndicatorVisible != Dali::Window::INVISIBLE );
+ SetIndicatorProperties( show, lastOrientation );
+ mIndicatorIsShown = show;
+}
+
+void Window::DoRotateIndicator( Dali::Window::WindowOrientation orientation )
+{
+ if( mIndicatorIsShown )
+ {
+ mShowRotatedIndicatorOnClose = true;
+ mNextIndicatorOrientation = orientation;
+ mIndicator->Close(); // May synchronously call IndicatorClosed() callback
+ }
+ else
+ {
+ // Save orientation for when the indicator is next shown
+ mShowRotatedIndicatorOnClose = false;
+ mNextIndicatorOrientation = orientation;
+ }
+}
+
+void Window::SetIndicatorProperties( bool isShow, Dali::Window::WindowOrientation lastOrientation )
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+
+ int show_state = static_cast<int>( isShow );
+ ecore_x_window_prop_property_set( win,
+ ECORE_X_ATOM_E_ILLUME_INDICATOR_STATE,
+ ECORE_X_ATOM_CARDINAL, 32, &show_state, 1);
+
+ if ( isShow )
+ {
+ ecore_x_e_illume_indicator_state_set(win, ECORE_X_ILLUME_INDICATOR_STATE_ON);
+ }
+ else
+ {
+ ecore_x_e_illume_indicator_state_set(win, ECORE_X_ILLUME_INDICATOR_STATE_OFF);
+ }
+ }
+}
+
+void Window::IndicatorTypeChanged(Indicator::Type type)
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Window win = x11Window->GetXWindow();
+ switch(type)
+ {
+ case Indicator::INDICATOR_TYPE_1:
+ ecore_x_e_illume_indicator_type_set( win, ECORE_X_ILLUME_INDICATOR_TYPE_1 );
+ break;
+
+ case Indicator::INDICATOR_TYPE_2:
+ ecore_x_e_illume_indicator_type_set( win, ECORE_X_ILLUME_INDICATOR_TYPE_2 );
+ break;
+
+ case Indicator::INDICATOR_TYPE_UNKNOWN:
+ default:
+ break;
+ }
+#endif // DALI_PROFILE_UBUNTU
+ }
+}
+
+void Window::IndicatorClosed( IndicatorInterface* indicator )
+{
+ DALI_LOG_TRACE_METHOD( gWindowLogFilter );
+
+ if( mShowRotatedIndicatorOnClose )
+ {
+ Dali::Window::WindowOrientation currentOrientation = mIndicatorOrientation;
+ mIndicator->Open(mNextIndicatorOrientation);
+ mIndicatorOrientation = mNextIndicatorOrientation;
+ SetIndicatorActorRotation();
+ DoShowIndicator(currentOrientation);
+ }
+}
+
+void Window::IndicatorVisibilityChanged(bool isVisible)
+{
+ mIndicatorVisibilityChangedSignal.Emit(isVisible);
+}
+
+void Window::SetIndicatorActorRotation()
+{
+ DALI_LOG_TRACE_METHOD( gWindowLogFilter );
+ DALI_ASSERT_DEBUG( mIndicator != NULL );
+
+ Dali::Actor actor = mIndicator->GetActor();
+ switch( mIndicatorOrientation )
+ {
+ case Dali::Window::PORTRAIT:
+ actor.SetParentOrigin( ParentOrigin::TOP_CENTER );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(0), Vector3::ZAXIS );
+ break;
+ case Dali::Window::PORTRAIT_INVERSE:
+ actor.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(180), Vector3::ZAXIS );
+ break;
+ case Dali::Window::LANDSCAPE:
+ actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(270), Vector3::ZAXIS );
+ break;
+ case Dali::Window::LANDSCAPE_INVERSE:
+ actor.SetParentOrigin( ParentOrigin::CENTER_RIGHT );
+ actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
+ actor.SetOrientation( Degree(90), Vector3::ZAXIS );
+ break;
+ }
+}
+
+void Window::Raise()
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ ecore_x_window_raise(win);
+ }
+}
+
+void Window::Lower()
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ ecore_x_window_lower(win);
+ }
+}
+
+void Window::Activate()
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ ecore_x_netwm_client_active_request(ecore_x_window_root_get(win), win, 1 /* request type, 1:application, 2:pager */, 0);
+ }
+}
+
+Dali::DragAndDropDetector Window::GetDragAndDropDetector() const
+{
+ return mDragAndDropDetector;
+}
+
+Dali::Any Window::GetNativeHandle() const
+{
+ if(mEventHandler)
+ {
+ return mEventHandler->mEcoreWindow;
+ }
+ else
+ {
+ return Dali::Any();
+ }
+}
+
+void Window::OnStart()
+{
+ ShowIndicator( mIndicatorVisible );
+}
+
+void Window::OnPause()
+{
+}
+
+void Window::OnResume()
+{
+ // resume indicator status
+ if( mIndicator != NULL )
+ {
+ // Restore own indicator opacity
+ // Send opacity mode to indicator service when app resumed
+ mIndicator->SetOpacityMode( mIndicatorOpacityMode );
+ }
+}
+
+void Window::OnStop()
+{
+ if( mIndicator )
+ {
+ mIndicator->Close();
+ }
+
+ delete mIndicator;
+ mIndicator = NULL;
+}
+
+void Window::OnDestroy()
+{
+ mAdaptor = NULL;
+}
+
+void Window::AddAvailableOrientation(Dali::Window::WindowOrientation orientation)
+{
+ bool found = false;
+
+ for( std::size_t i=0; i<mAvailableOrientations.size(); i++ )
+ {
+ if(mAvailableOrientations[i] == orientation)
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if( ! found )
+ {
+ mAvailableOrientations.push_back(orientation);
+ SetAvailableOrientations( mAvailableOrientations );
+ }
+}
+
+void Window::RemoveAvailableOrientation(Dali::Window::WindowOrientation orientation)
+{
+ for( std::vector<Dali::Window::WindowOrientation>::iterator iter = mAvailableOrientations.begin();
+ iter != mAvailableOrientations.end(); ++iter )
+ {
+ if( *iter == orientation )
+ {
+ mAvailableOrientations.erase( iter );
+ break;
+ }
+ }
+ SetAvailableOrientations( mAvailableOrientations );
+}
+
+void Window::SetAvailableOrientations(const std::vector<Dali::Window::WindowOrientation>& orientations)
+{
+ DALI_ASSERT_ALWAYS( mAvailableOrientations.size() <= 4 && "Incorrect number of available orientations" );
+
+ mAvailableOrientations = orientations;
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
+ if( ! mWMRotationAppSet )
+ {
+ mWMRotationAppSet = true;
+ ecore_x_e_window_rotation_app_set(ecoreWindow, EINA_TRUE);
+ }
+
+ int rotations[4];
+ for( std::size_t i=0; i<mAvailableOrientations.size(); i++ )
+ {
+ rotations[i] = static_cast<int>(mAvailableOrientations[i]);
+ }
+ ecore_x_e_window_rotation_available_rotations_set(ecoreWindow, rotations, mAvailableOrientations.size() );
+#endif // DALI_PROFILE_UBUNTU
+ }
+}
+
+const std::vector<Dali::Window::WindowOrientation>& Window::GetAvailableOrientations()
+{
+ return mAvailableOrientations;
+}
+
+void Window::SetPreferredOrientation(Dali::Window::WindowOrientation orientation)
+{
+ mPreferredOrientation = orientation;
+
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
+
+ if( ! mWMRotationAppSet )
+ {
+ mWMRotationAppSet = true;
+ ecore_x_e_window_rotation_app_set(ecoreWindow, EINA_TRUE);
+ }
+
+ ecore_x_e_window_rotation_preferred_rotation_set(ecoreWindow, orientation);
+#endif // DALI_PROFILE_UBUNTU
+ }
+}
+
+Dali::Window::WindowOrientation Window::GetPreferredOrientation()
+{
+ return mPreferredOrientation;
+}
+
+void Window::SetAcceptFocus( bool accept )
+{
+ mIsFocusAcceptable = accept;
+}
+
+bool Window::IsFocusAcceptable() const
+{
+ return mIsFocusAcceptable;
+}
+
+void Window::Show()
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ ecore_x_window_show( win );
+
+ // Need an update request
+ if( mAdaptor )
+ {
+ mAdaptor->RequestUpdateOnce();
+ }
+ }
+}
+
+void Window::Hide()
+{
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ ecore_x_window_hide( win );
+ }
+}
+
+bool Window::IsVisible() const
+{
+ bool visible = false;
+
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+ Ecore_X_Window win = x11Window->GetXWindow();
+ visible = static_cast< bool >( ecore_x_window_visible_get( win ) );
+ }
+ return visible;
+}
+
+void Window::RotationDone( int orientation, int width, int height )
+{
+ // Tell window manager we're done
+ ECore::WindowRenderSurface* x11Window = dynamic_cast< ECore::WindowRenderSurface * >( mSurface );
+ if( x11Window )
+ {
+#ifndef DALI_PROFILE_UBUNTU
+ Ecore_X_Window ecoreWindow = x11Window->GetXWindow();
+ Ecore_X_Window root = ecore_x_window_root_get(ecoreWindow);
+
+ /**
+ * send rotation done message to wm, even if window is already rotated.
+ * that's why wm must be wait for comming rotation done message
+ * after sending rotation request.
+ */
+ ecore_x_e_window_rotation_change_done_send(root, ecoreWindow, orientation, width, height);
+
+ /**
+ * set rotate window property
+ */
+ int angles[2] = { orientation, orientation };
+ ecore_x_window_prop_property_set( ecoreWindow,
+ ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE,
+ ECORE_X_ATOM_CARDINAL, 32, &angles, 2 );
+
+ mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( width, height ) );
+
+ // Emit signal
+ mResizedSignal.Emit( Dali::Window::WindowSize( width, height ) );
+
+ mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( width, height ) );
+#endif // DALI_PROFILE_UBUNTU
+ }
+}
+
+void Window::SetIndicatorVisibleMode( Dali::Window::IndicatorVisibleMode mode )
+{
+ mIndicatorVisible = mode;
+}
+
+unsigned int Window::GetSupportedAuxiliaryHintCount() const
+{
+ return 0;
+}
+
+std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
+{
+ return std::string();
+}
+
+unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
+{
+ return -1;
+}
+
+bool Window::RemoveAuxiliaryHint( unsigned int id )
+{
+ return false;
+}
+
+bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
+{
+ return false;
+}
+
+std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
+{
+ return std::string();
+}
+
+unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
+{
+ return -1;
+}
+
+void Window::SetInputRegion( const Rect< int >& inputRegion )
+{
+}
+
+void Window::SetType( Dali::Window::Type type )
+{
+ mType = type;
+}
+
+Dali::Window::Type Window::GetType() const
+{
+ return mType;
+}
+
+bool Window::SetNotificationLevel( Dali::Window::NotificationLevel::Type level )
+{
+ return false;
+}
+
+Dali::Window::NotificationLevel::Type Window::GetNotificationLevel() const
+{
+ return Dali::Window::NotificationLevel::NONE;
+}
+
+void Window::SetOpaqueState( bool opaque )
+{
+ mOpaqueState = opaque;
+}
+
+bool Window::IsOpaqueState() const
+{
+ return mOpaqueState;
+}
+
+bool Window::SetScreenOffMode(Dali::Window::ScreenOffMode::Type screenOffMode)
+{
+ return false;
+}
+
+Dali::Window::ScreenOffMode::Type Window::GetScreenOffMode() const
+{
+ return Dali::Window::ScreenOffMode::TIMEOUT;
+}
+
+bool Window::SetBrightness( int brightness )
+{
+ return false;
+}
+
+int Window::GetBrightness() const
+{
+ return 0;
+}
+
+void Window::SetSize( Dali::Window::WindowSize size )
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ if( positionSize.width != size.GetWidth() || positionSize.height != size.GetHeight() )
+ {
+ positionSize.width = size.GetWidth();
+ positionSize.height = size.GetHeight();
+
+ mSurface->MoveResize( positionSize );
+
+ mAdaptor->SurfaceResizePrepare( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+
+ // Emit signal
+ mResizedSignal.Emit( Dali::Window::WindowSize( positionSize.width, positionSize.height ) );
+
+ mAdaptor->SurfaceResizeComplete( Adaptor::SurfaceSize( positionSize.width, positionSize.height ) );
+ }
+}
+
+Dali::Window::WindowSize Window::GetSize() const
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ return Dali::Window::WindowSize( positionSize.width, positionSize.height );
+}
+
+void Window::SetPosition( Dali::Window::WindowPosition position )
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ if( positionSize.x != position.GetX() || positionSize.y != position.GetY() )
+ {
+ positionSize.x = position.GetX();
+ positionSize.y = position.GetY();
+
+ mSurface->MoveResize( positionSize );
+ }
+}
+
+Dali::Window::WindowPosition Window::GetPosition() const
+{
+ PositionSize positionSize = mSurface->GetPositionSize();
+
+ return Dali::Window::WindowPosition( positionSize.x, positionSize.y );
+}
+
+void Window::SetTransparency( bool transparent )
+{
+}
+
+} // Adaptor
+
+} // Internal
+
+} // Dali
+
+#pragma GCC diagnostic pop
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h>
+
+// EXTERNAL INCLUDES
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/x11/ecore-x-types.h>
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+namespace Adaptor
+{
+
+namespace ECore
+{
+
+namespace WindowInterface
+{
+// CONSTANTS
+const char* const CBHM_WINDOW = "CBHM_XWIN";
+
+Ecore_X_Window GetWindow()
+{
+ Ecore_X_Atom xAtomCbhm = ecore_x_atom_get( CBHM_WINDOW );
+
+ Ecore_X_Window xCbhmWin = 0;
+ unsigned char *buf = NULL;
+ int num = 0;
+// XA_WINDOW is a macro with C cast
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ int ret = ecore_x_window_prop_property_get( 0, xAtomCbhm, XA_WINDOW, 0, &buf, &num );
+#pragma GCC diagnostic pop
+
+ if ( ret && num )
+ {
+ memcpy( &xCbhmWin, buf, sizeof( Ecore_X_Window ) );
+ }
+ if ( buf )
+ {
+ free( buf );
+ }
+
+ return xCbhmWin;
+}
+
+std::string GetWindowProperty( Ecore_X_Atom property, Ecore_X_Atom *xDataType, unsigned int num )
+{
+ std::string data("");
+
+ if ( !property )
+ {
+ return data;
+ }
+
+ ecore_x_sync();
+
+ long unsigned int numRet = 0, bytes = 0;
+ int ret = 0, sizeRet;
+ unsigned int i;
+ unsigned char *propRet;
+ Ecore_X_Atom typeRet;
+
+ // X11 Function to get window property
+ ret = XGetWindowProperty( static_cast<Display*>(ecore_x_display_get()), // Display* X Server Connection
+ GetWindow(), // Window window in question
+ property, // Atom name of property
+ num, // long offset where required data is stored
+ LONG_MAX, // long length of data to retrieve
+ False, // Bool flag to delete data
+ ecore_x_window_prop_any_type(), // Atom atom id associated to property type
+ reinterpret_cast< Atom * >( &typeRet ), // Atom actual_type_return, atom id property type
+ &sizeRet, // int* format of property
+ &numRet, // unsigned long* number of items being returned in prop_return
+ &bytes, // unsigned long* remaining bytes if partial retrieval
+ &propRet ); // unsigned char** return data
+ if ( ret != Success )
+ {
+ return data;
+ }
+
+ if ( !numRet )
+ {
+ XFree( propRet );
+ return data;
+ }
+
+ numRet--; // As propRet in XGetWindowProperty gets an extra 0 added for compatibility reasons.
+
+ switch ( sizeRet ) // Format returned by XGetWindowProperty int, short, long
+ {
+ case 8:
+ {
+ for ( i = 0; i < numRet; i++ )
+ {
+ data += propRet[i];
+ }
+ }
+ break;
+
+ case 16:
+ {
+ for ( i = 0; i < numRet; i++ )
+ {
+ data += ( propRet )[i];
+ }
+ }
+ break;
+
+ case 32:
+ {
+ for ( i = 0; i < numRet; i++ )
+ {
+ data += ( propRet )[i];
+ }
+ }
+ break;
+ }
+
+ XFree( propRet );
+
+ if ( xDataType )
+ {
+ *xDataType = typeRet;
+ }
+
+ return data;
+ }
+
+void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate,
+ long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char *msg )
+{
+ XClientMessageEvent message;
+ memset(&message, 0, sizeof( message ) );
+ message.type = ClientMessage;
+ message.display = static_cast<Display*>( display );
+ message.message_type = messageType;
+ message.format = messageFormat;
+ message.window = window;
+ snprintf(message.data.b, 20, "%s", msg);
+
+ XSendEvent( static_cast<Display*>( display ), window, propagate, eventMask, reinterpret_cast< XEvent* >( &message ) );
+}
+
+
+} // namespace WindowInterface
+
+
+} // namespace ECore
+
+} // namespace Adaptor
+
+} // namespace Internal
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/internal/window-system/ubuntu-x11/window-render-surface-x.h>
+
+// EXTERNAL INCLUDES
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#include <X11/extensions/Xfixes.h> // for damage notify
+#include <X11/extensions/Xdamage.h> // for damage notify
+
+#include <dali/integration-api/gl-abstraction.h>
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+
+#include <dali/integration-api/x11/ecore-x-types.h>
+#include <dali/internal/system/common/trigger-event.h>
+#include <dali/internal/graphics/gles20/egl-implementation.h>
+#include <dali/internal/window-system/common/display-connection.h>
+
+namespace Dali
+{
+
+#if defined(DEBUG_ENABLED)
+extern Debug::Filter* gRenderSurfaceLogFilter;
+#endif
+
+namespace ECore
+{
+
+namespace
+{
+
+const int MINIMUM_DIMENSION_CHANGE( 1 ); ///< Minimum change for window to be considered to have moved
+
+} // unnamed namespace
+
+WindowRenderSurface::WindowRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ const std::string& className,
+ bool isTransparent)
+: EcoreXRenderSurface( positionSize, surface, name, isTransparent ),
+ mX11Window( 0 ),
+ mNeedToApproveDeiconify(false),
+ mClassName(className)
+{
+ DALI_LOG_INFO( gRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n" );
+ Init( surface );
+}
+
+WindowRenderSurface::~WindowRenderSurface()
+{
+ if( mOwnSurface )
+ {
+ ecore_x_window_free( mX11Window );
+ }
+}
+
+Ecore_X_Drawable WindowRenderSurface::GetDrawable()
+{
+ // already an e-core type
+ return static_cast< Ecore_X_Drawable >( mX11Window );
+}
+
+Any WindowRenderSurface::GetSurface()
+{
+ // already an e-core type
+ return Any( mX11Window );
+}
+
+Ecore_X_Window WindowRenderSurface::GetXWindow()
+{
+ return mX11Window;
+}
+
+void WindowRenderSurface::RequestToApproveDeiconify()
+{
+ mNeedToApproveDeiconify = true;
+}
+
+void WindowRenderSurface::InitializeEgl( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+
+ eglImpl.ChooseConfig(true, mColorDepth);
+}
+
+void WindowRenderSurface::CreateEglSurface( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+
+ // create the EGL surface
+ // need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XWindow window( mX11Window );
+ eglImpl.CreateSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( window ), mColorDepth );
+}
+
+void WindowRenderSurface::DestroyEglSurface( EglInterface& eglIf )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( eglIf );
+ eglImpl.DestroySurface();
+}
+
+bool WindowRenderSurface::ReplaceEGLSurface( EglInterface& egl )
+{
+ DALI_LOG_TRACE_METHOD( gRenderSurfaceLogFilter );
+
+ // need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit
+ XWindow window( mX11Window );
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+
+ return eglImpl.ReplaceSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( window ) );
+}
+
+void WindowRenderSurface::MoveResize( Dali::PositionSize positionSize )
+{
+ bool needToMove = false;
+ bool needToResize = false;
+
+ // check moving
+ if( (fabs(positionSize.x - mPosition.x) > MINIMUM_DIMENSION_CHANGE) ||
+ (fabs(positionSize.y - mPosition.y) > MINIMUM_DIMENSION_CHANGE) )
+ {
+ needToMove = true;
+ }
+
+ // check resizing
+ if( (fabs(positionSize.width - mPosition.width) > MINIMUM_DIMENSION_CHANGE) ||
+ (fabs(positionSize.height - mPosition.height) > MINIMUM_DIMENSION_CHANGE) )
+ {
+ needToResize = true;
+ }
+
+ if( needToMove && needToResize)
+ {
+ ecore_x_window_move_resize(mX11Window, positionSize.x, positionSize.y, positionSize.width, positionSize.height);
+ mPosition = positionSize;
+ }
+ else if(needToMove)
+ {
+ ecore_x_window_move(mX11Window, positionSize.x, positionSize.y);
+ mPosition = positionSize;
+ }
+ else if (needToResize)
+ {
+ ecore_x_window_resize(mX11Window, positionSize.width, positionSize.height);
+ mPosition = positionSize;
+ }
+
+}
+
+void WindowRenderSurface::Map()
+{
+ ecore_x_window_show(mX11Window);
+}
+
+void WindowRenderSurface::StartRender()
+{
+}
+
+bool WindowRenderSurface::PreRender( EglInterface&, Integration::GlAbstraction&, bool )
+{
+ // nothing to do for windows
+ return true;
+}
+
+void WindowRenderSurface::PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface )
+{
+ Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>( egl );
+ eglImpl.SwapBuffers();
+
+ // When the window is deiconified, it approves the deiconify operation to window manager after rendering
+ if(mNeedToApproveDeiconify)
+ {
+ // SwapBuffer is desychronized. So make sure to sychronize when window is deiconified.
+ glAbstraction.Finish();
+
+ XDisplay* display = AnyCast<XDisplay *>(displayConnection->GetDisplay());
+
+#ifndef DALI_PROFILE_UBUNTU
+ /* client sends immediately reply message using value 1 */
+ XEvent xev;
+
+ xev.xclient.window = mX11Window;
+ xev.xclient.type = ClientMessage;
+ xev.xclient.message_type = ECORE_X_ATOM_E_DEICONIFY_APPROVE;
+ xev.xclient.format = 32;
+ xev.xclient.data.l[0] = mX11Window;
+ xev.xclient.data.l[1] = 1;
+ xev.xclient.data.l[2] = 0;
+ xev.xclient.data.l[3] = 0;
+ xev.xclient.data.l[4] = 0;
+
+ XSendEvent(display, mX11Window, false, ECORE_X_EVENT_MASK_WINDOW_CONFIGURE, &xev);
+#endif // DALI_PROFILE_UBUNTU
+
+ XSync(display, false);
+
+ mNeedToApproveDeiconify = false;
+ }
+}
+
+void WindowRenderSurface::StopRender()
+{
+}
+
+void WindowRenderSurface::SetViewMode( ViewMode viewMode )
+{
+ Ecore_X_Atom viewModeAtom( ecore_x_atom_get( "_E_COMP_3D_APP_WIN" ) );
+
+ if( viewModeAtom != None )
+ {
+ unsigned int value( static_cast<unsigned int>( viewMode ) );
+ ecore_x_window_prop_card32_set( mX11Window, viewModeAtom, &value, 1 );
+ }
+}
+
+void WindowRenderSurface::CreateXRenderable()
+{
+ // if width or height are zero, go full screen.
+ if ( (mPosition.width == 0) || (mPosition.height == 0) )
+ {
+ // Default window size == screen size
+ mPosition.x = 0;
+ mPosition.y = 0;
+
+ ecore_x_screen_size_get( ecore_x_default_screen_get(), &mPosition.width, &mPosition.height );
+ }
+
+ if(mColorDepth == COLOR_DEPTH_32)
+ {
+ // create 32 bit window
+ mX11Window = ecore_x_window_argb_new( 0, mPosition.x, mPosition.y, mPosition.width, mPosition.height );
+ }
+ else
+ {
+ // create 24 bit window
+ mX11Window = ecore_x_window_new( 0, mPosition.x, mPosition.y, mPosition.width, mPosition.height );
+ }
+
+ if ( mX11Window == 0 )
+ {
+ DALI_ASSERT_ALWAYS(0 && "Failed to create X window");
+ }
+
+ // set up window title which will be helpful for debug utitilty
+ ecore_x_icccm_title_set( mX11Window, mTitle.c_str() );
+ ecore_x_netwm_name_set( mX11Window, mTitle.c_str() );
+ ecore_x_icccm_name_class_set( mX11Window, mTitle.c_str(), mClassName.c_str() );
+
+ // set up etc properties to match with ecore-evas
+ char *id = NULL;
+ if( ( id = getenv("DESKTOP_STARTUP_ID") ) )
+ {
+ ecore_x_netwm_startup_id_set( mX11Window, id );
+ }
+
+ ecore_x_icccm_hints_set( mX11Window,
+ 1, // accepts_focus
+ ECORE_X_WINDOW_STATE_HINT_NORMAL, // initial_state
+ 0, // icon_pixmap
+ 0, // icon_mask
+ 0, // icon_window
+ 0, // window_group
+ 0 ); // is_urgent
+
+ // we SHOULD guarantee the x11 window was created in x server.
+ ecore_x_sync();
+}
+
+void WindowRenderSurface::UseExistingRenderable( unsigned int surfaceId )
+{
+ mX11Window = static_cast< Ecore_X_Window >( surfaceId );
+}
+
+void WindowRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& /* threadSynchronization */ )
+{
+ // Nothing to do.
+}
+
+void WindowRenderSurface::ReleaseLock()
+{
+ // Nothing to do.
+}
+
+} // namespace ECore
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
+#define __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
+
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/integration-api/x11/ecore-x-render-surface.h>
+
+namespace Dali
+{
+
+namespace ECore
+{
+
+/**
+ * @copydoc Dali::ECore::EcoreXRenderSurface.
+ * Window specialization.
+ */
+class WindowRenderSurface : public EcoreXRenderSurface
+{
+public:
+
+ /**
+ * Uses an X11 surface to render to.
+ * @param [in] positionSize the position and size of the surface
+ * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int).
+ * @param [in] name optional name of surface passed in
+ * @param [in] className optional class name of the surface passed in
+ * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit
+ */
+ WindowRenderSurface( Dali::PositionSize positionSize,
+ Any surface,
+ const std::string& name,
+ const std::string& className,
+ bool isTransparent = false );
+
+ /**
+ * @copydoc Dali::ECore::EcoreXRenderSurface::~EcoreXRenderSurface
+ */
+ virtual ~WindowRenderSurface();
+
+public: // API
+
+ /**
+ * @copydoc Dali::RenderSurface::GetDrawable()
+ */
+ virtual Ecore_X_Drawable GetDrawable();
+
+ /**
+ * Request to approve deiconify operation
+ * If it is requested, it will send ECORE_X_ATOM_E_DEICONIFY_APPROVE event to window manager after rendering
+ */
+ void RequestToApproveDeiconify();
+
+ /**
+ * Map window
+ */
+ virtual void Map();
+
+ /**
+ * @copydoc Dali::ECore::EcoreXRenderSurface::GetSurface()
+ */
+ virtual Any GetSurface();
+
+ /**
+ * @copydoc Dali::ECore::EcoreXRenderSurface::GetXWindow()
+ */
+ virtual Ecore_X_Window GetXWindow();
+
+public: // from Dali::RenderSurface
+
+ /**
+ * @copydoc Dali::RenderSurface::InitializeEgl()
+ */
+ virtual void InitializeEgl( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::CreateEglSurface()
+ */
+ virtual void CreateEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::DestroyEglSurface()
+ */
+ virtual void DestroyEglSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReplaceEGLSurface()
+ */
+ virtual bool ReplaceEGLSurface( EglInterface& egl );
+
+ /**
+ * @copydoc Dali::RenderSurface::MoveResize()
+ */
+ virtual void MoveResize( Dali::PositionSize positionSize);
+
+ /**
+ * @copydoc Dali::RenderSurface::SetViewMode()
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @copydoc Dali::RenderSurface::StartRender()
+ */
+ virtual void StartRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::PreRender()
+ */
+ virtual bool PreRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::PostRender()
+ */
+ virtual void PostRender( EglInterface& egl, Integration::GlAbstraction& glAbstraction, DisplayConnection* displayConnection, bool replacingSurface, bool resizingSurface );
+
+ /**
+ * @copydoc Dali::RenderSurface::StopRender()
+ */
+ virtual void StopRender();
+
+ /**
+ * @copydoc Dali::RenderSurface::SetThreadSynchronization
+ */
+ virtual void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization );
+
+ /**
+ * @copydoc Dali::RenderSurface::ReleaseLock()
+ */
+ virtual void ReleaseLock();
+
+protected:
+
+ /**
+ * Create XWindow
+ */
+ virtual void CreateXRenderable();
+
+ /**
+ * @copydoc Dali::Internal::Adaptor::ECore::EcoreXRenderSurface::UseExistingRenderable
+ */
+ virtual void UseExistingRenderable( unsigned int surfaceId );
+
+private: // Data
+
+ Ecore_X_Window mX11Window; ///< X-Window
+ bool mNeedToApproveDeiconify; ///< Whether need to send ECORE_X_ATOM_E_DEICONIFY_APPROVE event
+ std::string mClassName; ///< The class name of the window
+
+}; // class WindowRenderSurface
+
+} // namespace ECore
+
+} // namespace Dali
+
+#endif // __DALI_INTERNAL_ECORE_X_WINDOW_RENDER_SURFACE_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/application.h>
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/debug.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/adaptor/common/application-impl.h>
+
+namespace Dali
+{
+
+Application Application::New()
+{
+ return New( NULL, NULL );
+}
+
+Application Application::New( int* argc, char **argv[] )
+{
+ Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
+ if( internal )
+ {
+ if( argc && ( *argc > 0 ) )
+ {
+ internal->GetWindow().SetClass( (*argv)[0], "" );
+ }
+
+ return Application( internal.Get() );
+ }
+ else
+ {
+ internal = Internal::Adaptor::Application::New( argc, argv, "", OPAQUE, PositionSize(),
+ Internal::Adaptor::Framework::NORMAL);
+ return Application(internal.Get());
+ }
+}
+
+Application Application::New( int* argc, char **argv[], const std::string& stylesheet )
+{
+ Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
+ if( internal )
+ {
+ if( argc && ( *argc > 0 ) )
+ {
+ internal->GetWindow().SetClass( (*argv)[0], "" );
+ }
+ internal->SetStyleSheet( stylesheet );
+
+ return Application( internal.Get() );
+ }
+ else
+ {
+ internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, OPAQUE, PositionSize(),
+ Internal::Adaptor::Framework::NORMAL);
+ return Application(internal.Get());
+ }
+}
+
+Application Application::New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode )
+{
+ Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
+ if( internal )
+ {
+ if( argc && ( *argc > 0 ) )
+ {
+ internal->GetWindow().SetClass( (*argv)[0], "" );
+ }
+ internal->SetStyleSheet( stylesheet );
+
+ internal->GetWindow().SetTransparency( ( windowMode == Application::OPAQUE ? false : true ) );
+
+ return Application( internal.Get() );
+ }
+ else
+ {
+ internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, windowMode, PositionSize(),
+ Internal::Adaptor::Framework::NORMAL);
+ return Application(internal.Get());
+ }
+}
+
+Application Application::New( int* argc, char **argv[], const std::string& stylesheet, Application::WINDOW_MODE windowMode, PositionSize positionSize )
+{
+ Internal::Adaptor::ApplicationPtr internal = Internal::Adaptor::Application::GetPreInitializedApplication();
+ if( internal )
+ {
+ if( argc && ( *argc > 0 ) )
+ {
+ internal->GetWindow().SetClass( (*argv)[0], "" );
+ }
+ internal->SetStyleSheet( stylesheet );
+
+ internal->GetWindow().SetTransparency( ( windowMode == Application::OPAQUE ? false : true ) );
+ internal->GetWindow().SetSize( Window::WindowSize( positionSize.width, positionSize.height ) );
+ internal->GetWindow().SetPosition( Window::WindowPosition( positionSize.x, positionSize.y ) );
+
+ return Application( internal.Get() );
+ }
+ else
+ {
+ internal = Internal::Adaptor::Application::New( argc, argv, stylesheet, windowMode, positionSize, Internal::Adaptor::Framework::NORMAL );
+ return Application( internal.Get() );
+ }
+}
+
+Application::~Application()
+{
+}
+
+Application::Application()
+{
+}
+
+Application::Application(const Application& application)
+: BaseHandle(application)
+{
+}
+
+Application& Application::operator=(const Application& application)
+{
+ if( *this != application )
+ {
+ BaseHandle::operator=( application );
+ }
+ return *this;
+}
+
+void Application::MainLoop()
+{
+ Internal::Adaptor::GetImplementation(*this).MainLoop(Configuration::APPLICATION_HANDLES_CONTEXT_LOSS);
+}
+
+void Application::MainLoop(Configuration::ContextLoss configuration)
+{
+ Internal::Adaptor::GetImplementation(*this).MainLoop(configuration);
+}
+
+void Application::Lower()
+{
+ Internal::Adaptor::GetImplementation(*this).Lower();
+}
+
+void Application::Quit()
+{
+ Internal::Adaptor::GetImplementation(*this).Quit();
+}
+
+bool Application::AddIdle( CallbackBase* callback )
+{
+ return Internal::Adaptor::GetImplementation(*this).AddIdle( callback );
+}
+
+Window Application::GetWindow()
+{
+ return Internal::Adaptor::GetImplementation(*this).GetWindow();
+}
+
+void Application::ReplaceWindow(PositionSize windowPosition, const std::string& name)
+{
+ Internal::Adaptor::GetImplementation(*this).ReplaceWindow(windowPosition, name);
+}
+
+std::string Application::GetResourcePath()
+{
+ return Internal::Adaptor::Application::GetResourcePath();
+}
+
+std::string Application::GetRegion() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetRegion();
+}
+
+std::string Application::GetLanguage() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetLanguage();
+}
+
+void Application::SetViewMode( ViewMode viewMode )
+{
+ Internal::Adaptor::GetImplementation(*this).SetViewMode( viewMode );
+}
+
+ViewMode Application::GetViewMode() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetViewMode();
+}
+
+void Application::SetStereoBase( float stereoBase )
+{
+ Internal::Adaptor::GetImplementation(*this).SetStereoBase( stereoBase );
+}
+
+float Application::GetStereoBase() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetStereoBase();
+}
+
+Application::AppSignalType& Application::InitSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).InitSignal();
+}
+
+Application::AppSignalType& Application::TerminateSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).TerminateSignal();
+}
+
+Application::AppSignalType& Application::PauseSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).PauseSignal();
+}
+
+Application::AppSignalType& Application::ResumeSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).ResumeSignal();
+}
+
+Application::AppSignalType& Application::ResetSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).ResetSignal();
+}
+
+Application::AppSignalType& Application::ResizeSignal()
+{
+ DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: ResizeSignal() is deprecated and will be removed from next release. Use Window::ResizedSignal() instead.\n" );
+
+ return Internal::Adaptor::GetImplementation(*this).ResizeSignal();
+}
+
+Application::AppControlSignalType & Application::AppControlSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).AppControlSignal();
+}
+
+Application::AppSignalType& Application::LanguageChangedSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).LanguageChangedSignal();
+}
+
+Application::AppSignalType& Application::RegionChangedSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).RegionChangedSignal();
+}
+
+Application::AppSignalType& Application::BatteryLowSignal()
+{
+ DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: BatteryLowSignal() is deprecated and will be removed from next release. Use Application::LowBatterySignal() instead.\n" );
+ return Internal::Adaptor::GetImplementation(*this).BatteryLowSignal();
+}
+
+Application::AppSignalType& Application::MemoryLowSignal()
+{
+ DALI_LOG_WARNING_NOFN( "DEPRECATION WARNING: MemoryLowSignal() is deprecated and will be removed from next release. Use Application::LowMemorySignal() instead.\n" );
+ return Internal::Adaptor::GetImplementation(*this).MemoryLowSignal();
+}
+
+Application::LowBatterySignalType& Application::LowBatterySignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).LowBatterySignal();
+}
+
+Application::LowMemorySignalType& Application::LowMemorySignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).LowMemorySignal();
+}
+
+Application::Application(Internal::Adaptor::Application* application)
+: BaseHandle(application)
+{
+}
+
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_APPLICATION_H__
+#define __DALI_APPLICATION_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/common/view-mode.h>
+#include <dali/public-api/object/base-handle.h>
+#include <dali/public-api/signals/callback.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application-configuration.h>
+#include <dali/public-api/adaptor-framework/device-status.h>
+#include <dali/public-api/adaptor-framework/window.h>
+
+namespace Dali
+{
+/**
+ * @addtogroup dali_adaptor_framework
+ * @{
+ */
+
+namespace Internal DALI_INTERNAL
+{
+namespace Adaptor
+{
+class Application;
+}
+}
+/**
+ * @brief An Application class object should be created by every application
+ * that wishes to use Dali.
+ *
+ * It provides a means for initializing the
+ * resources required by the Dali::Core.
+ *
+ * The Application class emits several signals which the user can
+ * connect to. The user should not create any Dali objects in the main
+ * function and instead should connect to the Init signal of the
+ * Application and create the Dali objects in the connected callback.
+ *
+ * Applications should follow the example below:
+ *
+ * @code
+ * class ExampleController: public ConnectionTracker
+ * {
+ * public:
+ * ExampleController( Application& application )
+ * : mApplication( application )
+ * {
+ * mApplication.InitSignal().Connect( this, &ExampleController::Create );
+ * }
+ *
+ * void Create( Application& application )
+ * {
+ * // Create Dali components...
+ * }
+ * ...
+ * private:
+ * Application& mApplication;
+ * };
+ *
+ * int main (int argc, char **argv)
+ * {
+ * Application app = Application::New(&argc, &argv);
+ * ExampleController example( app );
+ * app.MainLoop();
+ * }
+ * @endcode
+ *
+ * If required, you can also connect class member functions to a signal:
+ *
+ * @code
+ * MyApplication app;
+ * app.ResumeSignal().Connect(&app, &MyApplication::Resume);
+ * @endcode
+ *
+ * This class accepts command line arguments as well. The following options are supported:
+ *
+ * @code
+ * --no-vsync Disable VSync on Render
+ * -w|--width Stage Width
+ * -h|--height Stage Height
+ * -d|--dpi Emulated DPI
+ * --help Help
+ * @endcode
+ *
+ * When the above options are found, they are stripped from argv, and argc is updated appropriately.
+ * @SINCE_1_0.0
+ */
+class DALI_IMPORT_API Application : public BaseHandle
+{
+public:
+
+ typedef Signal< void (DeviceStatus::Battery::Status) > LowBatterySignalType; ///< Application device signal type @SINCE_1_2.62
+ typedef Signal< void (DeviceStatus::Memory::Status) > LowMemorySignalType; ///< Application device signal type @SINCE_1_2.62
+ typedef Signal< void (Application&) > AppSignalType; ///< Application lifecycle signal and system signal callback type @SINCE_1_0.0
+ typedef Signal< void (Application&, void *) > AppControlSignalType; ///< Application control signal callback type @SINCE_1_0.0
+
+ /**
+ * @brief Enumeration for deciding whether a Dali application window is opaque or transparent.
+ * @SINCE_1_0.0
+ */
+ enum WINDOW_MODE
+ {
+ OPAQUE = 0, ///< The window will be opaque @SINCE_1_0.0
+ TRANSPARENT = 1 ///< The window transparency will match the alpha value set in Dali::Stage::SetBackgroundcolor() @SINCE_1_0.0
+ };
+
+public:
+
+ /**
+ * @brief This is the constructor for applications without an argument list.
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PUBLIC
+ * @PRIVILEGE_DISPLAY
+ * @return A handle to the Application
+ */
+ static Application New();
+
+ /**
+ * @brief This is the constructor for applications.
+ *
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PUBLIC
+ * @PRIVILEGE_DISPLAY
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ * @return A handle to the Application
+ */
+ static Application New( int* argc, char **argv[] );
+
+ /**
+ * @brief This is the constructor for applications with a name.
+ *
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PUBLIC
+ * @PRIVILEGE_DISPLAY
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @return A handle to the Application
+ * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
+ */
+ static Application New( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * @brief This is the constructor for applications with a name.
+ *
+ * @SINCE_1_0.0
+ * @PRIVLEVEL_PUBLIC
+ * @PRIVILEGE_DISPLAY
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of WINDOW_MODE
+ * @return A handle to the Application
+ * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
+ */
+ static Application New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode );
+
+ /**
+ * @brief This is the constructor for applications.
+ *
+ * @SINCE_1_2.60
+ * @PRIVLEVEL_PUBLIC
+ * @PRIVILEGE_DISPLAY
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @param[in] windowMode A member of WINDOW_MODE
+ * @param[in] positionSize A position and a size of the window
+ * @return A handle to the Application
+ * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
+ */
+ static Application New( int* argc, char **argv[], const std::string& stylesheet, Application::WINDOW_MODE windowMode, PositionSize positionSize );
+
+ /**
+ * @brief Constructs an empty handle.
+ * @SINCE_1_0.0
+ */
+ Application();
+
+ /**
+ * @brief Copy Constructor.
+ * @SINCE_1_0.0
+ * @param[in] application Handle to an object
+ */
+ Application( const Application& application );
+
+ /**
+ * @brief Assignment operator.
+ * @SINCE_1_0.0
+ * @param[in] application Handle to an object
+ * @return A reference to this
+ */
+ Application& operator=( const Application& application );
+
+ /**
+ * @brief Destructor.
+ *
+ * This is non-virtual since derived Handle types must not contain data or virtual methods.
+ * @SINCE_1_0.0
+ */
+ ~Application();
+
+public:
+ /**
+ * @brief This starts the application.
+ *
+ * Choosing this form of main loop indicates that the default
+ * application configuration of APPLICATION_HANDLES_CONTEXT_LOSS is used. On platforms where
+ * context loss can occur, the application is responsible for tearing down and re-loading UI.
+ * The application should listen to Stage::ContextLostSignal and Stage::ContextRegainedSignal.
+ * @SINCE_1_0.0
+ */
+ void MainLoop();
+
+ /**
+ * @brief This starts the application, and allows the app to choose a different configuration.
+ *
+ * If the application plans on using the ReplaceSurface or ReplaceWindow API, then this will
+ * trigger context loss & regain.
+ * The application should listen to Stage::ContextLostSignal and Stage::ContextRegainedSignal.
+ * @SINCE_1_0.0
+ * @param[in] configuration The context loss configuration
+ */
+ void MainLoop(Configuration::ContextLoss configuration);
+
+ /**
+ * @brief This lowers the application to bottom without actually quitting it.
+ * @SINCE_1_0.0
+ */
+ void Lower();
+
+ /**
+ * @brief This quits the application. Tizen applications should use Lower to improve re-start performance unless they need to Quit completely.
+ * @SINCE_1_0.0
+ */
+ void Quit();
+
+ /**
+ * @brief Ensures that the function passed in is called from the main loop when it is idle.
+ * @SINCE_1_0.0
+ * @param[in] callback The function to call
+ * @return @c true if added successfully, @c false otherwise
+ *
+ * @note Function must be called from main event thread only
+ *
+ * A callback of the following type may be used:
+ * @code
+ * void MyFunction();
+ * @endcode
+ *
+ * @note Ownership of the callback is passed onto this class.
+ */
+ bool AddIdle( CallbackBase* callback );
+
+ /**
+ * @brief Retrieves the window used by the Application class.
+ *
+ * The application writer can use the window to change indicator and orientation
+ * properties.
+ * @SINCE_1_0.0
+ * @return A handle to the window
+ */
+ Window GetWindow();
+
+ /**
+ * @brief Replaces the current window.
+ *
+ * This will force context loss.
+ * If you plan on using this API in your application, then you should configure
+ * it to prevent discard behavior when handling the Init signal.
+ * @SINCE_1_0.0
+ * @param[in] windowPosition The position and size parameters of the new window
+ * @param[in] name The name of the new window
+ */
+ void ReplaceWindow(PositionSize windowPosition, const std::string& name);
+
+ /**
+ * @brief Get path application resources are stored at
+ *
+ * @SINCE_1_2.2
+ * @return the full path of the resources
+ */
+ static std::string GetResourcePath();
+
+ /**
+ * @brief This is used to get region information from device.
+ *
+ * @SINCE_1_2.62
+ * @return Region information
+ */
+ std::string GetRegion() const;
+
+ /**
+ * @brief This is used to get language information from device.
+ *
+ * @SINCE_1_2.62
+ * @return Language information
+ */
+ std::string GetLanguage() const;
+
+public: // Stereoscopy
+
+ /**
+ * @brief Sets the viewing mode for the application.
+ * @SINCE_1_0.0
+ * @param[in] viewMode The new viewing mode
+ */
+ void SetViewMode( ViewMode viewMode );
+
+ /**
+ * @brief Gets the current viewing mode.
+ * @SINCE_1_0.0
+ * @return The current viewing mode
+ */
+ ViewMode GetViewMode() const;
+
+ /**
+ * @brief Sets the stereo base (eye separation) for Stereoscopic 3D.
+ *
+ * The stereo base is the distance in millimetres between the eyes. Typical values are
+ * between 50mm and 70mm. The default value is 65mm.
+ * @SINCE_1_0.0
+ * @param[in] stereoBase The stereo base (eye separation) for Stereoscopic 3D
+ */
+ void SetStereoBase( float stereoBase );
+
+ /**
+ * @brief Gets the stereo base (eye separation) for Stereoscopic 3D.
+ *
+ * @SINCE_1_0.0
+ * @return The stereo base (eye separation) for Stereoscopic 3D
+ */
+ float GetStereoBase() const;
+
+public: // Signals
+
+ /**
+ * @brief The user should connect to this signal to determine when they should initialize
+ * their application.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& InitSignal();
+
+ /**
+ * @brief The user should connect to this signal to determine when they should terminate
+ * their application.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& TerminateSignal();
+
+ /**
+ * @brief The user should connect to this signal if they need to perform any special
+ * activities when the application is about to be paused.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& PauseSignal();
+
+ /**
+ * @brief The user should connect to this signal if they need to perform any special
+ * activities when the application has resumed.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& ResumeSignal();
+
+ /**
+ * @brief This signal is sent when the system requires the user to reinitialize itself.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& ResetSignal();
+
+ /**
+ * @DEPRECATED_1_1.43 Use Window::ResizedSignal() instead.
+ * @brief This signal is emitted when the window application rendering on is resized.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& ResizeSignal() DALI_DEPRECATED_API;
+
+ /**
+ * @brief This signal is emitted when another application sends a launch request to the application.
+ *
+ * When the application is launched, this signal is emitted after the main loop of the application starts up.
+ * The passed parameter describes the launch request and contains the information about why the application is launched.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppControlSignalType& AppControlSignal();
+
+ /**
+ * @brief This signal is emitted when the language is changed on the device.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& LanguageChangedSignal();
+
+ /**
+ * @brief This signal is emitted when the region of the device is changed.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& RegionChangedSignal();
+
+ /**
+ * @DEPRECATED_1_2.62 Use LowBatterySignal() instead.
+ * @brief This signal is emitted when the battery level of the device is low.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& BatteryLowSignal() DALI_DEPRECATED_API;
+
+ /**
+ * @DEPRECATED_1_2.62 Use LowMemorySignal() instead.
+ * @brief This signal is emitted when the memory level of the device is low.
+ * @SINCE_1_0.0
+ * @return The signal to connect to
+ */
+ AppSignalType& MemoryLowSignal() DALI_DEPRECATED_API;
+
+ /**
+ * @brief This signal is emitted when the battery level of the device is low.
+ * @SINCE_1_2.62
+ * @return The signal to connect to
+ */
+ LowBatterySignalType& LowBatterySignal();
+
+ /**
+ * @brief This signal is emitted when the memory level of the device is low.
+ * @SINCE_1_2.62
+ * @return The signal to connect to
+ */
+ LowMemorySignalType& LowMemorySignal();
+
+public: // Not intended for application developers
+ /// @cond internal
+ /**
+ * @brief Internal constructor.
+ * @SINCE_1_0.0
+ */
+ explicit DALI_INTERNAL Application(Internal::Adaptor::Application* application);
+ /// @endcond
+};
+
+/**
+ * @}
+ */
+} // namespace Dali
+
+#endif // __DALI_APPLICATION_H__
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/key.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/input/common/key-impl.h>
+
+namespace Dali
+{
+
+bool IsKey( const KeyEvent& keyEvent, KEY daliKey)
+{
+ return Internal::Adaptor::KeyLookup::IsKey( keyEvent, daliKey );
+}
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/object/any.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/imaging/common/native-image-source-impl.h>
+
+namespace Dali
+{
+
+NativeImageSourcePtr NativeImageSource::New( unsigned int width, unsigned int height, ColorDepth depth )
+{
+ Any empty;
+ NativeImageSourcePtr image = new NativeImageSource( width, height, depth, empty );
+ return image;
+}
+
+Any NativeImageSource::GetNativeImageSource()
+{
+ return mImpl->GetNativeImageSource();
+}
+
+NativeImageSourcePtr NativeImageSource::New( Any nativeImageSource )
+{
+ NativeImageSourcePtr image = new NativeImageSource(0, 0, COLOR_DEPTH_DEFAULT, nativeImageSource);
+ return image;
+}
+
+bool NativeImageSource::GetPixels( std::vector<unsigned char> &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const
+{
+ return mImpl->GetPixels( pixbuf, width, height, pixelFormat );
+}
+
+bool NativeImageSource::EncodeToFile(const std::string& filename) const
+{
+ return mImpl->EncodeToFile(filename);
+}
+
+void NativeImageSource::SetSource( Any source )
+{
+ mImpl->SetSource( source );
+}
+
+bool NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth )
+{
+ return mImpl->IsColorDepthSupported( colorDepth );
+}
+
+bool NativeImageSource::GlExtensionCreate()
+{
+ return mImpl->GlExtensionCreate();
+}
+
+void NativeImageSource::GlExtensionDestroy()
+{
+ mImpl->GlExtensionDestroy();
+}
+
+unsigned int NativeImageSource::TargetTexture()
+{
+ return mImpl->TargetTexture();
+}
+
+void NativeImageSource::PrepareTexture()
+{
+ mImpl->PrepareTexture();
+}
+
+unsigned int NativeImageSource::GetWidth() const
+{
+ return mImpl->GetWidth();
+}
+
+unsigned int NativeImageSource::GetHeight() const
+{
+ return mImpl->GetHeight();
+}
+
+bool NativeImageSource::RequiresBlending() const
+{
+ return mImpl->RequiresBlending();
+}
+
+NativeImageInterface::Extension* NativeImageSource::GetExtension()
+{
+ return mImpl->GetNativeImageInterfaceExtension();
+}
+
+NativeImageSource::NativeImageSource( unsigned int width, unsigned int height, ColorDepth depth, Any nativeImageSource )
+{
+ mImpl = Internal::Adaptor::NativeImageSource::New( width, height, depth, nativeImageSource );
+}
+
+NativeImageSource::~NativeImageSource()
+{
+ delete mImpl;
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/timer.h>
+
+// EXTERNAL INCLUDES
+#include <dali/public-api/common/dali-common.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/timer-impl.h>
+
+namespace Dali
+{
+
+Timer::Timer()
+{
+}
+
+Timer Timer::New( unsigned int milliSec )
+{
+ Internal::Adaptor::TimerPtr internal = Internal::Adaptor::Timer::New( milliSec );
+ return Timer(internal.Get());
+}
+
+Timer::Timer( const Timer& timer )
+: BaseHandle(timer)
+{
+}
+
+Timer& Timer::operator=( const Timer& timer )
+{
+ // check self assignment
+ if( *this != timer )
+ {
+ BaseHandle::operator=(timer);
+ }
+ return *this;
+}
+
+Timer::~Timer()
+{
+}
+
+Timer Timer::DownCast( BaseHandle handle )
+{
+ return Timer( dynamic_cast<Internal::Adaptor::Timer*>( handle.GetObjectPtr() ) );
+}
+
+void Timer::Start()
+{
+ Internal::Adaptor::GetImplementation(*this).Start();
+}
+
+void Timer::Stop()
+{
+ Internal::Adaptor::GetImplementation(*this).Stop();
+}
+
+void Timer::SetInterval( unsigned int interval )
+{
+ Internal::Adaptor::GetImplementation(*this).SetInterval( interval );
+}
+
+unsigned int Timer::GetInterval() const
+{
+ return Internal::Adaptor::GetImplementation(*this).GetInterval();
+}
+
+bool Timer::IsRunning() const
+{
+ return Internal::Adaptor::GetImplementation(*this).IsRunning();
+}
+
+Timer::TimerSignalType& Timer::TickSignal()
+{
+ return Internal::Adaptor::GetImplementation(*this).TickSignal();
+}
+
+Timer::Timer(Internal::Adaptor::Timer* timer)
+: BaseHandle(timer)
+{
+}
+
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/tts-player.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/accessibility/common/tts-player-impl.h>
+#include <dali/internal/adaptor/common/adaptor-impl.h>
+
+namespace Dali
+{
+
+TtsPlayer::TtsPlayer()
+{
+}
+
+TtsPlayer TtsPlayer::Get(Dali::TtsPlayer::Mode mode)
+{
+ TtsPlayer ttsPlayer;
+
+ if ( Adaptor::IsAvailable() )
+ {
+ ttsPlayer = Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetTtsPlayer(mode);
+ }
+
+ return ttsPlayer;
+}
+
+TtsPlayer::~TtsPlayer()
+{
+}
+
+TtsPlayer::TtsPlayer(const TtsPlayer& handle)
+: BaseHandle(handle)
+{
+}
+
+TtsPlayer& TtsPlayer::operator=(const TtsPlayer& rhs)
+{
+ BaseHandle::operator=(rhs);
+ return *this;
+}
+
+void TtsPlayer::Play(const std::string& text)
+{
+ GetImplementation(*this).Play(text);
+}
+
+void TtsPlayer::Stop()
+{
+ GetImplementation(*this).Stop();
+}
+
+void TtsPlayer::Pause()
+{
+ GetImplementation(*this).Pause();
+}
+
+void TtsPlayer::Resume()
+{
+ GetImplementation(*this).Resume();
+}
+
+TtsPlayer::State TtsPlayer::GetState()
+{
+ return GetImplementation(*this).GetState();
+}
+
+TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal()
+{
+ return GetImplementation(*this).StateChangedSignal();
+}
+
+TtsPlayer::TtsPlayer( Internal::Adaptor::TtsPlayer* player )
+: BaseHandle( player )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/widget-application.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/widget-application-impl.h>
+
+namespace Dali
+{
+
+WidgetApplication WidgetApplication::New( int* argc, char **argv[], const std::string& stylesheet )
+{
+ Internal::Adaptor::WidgetApplicationPtr internal = Internal::Adaptor::WidgetApplication::New( argc, argv, stylesheet);
+ return WidgetApplication(internal.Get());
+}
+
+WidgetApplication::~WidgetApplication()
+{
+}
+
+WidgetApplication::WidgetApplication()
+{
+}
+
+WidgetApplication::WidgetApplication(const WidgetApplication& widgetApplication)
+: Application(widgetApplication)
+{
+}
+
+WidgetApplication& WidgetApplication::operator=(const WidgetApplication& widgetApplication)
+{
+ if( *this != widgetApplication )
+ {
+ BaseHandle::operator=( widgetApplication );
+ }
+ return *this;
+}
+
+void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, CreateWidgetFunction createFunction )
+{
+ Internal::Adaptor::GetImplementation(*this).RegisterWidgetCreatingFunction( widgetName, createFunction );
+}
+
+WidgetApplication::WidgetApplication(Internal::Adaptor::WidgetApplication* widgetApplication)
+: Application(widgetApplication)
+{
+}
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_WIDGET_APPLICATION_H
+#define DALI_WIDGET_APPLICATION_H
+
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application.h>
+
+namespace Dali
+{
+
+namespace Internal DALI_INTERNAL
+{
+
+namespace Adaptor
+{
+class WidgetApplication;
+}
+
+}
+
+class Widget;
+
+/**
+ * @brief An WidgetApplication class object should be created by every widget application
+ * that wishes to use Dali.
+ *
+ * It provides a means for initializing the
+ * resources required by the Dali::Core.
+ *
+ * The WidgetApplication class emits several signals which the user can
+ * connect to. The user should not create any Dali objects in the main
+ * function and instead should connect to the Init signal of the
+ * WidgetApplication and create the Dali Widget object in the connected callback.
+ *
+ * WidgetApplications should follow the example below:
+ *
+ * @code
+ *
+ * //Widget header which
+ * #include <my-widget.h>
+ *
+ * class ExampleController: public ConnectionTracker
+ * {
+ * public:
+ * ExampleController( Application& application )
+ * : mWidgetApplication( application )
+ * {
+ * mApplication.InitSignal().Connect( this, &ExampleController::Create );
+ * }
+ *
+ * static Widget CreateWidgetFunction(const std::string& widgetName)
+ * {
+ * MyWidget widget = MyWidget::New();
+ * return widget;
+ * }
+ *
+ * void Create( Application& application )
+ * {
+ * mApplication.RegisterWidgetCreatingFunction( "myWidget", &ExampleController::CreateWidgetFunction );
+ * }
+ *
+ * private:
+ * WidgetApplication& mWidgetApplication;
+ * };
+ *
+ * int main (int argc, char **argv)
+ * {
+ * WidgetApplication app = WidgetApplication::New(&argc, &argv);
+ * ExampleController example( app );
+ * app.MainLoop();
+ * }
+ * @endcode
+ *
+ * If required, you can also connect class member functions to a signal:
+ *
+ * @code
+ * MyWidgetApplication app;
+ * app.ResumeSignal().Connect(&app, &MyWidgetApplication::Resume);
+ * @endcode
+ *
+ * @SINCE_1_3_5
+ */
+class DALI_IMPORT_API WidgetApplication : public Application
+{
+public:
+
+ /**
+ * @brief This is the typedef for Widget creator.
+ * @SINCE_1_3_5
+ */
+ typedef Widget(*CreateWidgetFunction)(const std::string&);
+
+public:
+
+ /**
+ * @brief This is the constructor for WidgetApplications with a name.
+ *
+ * @SINCE_1_3_5
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer to the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @return A handle to the WidgetApplication
+ * @note If the stylesheet is not specified, then the library's default stylesheet will not be overridden.
+ */
+ static WidgetApplication New( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * @brief The default constructor.
+ * @SINCE_1_3_5
+ */
+ WidgetApplication();
+
+ /**
+ * @brief Copy Constructor.
+ *
+ * @SINCE_1_3_5
+ * @param[in] widgetApplication Handle to an object
+ */
+ WidgetApplication( const WidgetApplication& widgetApplication );
+
+ /**
+ * @brief Assignment operator.
+ *
+ * @SINCE_1_3_5
+ * @param[in] widgetApplication Handle to an object
+ * @return A reference to this
+ */
+ WidgetApplication& operator=( const WidgetApplication& widgetApplication );
+
+ /**
+ * @brief Destructor
+ * @SINCE_1_3_5
+ */
+ ~WidgetApplication();
+
+ /**
+ * @brief Register create function for widget.
+ *
+ * @SINCE_1_3_5
+ * @param[in] widgetName Name of widget
+ * @param[in] createFunction Function pointer for widget creation.
+ */
+ void RegisterWidgetCreatingFunction( const std::string& widgetName, CreateWidgetFunction createFunction );
+
+public: // Not intended for application developers
+ /// @cond internal
+ /**
+ * @brief Internal constructor.
+ */
+ explicit DALI_INTERNAL WidgetApplication(Internal::Adaptor::WidgetApplication* widgetApplication);
+ /// @endcond
+};
+
+} // namespace Dali
+
+#endif // DALI_WIDGET_APPLICATION_H
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/widget.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/system/common/widget-impl.h>
+
+namespace Dali
+{
+
+Widget Widget::New()
+{
+ Internal::Adaptor::WidgetPtr internal = Internal::Adaptor::Widget::New();
+ return Widget(internal.Get());
+}
+
+Widget::~Widget()
+{
+}
+
+Widget::Widget()
+{
+}
+
+Widget::Widget(const Widget& widget)
+: BaseHandle(widget)
+{
+}
+
+Widget& Widget::operator=(const Widget& widget)
+{
+ if( *this != widget )
+ {
+ BaseHandle::operator=( widget );
+ }
+ return *this;
+}
+
+Widget::Widget(Internal::Adaptor::Widget* widget)
+: BaseHandle(widget)
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <dali/public-api/adaptor-framework/window.h>
+
+// INTERNAL INCLUDES
+#include <dali/internal/window-system/common/window-impl.h>
+#include <dali/internal/window-system/common/orientation-impl.h>
+
+namespace Dali
+{
+
+Window Window::New(PositionSize posSize, const std::string& name, bool isTransparent)
+{
+ Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, "", isTransparent);
+ return Window(window);
+}
+
+Window Window::New(PositionSize posSize, const std::string& name, const std::string& className, bool isTransparent)
+{
+ Internal::Adaptor::Window* window = Internal::Adaptor::Window::New(posSize, name, className, isTransparent);
+ return Window(window);
+}
+
+Window::Window()
+{
+}
+
+Window::~Window()
+{
+}
+
+Window::Window(const Window& handle)
+: BaseHandle(handle)
+{
+}
+
+Window& Window::operator=(const Window& rhs)
+{
+ BaseHandle::operator=(rhs);
+ return *this;
+}
+
+void Window::ShowIndicator( IndicatorVisibleMode visibleMode )
+{
+ GetImplementation(*this).ShowIndicator( visibleMode );
+}
+
+Window::IndicatorSignalType& Window::IndicatorVisibilityChangedSignal()
+{
+ return GetImplementation(*this).IndicatorVisibilityChangedSignal();
+}
+
+void Window::SetIndicatorBgOpacity( IndicatorBgOpacity opacity )
+{
+ GetImplementation(*this).SetIndicatorBgOpacity( opacity );
+}
+
+void Window::RotateIndicator( WindowOrientation orientation )
+{
+ GetImplementation(*this).RotateIndicator( orientation );
+}
+
+void Window::SetClass( std::string name, std::string klass )
+{
+ GetImplementation(*this).SetClass( name, klass );
+}
+
+void Window::Raise()
+{
+ GetImplementation(*this).Raise();
+}
+
+void Window::Lower()
+{
+ GetImplementation(*this).Lower();
+}
+
+void Window::Activate()
+{
+ GetImplementation(*this).Activate();
+}
+
+void Window::AddAvailableOrientation( WindowOrientation orientation )
+{
+ GetImplementation(*this).AddAvailableOrientation( orientation );
+}
+
+void Window::RemoveAvailableOrientation( WindowOrientation orientation )
+{
+ GetImplementation(*this).RemoveAvailableOrientation( orientation );
+}
+
+void Window::SetPreferredOrientation( Dali::Window::WindowOrientation orientation )
+{
+ GetImplementation(*this).SetPreferredOrientation( orientation );
+}
+
+Dali::Window::WindowOrientation Window::GetPreferredOrientation()
+{
+ return GetImplementation(*this).GetPreferredOrientation();
+}
+
+DragAndDropDetector Window::GetDragAndDropDetector() const
+{
+ return GetImplementation(*this).GetDragAndDropDetector();
+}
+
+Any Window::GetNativeHandle() const
+{
+ return GetImplementation(*this).GetNativeHandle();
+}
+
+Window::FocusSignalType& Window::FocusChangedSignal()
+{
+ return GetImplementation(*this).FocusChangedSignal();
+}
+
+void Window::SetAcceptFocus( bool accept )
+{
+ GetImplementation(*this).SetAcceptFocus( accept );
+}
+
+bool Window::IsFocusAcceptable() const
+{
+ return GetImplementation(*this).IsFocusAcceptable();
+}
+
+void Window::Show()
+{
+ GetImplementation(*this).Show();
+}
+
+void Window::Hide()
+{
+ GetImplementation(*this).Hide();
+}
+
+bool Window::IsVisible() const
+{
+ return GetImplementation(*this).IsVisible();
+}
+
+unsigned int Window::GetSupportedAuxiliaryHintCount() const
+{
+ return GetImplementation(*this).GetSupportedAuxiliaryHintCount();
+}
+
+std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const
+{
+ return GetImplementation(*this).GetSupportedAuxiliaryHint( index );
+}
+
+unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value )
+{
+ return GetImplementation(*this).AddAuxiliaryHint( hint, value );
+}
+
+bool Window::RemoveAuxiliaryHint( unsigned int id )
+{
+ return GetImplementation(*this).RemoveAuxiliaryHint( id );
+}
+
+bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value )
+{
+ return GetImplementation(*this).SetAuxiliaryHintValue( id, value );
+}
+
+std::string Window::GetAuxiliaryHintValue( unsigned int id ) const
+{
+ return GetImplementation(*this).GetAuxiliaryHintValue( id );
+}
+
+unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const
+{
+ return GetImplementation(*this).GetAuxiliaryHintId( hint );
+}
+
+void Window::SetInputRegion( const Rect< int >& inputRegion )
+{
+ return GetImplementation(*this).SetInputRegion( inputRegion );
+}
+
+void Window::SetType( Window::Type type )
+{
+ GetImplementation(*this).SetType( type );
+}
+
+Window::Type Window::GetType() const
+{
+ return GetImplementation(*this).GetType();
+}
+
+bool Window::SetNotificationLevel( Window::NotificationLevel::Type level )
+{
+ return GetImplementation(*this).SetNotificationLevel( level );
+}
+
+Window::NotificationLevel::Type Window::GetNotificationLevel() const
+{
+ return GetImplementation(*this).GetNotificationLevel();
+}
+
+void Window::SetOpaqueState( bool opaque )
+{
+ GetImplementation(*this).SetOpaqueState( opaque );
+}
+
+bool Window::IsOpaqueState() const
+{
+ return GetImplementation(*this).IsOpaqueState();
+}
+
+bool Window::SetScreenOffMode(Window::ScreenOffMode::Type screenMode)
+{
+ return GetImplementation(*this).SetScreenOffMode(screenMode);
+}
+
+Window::ScreenOffMode::Type Window::GetScreenOffMode() const
+{
+ return GetImplementation(*this).GetScreenOffMode();
+}
+
+bool Window::SetBrightness( int brightness )
+{
+ return GetImplementation(*this).SetBrightness( brightness );
+}
+
+int Window::GetBrightness() const
+{
+ return GetImplementation(*this).GetBrightness();
+}
+
+Window::ResizedSignalType& Window::ResizedSignal()
+{
+ return GetImplementation(*this).ResizedSignal();
+}
+
+void Window::SetSize( Window::WindowSize size )
+{
+ GetImplementation(*this).SetSize( size );
+}
+
+Window::WindowSize Window::GetSize() const
+{
+ return GetImplementation(*this).GetSize();
+}
+
+void Window::SetPosition( Window::WindowPosition position )
+{
+ GetImplementation(*this).SetPosition( position );
+}
+
+Window::WindowPosition Window::GetPosition() const
+{
+ return GetImplementation(*this).GetPosition();
+}
+
+void Window::SetTransparency( bool transparent )
+{
+ GetImplementation(*this).SetTransparency( transparent );
+}
+
+Window::Window( Internal::Adaptor::Window* window )
+: BaseHandle( window )
+{
+}
+
+} // namespace Dali
--- /dev/null
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// HEADER
+#include <dali/public-api/dali-adaptor-version.h>
+
+// EXTERNAL INCLUDES
+#ifdef DEBUG_ENABLED
+#include <iostream>
+#endif
+
+namespace Dali
+{
+
+const unsigned int ADAPTOR_MAJOR_VERSION = 1;
+const unsigned int ADAPTOR_MINOR_VERSION = 3;
+const unsigned int ADAPTOR_MICRO_VERSION = 7;
+const char * const ADAPTOR_BUILD_DATE = __DATE__ " " __TIME__;
+
+#ifdef DEBUG_ENABLED
+namespace
+{
+/// Allows the printing of the version number ONLY when debug is enabled
+struct PrintVersion
+{
+ PrintVersion()
+ {
+ std::cerr << "DALi Adaptor: " << ADAPTOR_MAJOR_VERSION << "." << ADAPTOR_MINOR_VERSION << "." << ADAPTOR_MICRO_VERSION << " (" << ADAPTOR_BUILD_DATE << ")" << std::endl;
+ }
+};
+PrintVersion ADAPTOR_VERSION;
+} // unnamed namespace
+#endif
+
+} // namespace Dali
--- /dev/null
+#ifndef __DALI_H__
+#define __DALI_H__
+
+/*
+ * Copyright (c) 2015 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <dali/public-api/dali-core.h>
+
+// Application / UI Framework adaption
+#include <dali/public-api/adaptor-framework/application.h>
+#include <dali/public-api/adaptor-framework/device-status.h>
+#include <dali/public-api/adaptor-framework/input-method.h>
+#include <dali/public-api/adaptor-framework/key.h>
+#include <dali/public-api/adaptor-framework/timer.h>
+#include <dali/public-api/adaptor-framework/tts-player.h>
+#include <dali/public-api/adaptor-framework/native-image-source.h>
+#include <dali/public-api/adaptor-framework/widget-application.h>
+#include <dali/public-api/adaptor-framework/widget.h>
+#include <dali/public-api/dali-adaptor-version.h>
+
+#endif //__DALI_H__
--- /dev/null
+adaptor_public_api_src_files = \
+ $(adaptor_public_api_dir)/adaptor-framework/application.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/key.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/window.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/timer.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/tts-player.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/native-image-source.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/widget.cpp \
+ $(adaptor_public_api_dir)/adaptor-framework/widget-application.cpp \
+ $(adaptor_public_api_dir)/dali-adaptor-version.cpp
+
+
+public_api_header_files = \
+ $(adaptor_public_api_dir)/dali-adaptor-version.h
+
+
+public_api_adaptor_framework_header_files = \
+ $(adaptor_public_api_dir)/adaptor-framework/application.h \
+ $(adaptor_public_api_dir)/adaptor-framework/application-configuration.h \
+ $(adaptor_public_api_dir)/adaptor-framework/device-status.h \
+ $(adaptor_public_api_dir)/adaptor-framework/input-method.h \
+ $(adaptor_public_api_dir)/adaptor-framework/key.h \
+ $(adaptor_public_api_dir)/adaptor-framework/style-change.h \
+ $(adaptor_public_api_dir)/adaptor-framework/timer.h \
+ $(adaptor_public_api_dir)/adaptor-framework/tts-player.h \
+ $(adaptor_public_api_dir)/adaptor-framework/native-image-source.h \
+ $(adaptor_public_api_dir)/adaptor-framework/window.h \
+ $(adaptor_public_api_dir)/adaptor-framework/widget.h \
+ $(adaptor_public_api_dir)/adaptor-framework/widget-application.h
+
+adaptor_dali_header_file = \
+ $(adaptor_public_api_dir)/dali.h
+
+# wearable and watch extra public headers
+adaptor_dali_wearable_header_file = \
+ $(adaptor_public_api_dir)/watch/dali-wearable.h
+
+public_dali_watch_header_files = \
+ $(adaptor_public_api_dir)/watch/watch-application.h \
+ $(adaptor_public_api_dir)/watch/watch-time.h
+
+public_dali_capture_header_files = \
+ $(adaptor_public_api_dir)/capture/capture.h
+
--- /dev/null
+#ifndef __DALI_WATCH_APPLICATION_H__
+#define __DALI_WATCH_APPLICATION_H__
+
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// EXTERNAL INCLUDES
+#include <string>
+#include <dali/public-api/object/base-handle.h>
+#include <dali/public-api/signals/callback.h>
+
+// INTERNAL INCLUDES
+#include <dali/public-api/adaptor-framework/application.h>
+#include <dali/public-api/watch/watch-time.h>
+
+namespace Dali
+{
+/**
+ * @addtogroup dali_adaptor_framework
+ * @{
+ */
+namespace Internal DALI_INTERNAL
+{
+namespace Adaptor
+{
+class WatchApplication;
+}
+}
+
+/**
+ * @brief A WatchApplication class object should be created by every watch application
+ * that wishes to use Dali.
+ *
+ * It provides a means for initialising the resources required by the Dali::Core.
+ * Like Application class, the WatchApplication class manages Tizen watch application life cycle.
+ *
+ * The WatchApplication class emits additional signals which are availalble only in the watch application
+ * (TimeTick, AmbientTick, AmbientChanged)
+ *
+ * This feature is supported in wearable applications only.
+ *
+ * WatchApplication should follow the example below:
+ *
+ * @code
+ * class ExampleController: public ConnectionTracker
+ * {
+ * public:
+ * ExampleController( WatchApplication& application )
+ * : mApplication( application )
+ * {
+ * mApplication.InitSignal().Connect( this, &ExampleController::Create );
+ * }
+ *
+ * void Create( Application& application )
+ * {
+ * // Create Dali components...
+ * }
+ * ...
+ * private:
+ * WatchApplication& mApplication;
+ * };
+ *
+ * int DALI_EXPORT_API main (int argc, char **argv)
+ * {
+ * WatchApplication app = WatchApplication::New(&argc, &argv);
+ * ExampleController example( app );
+ * app.MainLoop();
+ * }
+ * @endcode
+ *
+ * If required, you can also connect class member functions to a signal:
+ *
+ * @code
+ * MyApplication app;
+ * app.ResumeSignal().Connect(&app, &MyApplication::Resume);
+ * @endcode
+ *
+ * When the above options are found, they are stripped from argv, and argc is updated appropriately.
+ * @SINCE_1_1.37
+ */
+
+class DALI_IMPORT_API WatchApplication : public Application
+{
+public:
+ typedef Signal< void (Application&, const WatchTime&) > WatchTimeSignal; ///< Watch pointer signal callback type @SINCE_1_1.37
+ typedef Signal< void (Application&, bool) > WatchBoolSignal; ///< Watch bool signal callback type @SINCE_1_1.37
+
+public:
+
+ /**
+ * @brief This is the constructor for applications without an argument list.
+ * @SINCE_1_1.37
+ * @return A handle to the WatchApplication
+ */
+ static WatchApplication New();
+
+ /**
+ * @brief This is the constructor for applications.
+ *
+ * @SINCE_1_1.37
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer the the argument list
+ * @return A handle to the WatchApplication
+ */
+ static WatchApplication New( int* argc, char **argv[] );
+
+ /**
+ * @brief This is the constructor for applications with a name
+ *
+ * @SINCE_1_1.37
+ * @param[in,out] argc A pointer to the number of arguments
+ * @param[in,out] argv A pointer the the argument list
+ * @param[in] stylesheet The path to user defined theme file
+ * @return A handle to the WatchApplication
+ */
+ static WatchApplication New( int* argc, char **argv[], const std::string& stylesheet );
+
+ /**
+ * @brief Construct an empty handle
+ * @SINCE_1_1.37
+ */
+ WatchApplication();
+
+ /**
+ * @brief Copy Constructor
+ * @SINCE_1_1.37
+ * @param[in] implementation The WatchApplication implementation
+ */
+ WatchApplication( const WatchApplication& implementation );
+
+ /**
+ * @brief Assignment operator
+ * @SINCE_1_1.37
+ * @param[in] application Handle to an object
+ * @return A reference to this
+ */
+ WatchApplication& operator=( const WatchApplication& application );
+
+ /**
+ * @brief Destructor
+ *
+ * This is non-virtual since derived Handle types must not contain data or virtual methods.
+ * @SINCE_1_1.37
+ */
+ ~WatchApplication();
+
+public:
+ /**
+ * @brief This signal is emitted at every second
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(Application& application, const WatchTime& time);
+ * @endcode
+ * time(watch time handle) will not be available after returning this callback. It will be freed by the framework.
+ * @SINCE_1_1.37
+ * @return The signal to connect to
+ */
+ WatchTimeSignal& TimeTickSignal();
+
+ /**
+ * @brief This signal is emitted at each minute in ambient mode
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(Application& application, const WatchTime& time);
+ * @endcode
+ * time(watch time handle) will not be available after returning this callback. It will be freed by the framework.
+ * @SINCE_1_1.37
+ * @remarks http://tizen.org/privilege/alarm.set privilege is needed to receive ambient ticks at each minute.
+ * The AmbientTickSignal() will be ignored if your app doesn't have the privilege
+ * @return The signal to connect to
+ */
+ WatchTimeSignal& AmbientTickSignal();
+
+ /**
+ * @brief This signal is emitted when the device enters or exits ambient mode
+ * A callback of the following type may be connected:
+ * @code
+ * void YourCallbackName(Application& application, bool ambient);
+ * @endcode
+ * ambient_mode If true the device enters the ambient mode, otherwise false
+ * @SINCE_1_1.37
+ * @return The signal to connect to
+ */
+ WatchBoolSignal& AmbientChangedSignal();
+
+public: // Not intended for application developers
+ /// @cond internal
+ /**
+ * @brief Internal constructor
+ * @SINCE_1_1.37
+ */
+ explicit DALI_INTERNAL WatchApplication(Internal::Adaptor::WatchApplication* implementation);
+ /// @endcond
+};
+
+/**
+ * @}
+ */
+} // namespace Dali
+
+#endif // __DALI_WATCH_APPLICATION_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "pixel-manipulation.h"
-#include "alpha-mask.h"
-#include "pixel-buffer-impl.h"
-#include <dali/public-api/images/image-operations.h> // For ImageDimensions
-#include <platform-abstractions/portable/image-operations.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask )
-{
- int srcAlphaByteOffset=0;
- int srcAlphaMask=0;
- Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat();
-
- if( Pixel::HasAlpha(srcPixelFormat) )
- {
- Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask );
- }
- else if( srcPixelFormat == Pixel::L8 )
- {
- srcAlphaMask=0xFF;
- }
-
- int destAlphaByteOffset=0;
- int destAlphaMask=0;
- Dali::Pixel::GetAlphaOffsetAndMask( buffer.GetPixelFormat(), destAlphaByteOffset, destAlphaMask );
-
- unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat );
- unsigned char* srcBuffer = mask.GetBuffer();
- unsigned char* destBuffer = buffer.GetBuffer();
-
- unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( buffer.GetPixelFormat() );
-
- int srcOffset=0;
- int destOffset=0;
-
- float srcAlphaValue = 1.0f;
-
- for( unsigned int row = 0; row < buffer.GetHeight(); ++row )
- {
- for( unsigned int col = 0; col < buffer.GetWidth(); ++col )
- {
- unsigned char alpha = srcBuffer[srcOffset + srcAlphaByteOffset] & srcAlphaMask;
- srcAlphaValue = float(alpha)/255.0f;
-
- unsigned char destAlpha = destBuffer[destOffset + destAlphaByteOffset] & destAlphaMask;
- float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f);
- destAlpha = destAlphaValue;
- destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask;
- destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask );
-
- srcOffset += srcBytesPerPixel;
- destOffset += destBytesPerPixel;
- }
- }
-}
-
-PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask )
-{
- // Set up source alpha offsets
- int srcAlphaByteOffset=0;
- int srcAlphaMask=0;
- Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat();
-
- if( Pixel::HasAlpha(srcPixelFormat) )
- {
- Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask );
- }
- else if( srcPixelFormat == Pixel::L8 )
- {
- srcAlphaMask=0xFF;
- }
-
- unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat );
- unsigned char* srcBuffer = mask.GetBuffer();
-
- // Set up source color offsets
- Dali::Pixel::Format srcColorPixelFormat = buffer.GetPixelFormat();
- unsigned int srcColorBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcColorPixelFormat );
-
- // Setup destination offsets
- Dali::Pixel::Format destPixelFormat = Dali::Pixel::RGBA8888;
- unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( destPixelFormat );
- int destAlphaByteOffset=0;
- int destAlphaMask=0;
- Dali::Pixel::GetAlphaOffsetAndMask( destPixelFormat, destAlphaByteOffset, destAlphaMask );
-
- PixelBufferPtr newPixelBuffer = PixelBuffer::New( buffer.GetWidth(), buffer.GetHeight(),
- destPixelFormat );
- unsigned char* destBuffer = newPixelBuffer->GetBuffer();
- unsigned char* oldBuffer = buffer.GetBuffer();
-
- int srcAlphaOffset=0;
- int srcColorOffset=0;
- int destOffset=0;
- bool hasAlpha = Dali::Pixel::HasAlpha(buffer.GetPixelFormat());
-
- float srcAlphaValue = 1.0f;
- unsigned char destAlpha = 0;
-
- for( unsigned int row = 0; row < buffer.GetHeight(); ++row )
- {
- for( unsigned int col = 0; col < buffer.GetWidth(); ++col )
- {
- unsigned char alpha = srcBuffer[srcAlphaOffset + srcAlphaByteOffset] & srcAlphaMask;
- srcAlphaValue = float(alpha)/255.0f;
-
- ConvertColorChannelsToRGBA8888(oldBuffer, srcColorOffset, srcColorPixelFormat, destBuffer, destOffset );
-
- if( hasAlpha )
- {
- destAlpha = ConvertAlphaChannelToA8( oldBuffer, srcColorOffset, srcColorPixelFormat );
- float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f);
- destAlpha = destAlphaValue;
- }
- else
- {
- destAlpha = floorf(Clamp(srcAlphaValue * 255.0f, 0.0f, 255.0f));
- }
-
- destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask;
- destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask );
-
- srcColorOffset += srcColorBytesPerPixel;
- srcAlphaOffset += srcBytesPerPixel;
- destOffset += destBytesPerPixel;
- }
- }
-
- return newPixelBuffer;
-}
-
-} //namespace Adaptor
-
-}// namespace Internal
-
-}// namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
-#define DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "pixel-buffer-impl.h"
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-/**
- * Apply the mask to a buffer's alpha channel
- * @param[in] buffer The buffer to apply the mask to
- * @param[in] mask The mask to apply
- */
-void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask );
-
-/**
- * Create a new PixelBuffer with an alpha channel large enough to handle the alpha from
- * the mask, converting the color values to the new size, and either multiplying the mask's
- * alpha into the existing alpha value, or writing the mask's alpha value directly into
- * the new buffer's alpha channel.
- *
- * @param[in] buffer The buffer to apply the mask to
- * @param[in] mask The mask to apply
- * @return A new pixel buffer containing the masked image
- */
-PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask );
-
-} //namespace Adaptor
-} //namespace Internal
-} //namespace Dali
-
-#endif // DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H
+++ /dev/null
-#ifndef DALI_INTERNAL_PORTABLE_FILE_READER_H
-#define DALI_INTERNAL_PORTABLE_FILE_READER_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// INTERNAL INCLUDES
-#include "file-closer.h"
-
-// EXTERNAL INCLUDES
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Platform
-{
-
-class FileReader : public FileCloser
-{
-public:
- FileReader( const std::string& filename )
- : FileCloser( filename.c_str(), "rb" )
- {
- }
-
- FileReader( Dali::Vector<uint8_t>& vector )
- : FileCloser( &vector[0], vector.Size(), "rb" )
- {
- }
-
- FileReader( Dali::Vector<uint8_t>& vector, size_t dataSize )
- : FileCloser( &vector[0], dataSize, "rb" )
- {
- }
-
- FileReader( uint8_t* data, size_t dataSize )
- : FileCloser( data, dataSize, "rb" )
- {
- }
-};
-
-} /* namespace Platform */
-} /* namespace Internal */
-} /* namespace Dali */
-
-#endif // DALI_INTERNAL_PORTABLE_FILE_READER_H
+++ /dev/null
-#ifndef DALI_INTERNAL_PORTABLE_FILE_WRITER_H
-#define DALI_INTERNAL_PORTABLE_FILE_WRITER_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// INTERNAL INCLUDES
-#include "file-closer.h"
-
-// EXTERNAL INCLUDES
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Platform
-{
-
-class FileWriter : public FileCloser
-{
-public:
- /**
- * Opens a file pointer onto the memory for writing to.
- * Note, in some implementations, the vector may be resized to be larger than dataSize.
- * @param[in,out] vector The vector to write to
- * @param[in] dataSize the amount of data to be written
- */
- FileWriter( Dali::Vector<uint8_t>& vector, size_t dataSize )
- : FileCloser( vector, dataSize, "wb" )
- {
- }
-};
-
-} /* namespace Platform */
-} /* namespace Internal */
-} /* namespace Dali */
-
-#endif // DALI_INTERNAL_PORTABLE_FILE_WRITER_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// EXTERNAL INCLUDES
-#include <memory.h>
-
-// INTERNAL INCLUDES
-#include "gaussian-blur.h"
-#include "pixel-buffer-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-
-
-void ConvoluteAndTranspose( unsigned char* inBuffer,
- unsigned char* outBuffer,
- const unsigned int bufferWidth,
- const unsigned int bufferHeight,
- const float blurRadius )
-{
- // Calculate the weights for gaussian blur
- int radius = static_cast<int>( std::ceil( blurRadius ) );
- int rows = radius * 2 + 1;
-
- float sigma = ( blurRadius < Math::MACHINE_EPSILON_1 ) ? 0.0f : blurRadius * 0.4f + 0.6f; // The same equation used by Android
- float sigma22 = 2.0f * sigma * sigma;
- float sqrtSigmaPi2 = std::sqrt( 2.0f * Math::PI ) * sigma;
- float radius2 = radius * radius;
- float normalizeFactor = 0.0f;
-
- float* weightMatrix = new float[rows];
- int index = 0;
-
- for ( int row = -radius; row <= radius; row++ )
- {
- float distance = row * row;
- if ( distance > radius2 )
- {
- weightMatrix[index] = 0.0f;
- }
- else
- {
- weightMatrix[index] = static_cast<float>( std::exp( -( distance ) / sigma22 ) / sqrtSigmaPi2 );
- }
- normalizeFactor += weightMatrix[index];
- index++;
- }
-
- for ( int i = 0; i < rows; i++ )
- {
- weightMatrix[i] /= normalizeFactor;
- }
-
- // Perform the convolution and transposition using the weights
- int columns = rows;
- int columns2 = columns / 2;
- for ( unsigned int y = 0; y < bufferHeight; y++ )
- {
- unsigned int targetPixelIndex = y;
- unsigned int ioffset = y * bufferWidth;
- for ( unsigned int x = 0; x < bufferWidth; x++ )
- {
- float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f;
- int weightColumnOffset = columns2;
- for ( int column = -columns2; column <= columns2; column++ )
- {
- float weight = weightMatrix[weightColumnOffset + column];
- if ( fabsf( weight ) > Math::MACHINE_EPSILON_1 )
- {
- int ix = x + column;
- ix = std::max( 0, std::min( ix, static_cast<int>( bufferWidth - 1 ) ) );
- unsigned int sourcePixelIndex = ioffset + ix;
- r += weight * inBuffer[sourcePixelIndex*4];
- g += weight * inBuffer[sourcePixelIndex*4+1];
- b += weight * inBuffer[sourcePixelIndex*4+2];
- a += weight * inBuffer[sourcePixelIndex*4+3];
- }
- }
-
- outBuffer[targetPixelIndex*4] = std::max( 0, std::min( static_cast<int>( r + 0.5f ), 255 ) );
- outBuffer[targetPixelIndex*4+1] = std::max( 0, std::min( static_cast<int>( g + 0.5f ), 255 ) );
- outBuffer[targetPixelIndex*4+2] = std::max( 0, std::min( static_cast<int>( b + 0.5f ), 255 ) );
- outBuffer[targetPixelIndex*4+3] = std::max( 0, std::min( static_cast<int>( a + 0.5f ), 255 ) );
-
- targetPixelIndex += bufferHeight;
- }
- }
-
- delete [] weightMatrix;
-}
-
-void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius )
-{
- unsigned int bufferWidth = buffer.GetWidth();
- unsigned int bufferHeight = buffer.GetHeight();
-
- // Create a temporary buffer for the two-pass blur
- PixelBufferPtr softShadowImageBuffer = PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
- memcpy( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), 4u * bufferWidth * bufferHeight );
-
- // We perform the blur first but write its output image buffer transposed, so that we
- // can just do it in two passes. The first pass blurs horizontally and transposes, the
- // second pass does the same, but as the image is now transposed, it's really doing a
- // vertical blur. The second transposition makes the image the right way up again. This
- // is much faster than doing a 2D convolution.
- ConvoluteAndTranspose( buffer.GetBuffer(), softShadowImageBuffer->GetBuffer(), bufferWidth, bufferHeight, blurRadius );
- ConvoluteAndTranspose( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), bufferHeight, bufferWidth, blurRadius );
-
- // On leaving scope, softShadowImageBuffer will get destroyed.
-}
-
-} //namespace Adaptor
-
-}// namespace Internal
-
-}// namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
-#define DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "pixel-buffer-impl.h"
-
-namespace Dali
-{
-
-namespace Internal
-{
-
-namespace Adaptor
-{
-
-/**
- * Perform a one dimension Gaussian blur convolution and write its output buffer transposed.
- *
- * @param[in] inBuffer The input buffer with the source image
- * @param[in] outBuffer The output buffer with the Gaussian blur applied and transposed
- * @param[in] bufferWidth The width of the buffer
- * @param[in] bufferHeight The height of the buffer
- * @param[in] blurRadius The radius for Gaussian blur
- */
-void ConvoluteAndTranspose( unsigned char* inBuffer, unsigned char* outBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight, const float blurRadius );
-
-/**
- * Perform Gaussian blur on a buffer.
- *
- * A Gaussian blur is generated by replacing each pixel’s color values with the average of the surrounding pixels’
- * colors. This region is a circle with the given radius. Thus, a bigger radius yields a blurrier image.
- *
- * @note The pixel format of the buffer must be RGBA8888
- *
- * @param[in] buffer The buffer to apply the Gaussian blur to
- * @param[in] blurRadius The radius for Gaussian blur
- */
-void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius );
-
-} //namespace Adaptor
-
-} //namespace Internal
-
-} //namespace Dali
-
-#endif // DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "image-operations.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-#include <stddef.h>
-#include <cmath>
-#include <limits>
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/public-api/math/vector2.h>
-#include <resampler.h>
-#include <image-loading.h>
-
-// INTERNAL INCLUDES
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Platform
-{
-
-namespace
-{
-
-// The BORDER_FILL_VALUE is a single byte value that is used for horizontal and vertical borders.
-// A value of 0x00 gives us transparency for pixel buffers with an alpha channel, or black otherwise.
-// We can optionally use a Vector4 color here, but at reduced fill speed.
-const uint8_t BORDER_FILL_VALUE( 0x00 );
-// A maximum size limit for newly created bitmaps. ( 1u << 16 ) - 1 is chosen as we are using 16bit words for dimensions.
-const unsigned int MAXIMUM_TARGET_BITMAP_SIZE( ( 1u << 16 ) - 1 );
-
-// Constants used by the ImageResampler.
-const float DEFAULT_SOURCE_GAMMA = 1.75f; ///< Default source gamma value used in the Resampler() function. Partial gamma correction looks better on mips. Set to 1.0 to disable gamma correction.
-const float FILTER_SCALE = 1.f; ///< Default filter scale value used in the Resampler() function. Filter scale - values < 1.0 cause aliasing, but create sharper looking mips.
-
-using Integration::Bitmap;
-using Integration::BitmapPtr;
-typedef unsigned char PixelBuffer;
-
-/**
- * @brief 4 byte pixel structure.
- */
-struct Pixel4Bytes
-{
- uint8_t r;
- uint8_t g;
- uint8_t b;
- uint8_t a;
-} __attribute__((packed, aligned(4))); //< Tell the compiler it is okay to use a single 32 bit load.
-
-/**
- * @brief RGB888 pixel structure.
- */
-struct Pixel3Bytes
-{
- uint8_t r;
- uint8_t g;
- uint8_t b;
-} __attribute__((packed, aligned(1)));
-
-/**
- * @brief RGB565 pixel typedefed from a short.
- *
- * Access fields by manual shifting and masking.
- */
-typedef uint16_t PixelRGB565;
-
-/**
- * @brief a Pixel composed of two independent byte components.
- */
-struct Pixel2Bytes
-{
- uint8_t l;
- uint8_t a;
-} __attribute__((packed, aligned(2))); //< Tell the compiler it is okay to use a single 16 bit load.
-
-
-#if defined(DEBUG_ENABLED)
-/**
- * Disable logging of image operations or make it verbose from the commandline
- * as follows (e.g., for dali demo app):
- * <code>
- * LOG_IMAGE_OPERATIONS=0 dali-demo #< off
- * LOG_IMAGE_OPERATIONS=3 dali-demo #< on, verbose
- * </code>
- */
-Debug::Filter* gImageOpsLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_IMAGE_OPERATIONS" );
-#endif
-
-/** @return The greatest even number less than or equal to the argument. */
-inline unsigned int EvenDown( const unsigned int a )
-{
- const unsigned int evened = a & ~1u;
- return evened;
-}
-
-/**
- * @brief Log bad parameters.
- */
-void ValidateScalingParameters( const unsigned int inputWidth,
- const unsigned int inputHeight,
- const unsigned int desiredWidth,
- const unsigned int desiredHeight )
-{
- if( desiredWidth > inputWidth || desiredHeight > inputHeight )
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Upscaling not supported (%u, %u -> %u, %u).\n", inputWidth, inputHeight, desiredWidth, desiredHeight );
- }
-
- if( desiredWidth == 0u || desiredHeight == 0u )
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Downscaling to a zero-area target is pointless.\n" );
- }
-
- if( inputWidth == 0u || inputHeight == 0u )
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Zero area images cannot be scaled\n" );
- }
-}
-
-/**
- * @brief Do debug assertions common to all scanline halving functions.
- * @note Inline and in anon namespace so should boil away in release builds.
- */
-inline void DebugAssertScanlineParameters( const uint8_t * const pixels, const unsigned int width )
-{
- DALI_ASSERT_DEBUG( pixels && "Null pointer." );
- DALI_ASSERT_DEBUG( width > 1u && "Can't average fewer than two pixels." );
- DALI_ASSERT_DEBUG( width < 131072u && "Unusually wide image: are you sure you meant to pass that value in?" );
-}
-
-/**
- * @brief Assertions on params to functions averaging pairs of scanlines.
- * @note Inline as intended to boil away in release.
- */
-inline void DebugAssertDualScanlineParameters( const uint8_t * const scanline1,
- const uint8_t * const scanline2,
- uint8_t* const outputScanline,
- const size_t widthInComponents )
-{
- DALI_ASSERT_DEBUG( scanline1 && "Null pointer." );
- DALI_ASSERT_DEBUG( scanline2 && "Null pointer." );
- DALI_ASSERT_DEBUG( outputScanline && "Null pointer." );
- DALI_ASSERT_DEBUG( ((scanline1 >= scanline2 + widthInComponents) || (scanline2 >= scanline1 + widthInComponents )) && "Scanlines alias." );
- DALI_ASSERT_DEBUG( ((outputScanline >= (scanline2 + widthInComponents)) || (scanline2 >= (scanline1 + widthInComponents))) && "Scanline 2 aliases output." );
-}
-
-/**
- * @brief Converts a scaling mode to the definition of which dimensions matter when box filtering as a part of that mode.
- */
-BoxDimensionTest DimensionTestForScalingMode( FittingMode::Type fittingMode )
-{
- BoxDimensionTest dimensionTest;
- dimensionTest = BoxDimensionTestEither;
-
- switch( fittingMode )
- {
- // Shrink to fit attempts to make one or zero dimensions smaller than the
- // desired dimensions and one or two dimensions exactly the same as the desired
- // ones, so as long as one dimension is larger than the desired size, box
- // filtering can continue even if the second dimension is smaller than the
- // desired dimensions:
- case FittingMode::SHRINK_TO_FIT:
- {
- dimensionTest = BoxDimensionTestEither;
- break;
- }
- // Scale to fill mode keeps both dimensions at least as large as desired:
- case FittingMode::SCALE_TO_FILL:
- {
- dimensionTest = BoxDimensionTestBoth;
- break;
- }
- // Y dimension is irrelevant when downscaling in FIT_WIDTH mode:
- case FittingMode::FIT_WIDTH:
- {
- dimensionTest = BoxDimensionTestX;
- break;
- }
- // X Dimension is ignored by definition in FIT_HEIGHT mode:
- case FittingMode::FIT_HEIGHT:
- {
- dimensionTest = BoxDimensionTestY;
- break;
- }
- }
-
- return dimensionTest;
-}
-
-/**
- * @brief Work out the dimensions for a uniform scaling of the input to map it
- * into the target while effecting ShinkToFit scaling mode.
- */
-ImageDimensions FitForShrinkToFit( ImageDimensions target, ImageDimensions source )
-{
- // Scale the input by the least extreme of the two dimensions:
- const float widthScale = target.GetX() / float(source.GetX());
- const float heightScale = target.GetY() / float(source.GetY());
- const float scale = widthScale < heightScale ? widthScale : heightScale;
-
- // Do no scaling at all if the result would increase area:
- if( scale >= 1.0f )
- {
- return source;
- }
-
- return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
-}
-
-/**
- * @brief Work out the dimensions for a uniform scaling of the input to map it
- * into the target while effecting SCALE_TO_FILL scaling mode.
- * @note An image scaled into the output dimensions will need either top and
- * bottom or left and right to be cropped away unless the source was pre-cropped
- * to match the destination aspect ratio.
- */
-ImageDimensions FitForScaleToFill( ImageDimensions target, ImageDimensions source )
-{
- DALI_ASSERT_DEBUG( source.GetX() > 0 && source.GetY() > 0 && "Zero-area rectangles should not be passed-in" );
- // Scale the input by the least extreme of the two dimensions:
- const float widthScale = target.GetX() / float(source.GetX());
- const float heightScale = target.GetY() / float(source.GetY());
- const float scale = widthScale > heightScale ? widthScale : heightScale;
-
- // Do no scaling at all if the result would increase area:
- if( scale >= 1.0f )
- {
- return source;
- }
-
- return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
-}
-
-/**
- * @brief Work out the dimensions for a uniform scaling of the input to map it
- * into the target while effecting FIT_WIDTH scaling mode.
- */
-ImageDimensions FitForFitWidth( ImageDimensions target, ImageDimensions source )
-{
- DALI_ASSERT_DEBUG( source.GetX() > 0 && "Cant fit a zero-dimension rectangle." );
- const float scale = target.GetX() / float(source.GetX());
-
- // Do no scaling at all if the result would increase area:
- if( scale >= 1.0f )
- {
- return source;
- }
- return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
-}
-
-/**
- * @brief Work out the dimensions for a uniform scaling of the input to map it
- * into the target while effecting FIT_HEIGHT scaling mode.
- */
-ImageDimensions FitForFitHeight( ImageDimensions target, ImageDimensions source )
-{
- DALI_ASSERT_DEBUG( source.GetY() > 0 && "Cant fit a zero-dimension rectangle." );
- const float scale = target.GetY() / float(source.GetY());
-
- // Do no scaling at all if the result would increase area:
- if( scale >= 1.0f )
- {
- return source;
- }
-
- return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f );
-}
-
-/**
- * @brief Generate the rectangle to use as the target of a pixel sampling pass
- * (e.g., nearest or linear).
- */
-ImageDimensions FitToScalingMode( ImageDimensions requestedSize, ImageDimensions sourceSize, FittingMode::Type fittingMode )
-{
- ImageDimensions fitDimensions;
- switch( fittingMode )
- {
- case FittingMode::SHRINK_TO_FIT:
- {
- fitDimensions = FitForShrinkToFit( requestedSize, sourceSize );
- break;
- }
- case FittingMode::SCALE_TO_FILL:
- {
- fitDimensions = FitForScaleToFill( requestedSize, sourceSize );
- break;
- }
- case FittingMode::FIT_WIDTH:
- {
- fitDimensions = FitForFitWidth( requestedSize, sourceSize );
- break;
- }
- case FittingMode::FIT_HEIGHT:
- {
- fitDimensions = FitForFitHeight( requestedSize, sourceSize );
- break;
- }
- }
-
- return fitDimensions;
-}
-
-/**
- * @brief Calculate the number of lines on the X and Y axis that need to be
- * either added or removed with repect to the specified fitting mode.
- * (e.g., nearest or linear).
- * @param[in] sourceSize The size of the source image
- * @param[in] fittingMode The fitting mode to use
- * @param[in/out] requestedSize The target size that the image will be fitted to.
- * If the source image is smaller than the requested size, the source is not scaled up.
- * So we reduce the target size while keeping aspect by lowering resolution.
- * @param[out] scanlinesToCrop The number of scanlines to remove from the image (can be negative to represent Y borders required)
- * @param[out] columnsToCrop The number of columns to remove from the image (can be negative to represent X borders required)
- */
-void CalculateBordersFromFittingMode( ImageDimensions sourceSize, FittingMode::Type fittingMode, ImageDimensions& requestedSize, int& scanlinesToCrop, int& columnsToCrop )
-{
- const unsigned int sourceWidth( sourceSize.GetWidth() );
- const unsigned int sourceHeight( sourceSize.GetHeight() );
- const float targetAspect( static_cast< float >( requestedSize.GetWidth() ) / static_cast< float >( requestedSize.GetHeight() ) );
- int finalWidth = 0;
- int finalHeight = 0;
-
- switch( fittingMode )
- {
- case FittingMode::FIT_WIDTH:
- {
- finalWidth = sourceWidth;
- finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
-
- columnsToCrop = 0;
- scanlinesToCrop = -( finalHeight - sourceHeight );
- break;
- }
-
- case FittingMode::FIT_HEIGHT:
- {
- finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
- finalHeight = sourceHeight;
-
- columnsToCrop = -( finalWidth - sourceWidth );
- scanlinesToCrop = 0;
- break;
- }
-
- case FittingMode::SHRINK_TO_FIT:
- {
- const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) );
- if( sourceAspect > targetAspect )
- {
- finalWidth = sourceWidth;
- finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
-
- columnsToCrop = 0;
- scanlinesToCrop = -( finalHeight - sourceHeight );
- }
- else
- {
- finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
- finalHeight = sourceHeight;
-
- columnsToCrop = -( finalWidth - sourceWidth );
- scanlinesToCrop = 0;
- }
- break;
- }
-
- case FittingMode::SCALE_TO_FILL:
- {
- const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) );
- if( sourceAspect > targetAspect )
- {
- finalWidth = static_cast< float >( sourceHeight ) * targetAspect;
- finalHeight = sourceHeight;
-
- columnsToCrop = -( finalWidth - sourceWidth );
- scanlinesToCrop = 0;
- }
- else
- {
- finalWidth = sourceWidth;
- finalHeight = static_cast< float >( sourceWidth ) / targetAspect;
-
- columnsToCrop = 0;
- scanlinesToCrop = -( finalHeight - sourceHeight );
- }
- break;
- }
- }
-
- requestedSize.SetWidth( finalWidth );
- requestedSize.SetHeight( finalHeight );
-}
-
-/**
- * @brief Construct a pixel buffer object from a copy of the pixel array passed in.
- */
-Dali::Devel::PixelBuffer MakePixelBuffer( const uint8_t * const pixels, Pixel::Format pixelFormat, unsigned int width, unsigned int height )
-{
- DALI_ASSERT_DEBUG( pixels && "Null bitmap buffer to copy." );
-
- // Allocate a pixel buffer to hold the image passed in:
- auto newBitmap = Dali::Devel::PixelBuffer::New( width, height, pixelFormat );
-
- // Copy over the pixels from the downscaled image that was generated in-place in the pixel buffer of the input bitmap:
- memcpy( newBitmap.GetBuffer(), pixels, width * height * Pixel::GetBytesPerPixel( pixelFormat ) );
- return newBitmap;
-}
-
-/**
- * @brief Work out the desired width and height, accounting for zeros.
- *
- * @param[in] bitmapWidth Width of image before processing.
- * @param[in] bitmapHeight Height of image before processing.
- * @param[in] requestedWidth Width of area to scale image into. Can be zero.
- * @param[in] requestedHeight Height of area to scale image into. Can be zero.
- * @return Dimensions of area to scale image into after special rules are applied.
- */
-ImageDimensions CalculateDesiredDimensions( unsigned int bitmapWidth, unsigned int bitmapHeight, unsigned int requestedWidth, unsigned int requestedHeight )
-{
- unsigned int maxSize = Dali::GetMaxTextureSize();
-
- // If no dimensions have been requested, default to the source ones:
- if( requestedWidth == 0 && requestedHeight == 0 )
- {
- if( bitmapWidth <= maxSize && bitmapHeight <= maxSize )
- {
- return ImageDimensions( bitmapWidth, bitmapHeight );
- }
- else
- {
- // Calculate the size from the max texture size and the source image aspect ratio
- if( bitmapWidth > bitmapHeight )
- {
- return ImageDimensions( maxSize, bitmapHeight * maxSize / static_cast< float >( bitmapWidth ) + 0.5f );
- }
- else
- {
- return ImageDimensions( bitmapWidth * maxSize / static_cast< float >( bitmapHeight ) + 0.5f, maxSize );
- }
- }
- }
-
- // If both dimensions have values requested, use them both:
- if( requestedWidth != 0 && requestedHeight != 0 )
- {
- if( requestedWidth <= maxSize && requestedHeight <= maxSize )
- {
- return ImageDimensions( requestedWidth, requestedHeight );
- }
- else
- {
- // Calculate the size from the max texture size and the source image aspect ratio
- if( requestedWidth > requestedHeight )
- {
- return ImageDimensions( maxSize, requestedHeight * maxSize / static_cast< float >( requestedWidth ) + 0.5f );
- }
- else
- {
- return ImageDimensions( requestedWidth * maxSize / static_cast< float >( requestedHeight ) + 0.5f, maxSize );
- }
- }
- }
-
- // Only one of the dimensions has been requested. Calculate the other from
- // the requested one and the source image aspect ratio:
- if( requestedWidth != 0 )
- {
- requestedWidth = std::min( requestedWidth, maxSize );
- return ImageDimensions( requestedWidth, bitmapHeight / float(bitmapWidth) * requestedWidth + 0.5f );
- }
-
- requestedHeight = std::min( requestedHeight, maxSize );
- return ImageDimensions( bitmapWidth / float(bitmapHeight) * requestedHeight + 0.5f, requestedHeight );
-}
-
-} // namespace - unnamed
-
-ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions )
-{
- return CalculateDesiredDimensions( rawDimensions.GetWidth(), rawDimensions.GetHeight(), requestedDimensions.GetWidth(), requestedDimensions.GetHeight() ) ;
-}
-
-/**
- * @brief Apply cropping and padding for specified fitting mode.
- *
- * Once the bitmap has been (optionally) downscaled to an appropriate size, this method performs alterations
- * based on the fitting mode.
- *
- * This will add vertical or horizontal borders if necessary.
- * Crop the source image data vertically or horizontally if necessary.
- * The aspect of the source image is preserved.
- * If the source image is smaller than the desired size, the algorithm will modify the the newly created
- * bitmaps dimensions to only be as large as necessary, as a memory saving optimization. This will cause
- * GPU scaling to be performed at render time giving the same result with less texture traversal.
- *
- * @param[in] bitmap The source pixel buffer to perform modifications on.
- * @param[in] desiredDimensions The target dimensions to aim to fill based on the fitting mode.
- * @param[in] fittingMode The fitting mode to use.
- *
- * @return A new bitmap with the padding and cropping required for fitting mode applied.
- * If no modification is needed or possible, the passed in bitmap is returned.
- */
-Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode );
-
-/**
- * @brief Adds horizontal or vertical borders to the source image.
- *
- * @param[in] targetPixels The destination image pointer to draw the borders on.
- * @param[in] bytesPerPixel The number of bytes per pixel of the target pixel buffer.
- * @param[in] targetDimensions The dimensions of the destination image.
- * @param[in] padDimensions The columns and scanlines to pad with borders.
- */
-void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions );
-
-Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode )
-{
- if( bitmap )
- {
- // Calculate the desired box, accounting for a possible zero component:
- const ImageDimensions desiredDimensions = CalculateDesiredDimensions( bitmap.GetWidth(), bitmap.GetHeight(), dimensions.GetWidth(), dimensions.GetHeight() );
-
- // If a different size than the raw one has been requested, resize the image
- // maximally using a repeated box filter without making it smaller than the
- // requested size in either dimension:
- bitmap = DownscaleBitmap( bitmap, desiredDimensions, fittingMode, samplingMode );
-
- // Cut the bitmap according to the desired width and height so that the
- // resulting bitmap has the same aspect ratio as the desired dimensions.
- // Add crop and add borders if necessary depending on fitting mode.
- if( bitmap )
- {
- bitmap = CropAndPadForFittingMode( bitmap, desiredDimensions, fittingMode );
- }
- }
-
- return bitmap;
-}
-
-Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode )
-{
- const unsigned int inputWidth = bitmap.GetWidth();
- const unsigned int inputHeight = bitmap.GetHeight();
-
- if( desiredDimensions.GetWidth() < 1u || desiredDimensions.GetHeight() < 1u )
- {
- DALI_LOG_WARNING( "Image scaling aborted as desired dimensions too small (%u, %u).\n", desiredDimensions.GetWidth(), desiredDimensions.GetHeight() );
- }
- else if( inputWidth != desiredDimensions.GetWidth() || inputHeight != desiredDimensions.GetHeight() )
- {
- // Calculate any padding or cropping that needs to be done based on the fitting mode.
- // Note: If the desired size is larger than the original image, the desired size will be
- // reduced while maintaining the aspect, in order to save unnecessary memory usage.
- int scanlinesToCrop = 0;
- int columnsToCrop = 0;
-
- CalculateBordersFromFittingMode( ImageDimensions( inputWidth, inputHeight ), fittingMode, desiredDimensions, scanlinesToCrop, columnsToCrop );
-
- unsigned int desiredWidth( desiredDimensions.GetWidth() );
- unsigned int desiredHeight( desiredDimensions.GetHeight() );
-
- // Action the changes by making a new bitmap with the central part of the loaded one if required.
- if( scanlinesToCrop != 0 || columnsToCrop != 0 )
- {
- // Split the adding and removing of scanlines and columns into separate variables,
- // so we can use one piece of generic code to action the changes.
- unsigned int scanlinesToPad = 0;
- unsigned int columnsToPad = 0;
- if( scanlinesToCrop < 0 )
- {
- scanlinesToPad = -scanlinesToCrop;
- scanlinesToCrop = 0;
- }
- if( columnsToCrop < 0 )
- {
- columnsToPad = -columnsToCrop;
- columnsToCrop = 0;
- }
-
- // If there is no filtering, then the final image size can become very large, exit if larger than maximum.
- if( ( desiredWidth > MAXIMUM_TARGET_BITMAP_SIZE ) || ( desiredHeight > MAXIMUM_TARGET_BITMAP_SIZE ) ||
- ( columnsToPad > MAXIMUM_TARGET_BITMAP_SIZE ) || ( scanlinesToPad > MAXIMUM_TARGET_BITMAP_SIZE ) )
- {
- DALI_LOG_WARNING( "Image scaling aborted as final dimensions too large (%u, %u).\n", desiredWidth, desiredHeight );
- return bitmap;
- }
-
- // Create new PixelBuffer with the desired size.
- const auto pixelFormat = bitmap.GetPixelFormat();
-
- auto croppedBitmap = Devel::PixelBuffer::New( desiredWidth, desiredHeight, pixelFormat );
-
- // Add some pre-calculated offsets to the bitmap pointers so this is not done within a loop.
- // The cropping is added to the source pointer, and the padding is added to the destination.
- const auto bytesPerPixel = Pixel::GetBytesPerPixel( pixelFormat );
- const PixelBuffer * const sourcePixels = bitmap.GetBuffer() + ( ( ( ( scanlinesToCrop / 2 ) * inputWidth ) + ( columnsToCrop / 2 ) ) * bytesPerPixel );
- PixelBuffer * const targetPixels = croppedBitmap.GetBuffer();
- PixelBuffer * const targetPixelsActive = targetPixels + ( ( ( ( scanlinesToPad / 2 ) * desiredWidth ) + ( columnsToPad / 2 ) ) * bytesPerPixel );
- DALI_ASSERT_DEBUG( sourcePixels && targetPixels );
-
- // Copy the image data to the new bitmap.
- // Optimize to a single memcpy if the left and right edges don't need a crop or a pad.
- unsigned int outputSpan( desiredWidth * bytesPerPixel );
- if( columnsToCrop == 0 && columnsToPad == 0 )
- {
- memcpy( targetPixelsActive, sourcePixels, ( desiredHeight - scanlinesToPad ) * outputSpan );
- }
- else
- {
- // The width needs to change (due to either a crop or a pad), so we copy a scanline at a time.
- // Precalculate any constants to optimize the inner loop.
- const unsigned int inputSpan( inputWidth * bytesPerPixel );
- const unsigned int copySpan( ( desiredWidth - columnsToPad ) * bytesPerPixel );
- const unsigned int scanlinesToCopy( desiredHeight - scanlinesToPad );
-
- for( unsigned int y = 0; y < scanlinesToCopy; ++y )
- {
- memcpy( &targetPixelsActive[ y * outputSpan ], &sourcePixels[ y * inputSpan ], copySpan );
- }
- }
-
- // Add vertical or horizontal borders to the final image (if required).
- desiredDimensions.SetWidth( desiredWidth );
- desiredDimensions.SetHeight( desiredHeight );
- AddBorders( croppedBitmap.GetBuffer(), bytesPerPixel, desiredDimensions, ImageDimensions( columnsToPad, scanlinesToPad ) );
- // Overwrite the loaded bitmap with the cropped version
- bitmap = croppedBitmap;
- }
- }
-
- return bitmap;
-}
-
-void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions )
-{
- // Assign ints for faster access.
- unsigned int desiredWidth( targetDimensions.GetWidth() );
- unsigned int desiredHeight( targetDimensions.GetHeight() );
- unsigned int columnsToPad( padDimensions.GetWidth() );
- unsigned int scanlinesToPad( padDimensions.GetHeight() );
- unsigned int outputSpan( desiredWidth * bytesPerPixel );
-
- // Add letterboxing (symmetrical borders) if needed.
- if( scanlinesToPad > 0 )
- {
- // Add a top border. Note: This is (deliberately) rounded down if padding is an odd number.
- memset( targetPixels, BORDER_FILL_VALUE, ( scanlinesToPad / 2 ) * outputSpan );
-
- // We subtract scanlinesToPad/2 from scanlinesToPad so that we have the correct
- // offset for odd numbers (as the top border is 1 pixel smaller in these cases.
- unsigned int bottomBorderHeight = scanlinesToPad - ( scanlinesToPad / 2 );
-
- // Bottom border.
- memset( &targetPixels[ ( desiredHeight - bottomBorderHeight ) * outputSpan ], BORDER_FILL_VALUE, bottomBorderHeight * outputSpan );
- }
- else if( columnsToPad > 0 )
- {
- // Add a left and right border.
- // Left:
- // Pre-calculate span size outside of loop.
- unsigned int leftBorderSpanWidth( ( columnsToPad / 2 ) * bytesPerPixel );
- for( unsigned int y = 0; y < desiredHeight; ++y )
- {
- memset( &targetPixels[ y * outputSpan ], BORDER_FILL_VALUE, leftBorderSpanWidth );
- }
-
- // Right:
- // Pre-calculate the initial x offset as it is always the same for a small optimization.
- // We subtract columnsToPad/2 from columnsToPad so that we have the correct
- // offset for odd numbers (as the left border is 1 pixel smaller in these cases.
- unsigned int rightBorderWidth = columnsToPad - ( columnsToPad / 2 );
- PixelBuffer * const destPixelsRightBorder( targetPixels + ( ( desiredWidth - rightBorderWidth ) * bytesPerPixel ) );
- unsigned int rightBorderSpanWidth = rightBorderWidth * bytesPerPixel;
-
- for( unsigned int y = 0; y < desiredHeight; ++y )
- {
- memset( &destPixelsRightBorder[ y * outputSpan ], BORDER_FILL_VALUE, rightBorderSpanWidth );
- }
- }
-}
-
-Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap,
- ImageDimensions desired,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode )
-{
- // Source dimensions as loaded from resources (e.g. filesystem):
- auto bitmapWidth = bitmap.GetWidth();
- auto bitmapHeight = bitmap.GetHeight();
- // Desired dimensions (the rectangle to fit the source image to):
- auto desiredWidth = desired.GetWidth();
- auto desiredHeight = desired.GetHeight();
-
- Dali::Devel::PixelBuffer outputBitmap { bitmap };
-
- // If a different size than the raw one has been requested, resize the image:
- if(
- (desiredWidth > 0.0f) && (desiredHeight > 0.0f) &&
- ((desiredWidth < bitmapWidth) || (desiredHeight < bitmapHeight)) )
- {
- auto pixelFormat = bitmap.GetPixelFormat();
-
- // Do the fast power of 2 iterated box filter to get to roughly the right side if the filter mode requests that:
- unsigned int shrunkWidth = -1, shrunkHeight = -1;
- DownscaleInPlacePow2( bitmap.GetBuffer(), pixelFormat, bitmapWidth, bitmapHeight, desiredWidth, desiredHeight, fittingMode, samplingMode, shrunkWidth, shrunkHeight );
-
- // Work out the dimensions of the downscaled bitmap, given the scaling mode and desired dimensions:
- const ImageDimensions filteredDimensions = FitToScalingMode( ImageDimensions( desiredWidth, desiredHeight ), ImageDimensions( shrunkWidth, shrunkHeight ), fittingMode );
- const unsigned int filteredWidth = filteredDimensions.GetWidth();
- const unsigned int filteredHeight = filteredDimensions.GetHeight();
-
- // Run a filter to scale down the bitmap if it needs it:
- bool filtered = false;
- if( filteredWidth < shrunkWidth || filteredHeight < shrunkHeight )
- {
- if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR ||
- samplingMode == SamplingMode::NEAREST || samplingMode == SamplingMode::BOX_THEN_NEAREST )
- {
- outputBitmap = Dali::Devel::PixelBuffer::New( filteredWidth, filteredHeight, pixelFormat );
-
- if( outputBitmap )
- {
- if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR )
- {
- LinearSample( bitmap.GetBuffer(), ImageDimensions(shrunkWidth, shrunkHeight), pixelFormat, outputBitmap.GetBuffer(), filteredDimensions );
- }
- else
- {
- PointSample( bitmap.GetBuffer(), shrunkWidth, shrunkHeight, pixelFormat, outputBitmap.GetBuffer(), filteredWidth, filteredHeight );
- }
- filtered = true;
- }
- }
- }
- // Copy out the 2^x downscaled, box-filtered pixels if no secondary filter (point or linear) was applied:
- if( filtered == false && ( shrunkWidth < bitmapWidth || shrunkHeight < bitmapHeight ) )
- {
- outputBitmap = MakePixelBuffer( bitmap.GetBuffer(), pixelFormat, shrunkWidth, shrunkHeight );
- }
- }
-
- return outputBitmap;
-}
-
-namespace
-{
-/**
- * @brief Returns whether to keep box filtering based on whether downscaled dimensions will overshoot the desired ones aty the next step.
- * @param test Which combination of the two dimensions matter for terminating the filtering.
- * @param scaledWidth The width of the current downscaled image.
- * @param scaledHeight The height of the current downscaled image.
- * @param desiredWidth The target width for the downscaling.
- * @param desiredHeight The target height for the downscaling.
- */
-bool ContinueScaling( BoxDimensionTest test, unsigned int scaledWidth, unsigned int scaledHeight, unsigned int desiredWidth, unsigned int desiredHeight )
-{
- bool keepScaling = false;
- const unsigned int nextWidth = scaledWidth >> 1u;
- const unsigned int nextHeight = scaledHeight >> 1u;
-
- if( nextWidth >= 1u && nextHeight >= 1u )
- {
- switch( test )
- {
- case BoxDimensionTestEither:
- {
- keepScaling = nextWidth >= desiredWidth || nextHeight >= desiredHeight;
- break;
- }
- case BoxDimensionTestBoth:
- {
- keepScaling = nextWidth >= desiredWidth && nextHeight >= desiredHeight;
- break;
- }
- case BoxDimensionTestX:
- {
- keepScaling = nextWidth >= desiredWidth;
- break;
- }
- case BoxDimensionTestY:
- {
- keepScaling = nextHeight >= desiredHeight;
- break;
- }
- }
- }
-
- return keepScaling;
-}
-
-/**
- * @brief A shared implementation of the overall iterative box filter
- * downscaling algorithm.
- *
- * Specialise this for particular pixel formats by supplying the number of bytes
- * per pixel and two functions: one for averaging pairs of neighbouring pixels
- * on a single scanline, and a second for averaging pixels at corresponding
- * positions on different scanlines.
- **/
-template<
- int BYTES_PER_PIXEL,
- void (*HalveScanlineInPlace)( unsigned char * const pixels, const unsigned int width ),
- void (*AverageScanlines) ( const unsigned char * const scanline1, const unsigned char * const __restrict__ scanline2, unsigned char* const outputScanline, const unsigned int width )
->
-void DownscaleInPlacePow2Generic( unsigned char * const pixels,
- const unsigned int inputWidth,
- const unsigned int inputHeight,
- const unsigned int desiredWidth,
- const unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned& outWidth,
- unsigned& outHeight )
-{
- if( pixels == 0 )
- {
- return;
- }
- ValidateScalingParameters( inputWidth, inputHeight, desiredWidth, desiredHeight );
-
- // Scale the image until it would be smaller than desired, stopping if the
- // resulting height or width would be less than 1:
- unsigned int scaledWidth = inputWidth, scaledHeight = inputHeight;
- while( ContinueScaling( dimensionTest, scaledWidth, scaledHeight, desiredWidth, desiredHeight ) )
- {
- const unsigned int lastWidth = scaledWidth;
- scaledWidth >>= 1u;
- scaledHeight >>= 1u;
-
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Scaling to %u\t%u.\n", scaledWidth, scaledHeight );
-
- const unsigned int lastScanlinePair = scaledHeight - 1;
-
- // Scale pairs of scanlines until any spare one at the end is dropped:
- for( unsigned int y = 0; y <= lastScanlinePair; ++y )
- {
- // Scale two scanlines horizontally:
- HalveScanlineInPlace( &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], lastWidth );
- HalveScanlineInPlace( &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], lastWidth );
-
- // Scale vertical pairs of pixels while the last two scanlines are still warm in
- // the CPU cache(s):
- // Note, better access patterns for cache-coherence are possible for very large
- // images but even a 4k wide RGB888 image will use just 24kB of cache (4k pixels
- // * 3 Bpp * 2 scanlines) for two scanlines on the first iteration.
- AverageScanlines(
- &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL],
- &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL],
- &pixels[y * scaledWidth * BYTES_PER_PIXEL],
- scaledWidth );
- }
- }
-
- ///@note: we could finish off with one of two mutually exclusive passes, one squashing horizontally as far as possible, and the other vertically, if we knew a following cpu point or bilinear filter would restore the desired aspect ratio.
- outWidth = scaledWidth;
- outHeight = scaledHeight;
-}
-
-}
-
-void HalveScanlineInPlaceRGB888( unsigned char * const pixels, const unsigned int width )
-{
- DebugAssertScanlineParameters( pixels, width );
-
- const unsigned int lastPair = EvenDown( width - 2 );
-
- for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
- {
- // Load all the byte pixel components we need:
- const unsigned int c11 = pixels[pixel * 3];
- const unsigned int c12 = pixels[pixel * 3 + 1];
- const unsigned int c13 = pixels[pixel * 3 + 2];
- const unsigned int c21 = pixels[pixel * 3 + 3];
- const unsigned int c22 = pixels[pixel * 3 + 4];
- const unsigned int c23 = pixels[pixel * 3 + 5];
-
- // Save the averaged byte pixel components:
- pixels[outPixel * 3] = AverageComponent( c11, c21 );
- pixels[outPixel * 3 + 1] = AverageComponent( c12, c22 );
- pixels[outPixel * 3 + 2] = AverageComponent( c13, c23 );
- }
-}
-
-void HalveScanlineInPlaceRGBA8888( unsigned char * const pixels, const unsigned int width )
-{
- DebugAssertScanlineParameters( pixels, width );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
-
- uint32_t* const alignedPixels = reinterpret_cast<uint32_t*>(pixels);
-
- const unsigned int lastPair = EvenDown( width - 2 );
-
- for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
- {
- const uint32_t averaged = AveragePixelRGBA8888( alignedPixels[pixel], alignedPixels[pixel + 1] );
- alignedPixels[outPixel] = averaged;
- }
-}
-
-void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width )
-{
- DebugAssertScanlineParameters( pixels, width );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
-
- uint16_t* const alignedPixels = reinterpret_cast<uint16_t*>(pixels);
-
- const unsigned int lastPair = EvenDown( width - 2 );
-
- for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
- {
- const uint32_t averaged = AveragePixelRGB565( alignedPixels[pixel], alignedPixels[pixel + 1] );
- alignedPixels[outPixel] = averaged;
- }
-}
-
-void HalveScanlineInPlace2Bytes( unsigned char * const pixels, const unsigned int width )
-{
- DebugAssertScanlineParameters( pixels, width );
-
- const unsigned int lastPair = EvenDown( width - 2 );
-
- for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
- {
- // Load all the byte pixel components we need:
- const unsigned int c11 = pixels[pixel * 2];
- const unsigned int c12 = pixels[pixel * 2 + 1];
- const unsigned int c21 = pixels[pixel * 2 + 2];
- const unsigned int c22 = pixels[pixel * 2 + 3];
-
- // Save the averaged byte pixel components:
- pixels[outPixel * 2] = AverageComponent( c11, c21 );
- pixels[outPixel * 2 + 1] = AverageComponent( c12, c22 );
- }
-}
-
-void HalveScanlineInPlace1Byte( unsigned char * const pixels, const unsigned int width )
-{
- DebugAssertScanlineParameters( pixels, width );
-
- const unsigned int lastPair = EvenDown( width - 2 );
-
- for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel )
- {
- // Load all the byte pixel components we need:
- const unsigned int c1 = pixels[pixel];
- const unsigned int c2 = pixels[pixel + 1];
-
- // Save the averaged byte pixel component:
- pixels[outPixel] = AverageComponent( c1, c2 );
- }
-}
-
-/**
- * @ToDo: Optimise for ARM using a 4 bytes at a time loop wrapped around the single ARMV6 instruction: UHADD8 R4, R0, R5. Note, this is not neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro, or extra power for clocking-up the idle copro.
- * if (widthInComponents >= 7) { word32* aligned1 = scanline1 + 3 & 3; word32* aligned1_end = scanline1 + widthInPixels & 3; while(aligned1 < aligned1_end) { UHADD8 *aligned1++, *aligned2++, *alignedoutput++ } .. + 0 to 3 spare pixels at each end.
- */
-void AverageScanlines1( const unsigned char * const scanline1,
- const unsigned char * const __restrict__ scanline2,
- unsigned char* const outputScanline,
- const unsigned int width )
-{
- DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width );
-
- for( unsigned int component = 0; component < width; ++component )
- {
- outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
- }
-}
-
-void AverageScanlines2( const unsigned char * const scanline1,
- const unsigned char * const __restrict__ scanline2,
- unsigned char* const outputScanline,
- const unsigned int width )
-{
- DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 );
-
- for( unsigned int component = 0; component < width * 2; ++component )
- {
- outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
- }
-}
-
-void AverageScanlines3( const unsigned char * const scanline1,
- const unsigned char * const __restrict__ scanline2,
- unsigned char* const outputScanline,
- const unsigned int width )
-{
- DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 3 );
-
- for( unsigned int component = 0; component < width * 3; ++component )
- {
- outputScanline[component] = AverageComponent( scanline1[component], scanline2[component] );
- }
-}
-
-void AverageScanlinesRGBA8888( const unsigned char * const scanline1,
- const unsigned char * const __restrict__ scanline2,
- unsigned char * const outputScanline,
- const unsigned int width )
-{
- DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 4 );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline1) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline2) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(outputScanline) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
-
- const uint32_t* const alignedScanline1 = reinterpret_cast<const uint32_t*>(scanline1);
- const uint32_t* const alignedScanline2 = reinterpret_cast<const uint32_t*>(scanline2);
- uint32_t* const alignedOutput = reinterpret_cast<uint32_t*>(outputScanline);
-
- for( unsigned int pixel = 0; pixel < width; ++pixel )
- {
- alignedOutput[pixel] = AveragePixelRGBA8888( alignedScanline1[pixel], alignedScanline2[pixel] );
- }
-}
-
-void AverageScanlinesRGB565( const unsigned char * const scanline1,
- const unsigned char * const __restrict__ scanline2,
- unsigned char * const outputScanline,
- const unsigned int width )
-{
- DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline1) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(scanline2) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(outputScanline) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." );
-
- const uint16_t* const alignedScanline1 = reinterpret_cast<const uint16_t*>(scanline1);
- const uint16_t* const alignedScanline2 = reinterpret_cast<const uint16_t*>(scanline2);
- uint16_t* const alignedOutput = reinterpret_cast<uint16_t*>(outputScanline);
-
- for( unsigned int pixel = 0; pixel < width; ++pixel )
- {
- alignedOutput[pixel] = AveragePixelRGB565( alignedScanline1[pixel], alignedScanline2[pixel] );
- }
-}
-
-/// Dispatch to pixel format appropriate box filter downscaling functions.
-void DownscaleInPlacePow2( unsigned char * const pixels,
- Pixel::Format pixelFormat,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- unsigned& outWidth,
- unsigned& outHeight )
-{
- outWidth = inputWidth;
- outHeight = inputHeight;
- // Perform power of 2 iterated 4:1 box filtering if the requested filter mode requires it:
- if( samplingMode == SamplingMode::BOX || samplingMode == SamplingMode::BOX_THEN_NEAREST || samplingMode == SamplingMode::BOX_THEN_LINEAR )
- {
- // Check the pixel format is one that is supported:
- if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
- {
- const BoxDimensionTest dimensionTest = DimensionTestForScalingMode( fittingMode );
-
- if( pixelFormat == Pixel::RGBA8888 )
- {
- Internal::Platform::DownscaleInPlacePow2RGBA8888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
- }
- else if( pixelFormat == Pixel::RGB888 )
- {
- Internal::Platform::DownscaleInPlacePow2RGB888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
- }
- else if( pixelFormat == Pixel::RGB565 )
- {
- Internal::Platform::DownscaleInPlacePow2RGB565( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
- }
- else if( pixelFormat == Pixel::LA88 )
- {
- Internal::Platform::DownscaleInPlacePow2ComponentPair( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
- }
- else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
- {
- Internal::Platform::DownscaleInPlacePow2SingleBytePerPixel( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
- }
- else
- {
- DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
- }
- }
- }
- else
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not shrunk: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
- }
-}
-
-void DownscaleInPlacePow2RGB888( unsigned char *pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned& outWidth,
- unsigned& outHeight )
-{
- DownscaleInPlacePow2Generic<3, HalveScanlineInPlaceRGB888, AverageScanlines3>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
-}
-
-void DownscaleInPlacePow2RGBA8888( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned& outWidth,
- unsigned& outHeight )
-{
- DALI_ASSERT_DEBUG( ((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." );
- DownscaleInPlacePow2Generic<4, HalveScanlineInPlaceRGBA8888, AverageScanlinesRGBA8888>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
-}
-
-void DownscaleInPlacePow2RGB565( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight )
-{
- DownscaleInPlacePow2Generic<2, HalveScanlineInPlaceRGB565, AverageScanlinesRGB565>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
-}
-
-/**
- * @copydoc DownscaleInPlacePow2RGB888
- *
- * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565.
- */
-void DownscaleInPlacePow2ComponentPair( unsigned char *pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned& outWidth,
- unsigned& outHeight )
-{
- DownscaleInPlacePow2Generic<2, HalveScanlineInPlace2Bytes, AverageScanlines2>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
-}
-
-void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight )
-{
- DownscaleInPlacePow2Generic<1, HalveScanlineInPlace1Byte, AverageScanlines1>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight );
-}
-
-namespace
-{
-
-/**
- * @brief Point sample an image to a new resolution (like GL_NEAREST).
- *
- * Template is used purely as a type-safe code generator in this one
- * compilation unit. Generated code is inlined into type-specific wrapper
- * functions below which are exported to rest of module.
- */
-template<typename PIXEL>
-inline void PointSampleAddressablePixels( const uint8_t * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- uint8_t * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- DALI_ASSERT_DEBUG( ((desiredWidth <= inputWidth && desiredHeight <= inputHeight) ||
- outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL) || outPixels <= inPixels - desiredWidth * desiredHeight * sizeof(PIXEL)) &&
- "The input and output buffers must not overlap for an upscaling.");
- DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
- DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
-
- if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
- {
- return;
- }
- const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
- PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
- const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
- const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
-
- unsigned int inY = 0;
- for( unsigned int outY = 0; outY < desiredHeight; ++outY )
- {
- // Round fixed point y coordinate to nearest integer:
- const unsigned int integerY = (inY + (1u << 15u)) >> 16u;
- const PIXEL* const inScanline = &inAligned[inputWidth * integerY];
- PIXEL* const outScanline = &outAligned[desiredWidth * outY];
-
- DALI_ASSERT_DEBUG( integerY < inputHeight );
- DALI_ASSERT_DEBUG( reinterpret_cast<const uint8_t*>(inScanline) < ( inPixels + inputWidth * inputHeight * sizeof(PIXEL) ) );
- DALI_ASSERT_DEBUG( reinterpret_cast<uint8_t*>(outScanline) < ( outPixels + desiredWidth * desiredHeight * sizeof(PIXEL) ) );
-
- unsigned int inX = 0;
- for( unsigned int outX = 0; outX < desiredWidth; ++outX )
- {
- // Round the fixed-point x coordinate to an integer:
- const unsigned int integerX = (inX + (1u << 15u)) >> 16u;
- const PIXEL* const inPixelAddress = &inScanline[integerX];
- const PIXEL pixel = *inPixelAddress;
- outScanline[outX] = pixel;
- inX += deltaX;
- }
- inY += deltaY;
- }
-}
-
-}
-
-// RGBA8888
-void PointSample4BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- PointSampleAddressablePixels<uint32_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
-}
-
-// RGB565, LA88
-void PointSample2BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- PointSampleAddressablePixels<uint16_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
-}
-
-// L8, A8
-void PointSample1BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- PointSampleAddressablePixels<uint8_t>( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
-}
-
-/* RGB888
- * RGB888 is a special case as its pixels are not aligned addressable units.
- */
-void PointSample3BPP( const uint8_t * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- uint8_t * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
- {
- return;
- }
- const unsigned int BYTES_PER_PIXEL = 3;
-
- // Generate fixed-point 16.16 deltas in input image coordinates:
- const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
- const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
-
- // Step through output image in whole integer pixel steps while tracking the
- // corresponding locations in the input image using 16.16 fixed-point
- // coordinates:
- unsigned int inY = 0; //< 16.16 fixed-point input image y-coord.
- for( unsigned int outY = 0; outY < desiredHeight; ++outY )
- {
- const unsigned int integerY = (inY + (1u << 15u)) >> 16u;
- const uint8_t* const inScanline = &inPixels[inputWidth * integerY * BYTES_PER_PIXEL];
- uint8_t* const outScanline = &outPixels[desiredWidth * outY * BYTES_PER_PIXEL];
- unsigned int inX = 0; //< 16.16 fixed-point input image x-coord.
-
- for( unsigned int outX = 0; outX < desiredWidth * BYTES_PER_PIXEL; outX += BYTES_PER_PIXEL )
- {
- // Round the fixed-point input coordinate to the address of the input pixel to sample:
- const unsigned int integerX = (inX + (1u << 15u)) >> 16u;
- const uint8_t* const inPixelAddress = &inScanline[integerX * BYTES_PER_PIXEL];
-
- // Issue loads for all pixel color components up-front:
- const unsigned int c0 = inPixelAddress[0];
- const unsigned int c1 = inPixelAddress[1];
- const unsigned int c2 = inPixelAddress[2];
- ///@ToDo: Optimise - Benchmark one 32bit load that will be unaligned 2/3 of the time + 3 rotate and masks, versus these three aligned byte loads, versus using an RGB packed, aligned(1) struct and letting compiler pick a strategy.
-
- // Output the pixel components:
- outScanline[outX] = c0;
- outScanline[outX + 1] = c1;
- outScanline[outX + 2] = c2;
-
- // Increment the fixed-point input coordinate:
- inX += deltaX;
- }
-
- inY += deltaY;
- }
-}
-
-// Dispatch to a format-appropriate point sampling function:
-void PointSample( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- Pixel::Format pixelFormat,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight )
-{
- // Check the pixel format is one that is supported:
- if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
- {
- if( pixelFormat == Pixel::RGB888 )
- {
- PointSample3BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
- }
- else if( pixelFormat == Pixel::RGBA8888 )
- {
- PointSample4BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
- }
- else if( pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 )
- {
- PointSample2BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
- }
- else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
- {
- PointSample1BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight );
- }
- else
- {
- DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
- }
- }
- else
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not point sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
- }
-}
-
-// Linear sampling group below
-
-namespace
-{
-
-/** @brief Blend 4 pixels together using horizontal and vertical weights. */
-inline uint8_t BilinearFilter1BPPByte( uint8_t tl, uint8_t tr, uint8_t bl, uint8_t br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- return BilinearFilter1Component( tl, tr, bl, br, fractBlendHorizontal, fractBlendVertical );
-}
-
-/** @copydoc BilinearFilter1BPPByte */
-inline Pixel2Bytes BilinearFilter2Bytes( Pixel2Bytes tl, Pixel2Bytes tr, Pixel2Bytes bl, Pixel2Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- Pixel2Bytes pixel;
- pixel.l = BilinearFilter1Component( tl.l, tr.l, bl.l, br.l, fractBlendHorizontal, fractBlendVertical );
- pixel.a = BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical );
- return pixel;
-}
-
-/** @copydoc BilinearFilter1BPPByte */
-inline Pixel3Bytes BilinearFilterRGB888( Pixel3Bytes tl, Pixel3Bytes tr, Pixel3Bytes bl, Pixel3Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- Pixel3Bytes pixel;
- pixel.r = BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical );
- pixel.g = BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical );
- pixel.b = BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical );
- return pixel;
-}
-
-/** @copydoc BilinearFilter1BPPByte */
-inline PixelRGB565 BilinearFilterRGB565( PixelRGB565 tl, PixelRGB565 tr, PixelRGB565 bl, PixelRGB565 br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- const PixelRGB565 pixel = (BilinearFilter1Component( tl >> 11u, tr >> 11u, bl >> 11u, br >> 11u, fractBlendHorizontal, fractBlendVertical ) << 11u) +
- (BilinearFilter1Component( (tl >> 5u) & 63u, (tr >> 5u) & 63u, (bl >> 5u) & 63u, (br >> 5u) & 63u, fractBlendHorizontal, fractBlendVertical ) << 5u) +
- BilinearFilter1Component( tl & 31u, tr & 31u, bl & 31u, br & 31u, fractBlendHorizontal, fractBlendVertical );
- return pixel;
-}
-
-/** @copydoc BilinearFilter1BPPByte */
-inline Pixel4Bytes BilinearFilter4Bytes( Pixel4Bytes tl, Pixel4Bytes tr, Pixel4Bytes bl, Pixel4Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- Pixel4Bytes pixel;
- pixel.r = BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical );
- pixel.g = BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical );
- pixel.b = BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical );
- pixel.a = BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical );
- return pixel;
-}
-
-/**
- * @brief Generic version of bilinear sampling image resize function.
- * @note Limited to one compilation unit and exposed through type-specific
- * wrapper functions below.
- */
-template<
- typename PIXEL,
- PIXEL (*BilinearFilter) ( PIXEL tl, PIXEL tr, PIXEL bl, PIXEL br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ),
- bool DEBUG_ASSERT_ALIGNMENT
->
-inline void LinearSampleGeneric( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- const unsigned int inputWidth = inputDimensions.GetWidth();
- const unsigned int inputHeight = inputDimensions.GetHeight();
- const unsigned int desiredWidth = desiredDimensions.GetWidth();
- const unsigned int desiredHeight = desiredDimensions.GetHeight();
-
- DALI_ASSERT_DEBUG( ((outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL)) ||
- (inPixels >= outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))) &&
- "Input and output buffers cannot overlap.");
- if( DEBUG_ASSERT_ALIGNMENT )
- {
- DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
- DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." );
- }
-
- if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u )
- {
- return;
- }
- const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
- PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
- const unsigned int deltaX = (inputWidth << 16u) / desiredWidth;
- const unsigned int deltaY = (inputHeight << 16u) / desiredHeight;
-
- unsigned int inY = 0;
- for( unsigned int outY = 0; outY < desiredHeight; ++outY )
- {
- PIXEL* const outScanline = &outAligned[desiredWidth * outY];
-
- // Find the two scanlines to blend and the weight to blend with:
- const unsigned int integerY1 = inY >> 16u;
- const unsigned int integerY2 = integerY1 >= inputHeight ? integerY1 : integerY1 + 1;
- const unsigned int inputYWeight = inY & 65535u;
-
- DALI_ASSERT_DEBUG( integerY1 < inputHeight );
- DALI_ASSERT_DEBUG( integerY2 < inputHeight );
-
- const PIXEL* const inScanline1 = &inAligned[inputWidth * integerY1];
- const PIXEL* const inScanline2 = &inAligned[inputWidth * integerY2];
-
- unsigned int inX = 0;
- for( unsigned int outX = 0; outX < desiredWidth; ++outX )
- {
- // Work out the two pixel scanline offsets for this cluster of four samples:
- const unsigned int integerX1 = inX >> 16u;
- const unsigned int integerX2 = integerX1 >= inputWidth ? integerX1 : integerX1 + 1;
-
- // Execute the loads:
- const PIXEL pixel1 = inScanline1[integerX1];
- const PIXEL pixel2 = inScanline2[integerX1];
- const PIXEL pixel3 = inScanline1[integerX2];
- const PIXEL pixel4 = inScanline2[integerX2];
- ///@ToDo Optimise - for 1 and 2 and 4 byte types to execute a single 2, 4, or 8 byte load per pair (caveat clamping) and let half of them be unaligned.
-
- // Weighted bilinear filter:
- const unsigned int inputXWeight = inX & 65535u;
- outScanline[outX] = BilinearFilter( pixel1, pixel3, pixel2, pixel4, inputXWeight, inputYWeight );
-
- inX += deltaX;
- }
- inY += deltaY;
- }
-}
-
-}
-
-// Format-specific linear scaling instantiations:
-
-void LinearSample1BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- LinearSampleGeneric<uint8_t, BilinearFilter1BPPByte, false>( inPixels, inputDimensions, outPixels, desiredDimensions );
-}
-
-void LinearSample2BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- LinearSampleGeneric<Pixel2Bytes, BilinearFilter2Bytes, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
-}
-
-void LinearSampleRGB565( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- LinearSampleGeneric<PixelRGB565, BilinearFilterRGB565, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
-}
-
-void LinearSample3BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- LinearSampleGeneric<Pixel3Bytes, BilinearFilterRGB888, false>( inPixels, inputDimensions, outPixels, desiredDimensions );
-}
-
-void LinearSample4BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- LinearSampleGeneric<Pixel4Bytes, BilinearFilter4Bytes, true>( inPixels, inputDimensions, outPixels, desiredDimensions );
-}
-
-
-void Resample( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions,
- Resampler::Filter filterType,
- int numChannels, bool hasAlpha )
-{
- // Got from the test.cpp of the ImageResampler lib.
- const float ONE_DIV_255 = 1.0f / 255.0f;
- const int MAX_UNSIGNED_CHAR = std::numeric_limits<uint8_t>::max();
- const int LINEAR_TO_SRGB_TABLE_SIZE = 4096;
- const int ALPHA_CHANNEL = hasAlpha ? (numChannels-1) : 0;
-
- static bool loadColorSpaces = true;
- static float srgbToLinear[MAX_UNSIGNED_CHAR + 1];
- static unsigned char linearToSrgb[LINEAR_TO_SRGB_TABLE_SIZE];
-
- if( loadColorSpaces ) // Only create the color space conversions on the first execution
- {
- loadColorSpaces = false;
-
- for( int i = 0; i <= MAX_UNSIGNED_CHAR; ++i )
- {
- srgbToLinear[i] = pow( static_cast<float>( i ) * ONE_DIV_255, DEFAULT_SOURCE_GAMMA );
- }
-
- const float invLinearToSrgbTableSize = 1.0f / static_cast<float>( LINEAR_TO_SRGB_TABLE_SIZE );
- const float invSourceGamma = 1.0f / DEFAULT_SOURCE_GAMMA;
-
- for( int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i )
- {
- int k = static_cast<int>( 255.0f * pow( static_cast<float>( i ) * invLinearToSrgbTableSize, invSourceGamma ) + 0.5f );
- if( k < 0 )
- {
- k = 0;
- }
- else if( k > MAX_UNSIGNED_CHAR )
- {
- k = MAX_UNSIGNED_CHAR;
- }
- linearToSrgb[i] = static_cast<unsigned char>( k );
- }
- }
-
- Resampler* resamplers[numChannels];
- Vector<float> samples[numChannels];
-
- const int srcWidth = inputDimensions.GetWidth();
- const int srcHeight = inputDimensions.GetHeight();
- const int dstWidth = desiredDimensions.GetWidth();
- const int dstHeight = desiredDimensions.GetHeight();
-
- // Now create a Resampler instance for each component to process. The first instance will create new contributor tables, which are shared by the resamplers
- // used for the other components (a memory and slight cache efficiency optimization).
- resamplers[0] = new Resampler( srcWidth,
- srcHeight,
- dstWidth,
- dstHeight,
- Resampler::BOUNDARY_CLAMP,
- 0.0f, // sample_low,
- 1.0f, // sample_high. Clamp output samples to specified range, or disable clamping if sample_low >= sample_high.
- filterType, // The type of filter.
- NULL, // Pclist_x,
- NULL, // Pclist_y. Optional pointers to contributor lists from another instance of a Resampler.
- FILTER_SCALE, // src_x_ofs,
- FILTER_SCALE ); // src_y_ofs. Offset input image by specified amount (fractional values okay).
- samples[0].Resize( srcWidth );
- for( int i = 1; i < numChannels; ++i )
- {
- resamplers[i] = new Resampler( srcWidth,
- srcHeight,
- dstWidth,
- dstHeight,
- Resampler::BOUNDARY_CLAMP,
- 0.0f,
- 1.0f,
- filterType,
- resamplers[0]->get_clist_x(),
- resamplers[0]->get_clist_y(),
- FILTER_SCALE,
- FILTER_SCALE );
- samples[i].Resize( srcWidth );
- }
-
- const int srcPitch = srcWidth * numChannels;
- const int dstPitch = dstWidth * numChannels;
- int dstY = 0;
-
- for( int srcY = 0; srcY < srcHeight; ++srcY )
- {
- const unsigned char* pSrc = &inPixels[srcY * srcPitch];
-
- for( int x = 0; x < srcWidth; ++x )
- {
- for( int c = 0; c < numChannels; ++c )
- {
- if( c == ALPHA_CHANNEL && hasAlpha )
- {
- samples[c][x] = *pSrc++ * ONE_DIV_255;
- }
- else
- {
- samples[c][x] = srgbToLinear[*pSrc++];
- }
- }
- }
-
- for( int c = 0; c < numChannels; ++c )
- {
- if( !resamplers[c]->put_line( &samples[c][0] ) )
- {
- DALI_ASSERT_DEBUG( !"Out of memory" );
- }
- }
-
- for(;;)
- {
- int compIndex;
- for( compIndex = 0; compIndex < numChannels; ++compIndex )
- {
- const float* pOutputSamples = resamplers[compIndex]->get_line();
- if( !pOutputSamples )
- {
- break;
- }
-
- const bool isAlphaChannel = ( compIndex == ALPHA_CHANNEL && hasAlpha );
- DALI_ASSERT_DEBUG( dstY < dstHeight );
- unsigned char* pDst = &outPixels[dstY * dstPitch + compIndex];
-
- for( int x = 0; x < dstWidth; ++x )
- {
- if( isAlphaChannel )
- {
- int c = static_cast<int>( 255.0f * pOutputSamples[x] + 0.5f );
- if( c < 0 )
- {
- c = 0;
- }
- else if( c > MAX_UNSIGNED_CHAR )
- {
- c = MAX_UNSIGNED_CHAR;
- }
- *pDst = static_cast<unsigned char>( c );
- }
- else
- {
- int j = static_cast<int>( LINEAR_TO_SRGB_TABLE_SIZE * pOutputSamples[x] + 0.5f );
- if( j < 0 )
- {
- j = 0;
- }
- else if( j >= LINEAR_TO_SRGB_TABLE_SIZE )
- {
- j = LINEAR_TO_SRGB_TABLE_SIZE - 1;
- }
- *pDst = linearToSrgb[j];
- }
-
- pDst += numChannels;
- }
- }
- if( compIndex < numChannels )
- {
- break;
- }
-
- ++dstY;
- }
- }
-
- // Delete the resamplers.
- for( int i = 0; i < numChannels; ++i )
- {
- delete resamplers[i];
- }
-}
-
-void LanczosSample4BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 4, true );
-}
-
-void LanczosSample1BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions )
-{
- // For L8 images
- Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 1, false );
-}
-
-// Dispatch to a format-appropriate linear sampling function:
-void LinearSample( const unsigned char * __restrict__ inPixels,
- ImageDimensions inDimensions,
- Pixel::Format pixelFormat,
- unsigned char * __restrict__ outPixels,
- ImageDimensions outDimensions )
-{
- // Check the pixel format is one that is supported:
- if( pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::RGB565 )
- {
- if( pixelFormat == Pixel::RGB888 )
- {
- LinearSample3BPP( inPixels, inDimensions, outPixels, outDimensions );
- }
- else if( pixelFormat == Pixel::RGBA8888 )
- {
- LinearSample4BPP( inPixels, inDimensions, outPixels, outDimensions );
- }
- else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 )
- {
- LinearSample1BPP( inPixels, inDimensions, outPixels, outDimensions );
- }
- else if( pixelFormat == Pixel::LA88 )
- {
- LinearSample2BPP( inPixels, inDimensions, outPixels, outDimensions );
- }
- else if ( pixelFormat == Pixel::RGB565 )
- {
- LinearSampleRGB565( inPixels, inDimensions, outPixels, outDimensions );
- }
- else
- {
- DALI_ASSERT_DEBUG( false == "Inner branch conditions don't match outer branch." );
- }
- }
- else
- {
- DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not linear sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) );
- }
-}
-
-} /* namespace Platform */
-} /* namespace Internal */
-} /* namespace Dali */
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_
-#define DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_
-
-// EXTERNAL INCLUDES
-#include <stdint.h>
-
-// INTERNAL INCLUDES
-#include <dali/integration-api/bitmap.h>
-#include <dali/public-api/images/image-operations.h>
-#include <resampler.h>
-
-#ifdef DALI_ADAPTOR_COMPILATION
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#else
-#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
-#endif
-
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Platform
-{
-
-/**
- * @brief Identify which combination of x and y dimensions matter in terminating iterative box filtering.
- */
-enum BoxDimensionTest
-{
- BoxDimensionTestEither,
- BoxDimensionTestBoth,
- BoxDimensionTestX,
- BoxDimensionTestY
-};
-
-/**
- * @brief The integer dimensions of an image or a region of an image packed into
- * 16 bits per component.
- * @note This can only be used for images of up to 65535 x 65535 pixels.
- */
-typedef Uint16Pair ImageDimensions;
-
-/**
- * @brief Work out the true desired width and height, accounting for special
- * rules for zeros in either or both input requested dimensions.
- *
- * @param[in] rawDimensions Width and height of image before processing.
- * @param[in] requestedDimensions Width and height of area to scale image into. Can be zero.
- * @return Dimensions of area to scale image into after special rules are applied.
- */
-ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions );
-
-/**
- * @defgroup BitmapOperations Bitmap-to-Bitmap Image operations.
- * @{
- */
-
-/**
- * @brief Apply requested attributes to bitmap.
- *
- * This is the top-level function which runs the on-load image post-processing
- * pipeline. Bitmaps enter here as loaded from the file system by the file
- * loaders and leave downscaled and filtered as requested by the application,
- * ready for use.
- *
- * @param[in] bitmap The input bitmap.
- * @param[in] requestedAttributes Attributes which should be applied to bitmap.
- * @return A bitmap which results from applying the requested attributes to the
- * bitmap passed-in, or the original bitmap passed in if the attributes
- * have no effect.
- */
-Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode = FittingMode::DEFAULT, SamplingMode::Type samplingMode = SamplingMode::DEFAULT );
-
-/**
- * @brief Apply downscaling to a bitmap according to requested attributes.
- * @note The input bitmap pixel buffer may be modified and used as scratch working space for efficiency, so it must be discarded.
- **/
-Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap,
- ImageDimensions desired,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode );
-/**@}*/
-
-/**
- * @defgroup ImageBufferScalingAlgorithms Pixel buffer-level scaling algorithms.
- * @{
- */
-
-/**
- * @brief Destructive in-place downscaling by a power of 2 factor.
- *
- * A box filter with a 2x2 kernel is repeatedly applied as long as the result
- * of the next downscaling step would not be smaller than the desired
- * dimensions.
- * @param[in,out] pixels The buffer both to read from and write the result to.
- * @param[in] pixelFormat The format of the image pointed at by pixels.
- * @param[in] inputWidth The width of the input image.
- * @param[in] inputHeight The height of the input image.
- * @param[in] desiredWidth The width the client is requesting.
- * @param[in] desiredHeight The height the client is requesting.
- * @param[out] outWidth The resulting width after downscaling.
- * @param[out] outHeight The resulting height after downscaling.
- */
-void DownscaleInPlacePow2( unsigned char * const pixels,
- Pixel::Format pixelFormat,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- unsigned& outWidth,
- unsigned& outHeight );
-
-/**
- * @brief Destructive in-place downscaling by a power of 2 factor.
- *
- * A box filter with a 2x2 kernel is repeatedly applied as long as the result
- * of the next downscaling step would not be smaller than the desired
- * dimensions.
- * @param[in,out] pixels The buffer both to read from and write the result to.
- * @param[in] inputWidth The width of the input image.
- * @param[in] inputHeight The height of the input image.
- * @param[in] desiredWidth The width the client is requesting.
- * @param[in] desiredHeight The height the client is requesting.
- * @param[out] outWidth The resulting width after downscaling.
- * @param[out] outHeight The resulting height after downscaling.
- */
-void DownscaleInPlacePow2RGB888( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight );
-
-/**
- * @copydoc DownscaleInPlacePow2RGB888
- */
-void DownscaleInPlacePow2RGBA8888( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight );
-
-/**
- * @copydoc DownscaleInPlacePow2RGB888
- *
- * For the 2-byte packed 16 bit format RGB565.
- */
-void DownscaleInPlacePow2RGB565( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight );
-
-/**
- * @copydoc DownscaleInPlacePow2RGB888
- *
- * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565.
- */
-void DownscaleInPlacePow2ComponentPair( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight );
-
-/**
- * @copydoc DownscaleInPlacePow2RGB888
- *
- * For single-byte formats such as lum8 or alpha8.
- */
-void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned int desiredWidth,
- unsigned int desiredHeight,
- BoxDimensionTest dimensionTest,
- unsigned int& outWidth,
- unsigned int& outHeight );
-
-/**
- * @brief Rescales an input image into the exact output dimensions passed-in.
- *
- * Uses point sampling, equivalent to GL_NEAREST texture filter mode, for the
- * fastest results, at the expense of aliasing (noisy images) when downscaling.
- * @note inPixels is allowed to alias outPixels if this is a downscaling,
- * but not for upscaling.
- */
-void PointSample( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- Pixel::Format pixelFormat,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight );
-
-/**
- * @copydoc PointSample
- *
- * Specialised for 4-byte formats like RGBA8888 and BGRA8888.
- */
-void PointSample4BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight );
-
-/**
- * @copydoc PointSample
- *
- * Specialised for 3-byte formats like RGB888 and BGR888.
- */
-void PointSample3BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight );
-
-/**
- * @copydoc PointSample
- *
- * Specialised for 2-byte formats like LA88.
- */
-void PointSample2BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight );
-
-/**
- * @copydoc PointSample
- *
- * Specialised for 1-byte formats like L8 and A8.
- */
-void PointSample1BPP( const unsigned char * inPixels,
- unsigned int inputWidth,
- unsigned int inputHeight,
- unsigned char * outPixels,
- unsigned int desiredWidth,
- unsigned int desiredHeight );
-
-/**
- * @brief Resample input image to output image using a bilinear filter.
- *
- * Each output pixel is formed of a weighted sum of a 2x2 block of four input
- * pixels
- * @pre inPixels must not alias outPixels. The input image should be a totally
- * separate buffer from the input one.
- */
-void LinearSample( const unsigned char * __restrict__ inPixels,
- ImageDimensions inDimensions,
- Pixel::Format pixelFormat,
- unsigned char * __restrict__ outPixels,
- ImageDimensions outDimensions );
-
-/**
- * @copydoc LinearSample
- *
- * Specialised for one byte per pixel formats.
- */
-void LinearSample1BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @copydoc LinearSample
- *
- * Specialised for two byte per pixel formats.
- */
-void LinearSample2BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @copydoc LinearSample
- *
- * Specialised for RGB565 16 bit pixel format.
- */
-void LinearSampleRGB565( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @copydoc LinearSample
- *
- * Specialised for three byte per pixel formats like RGB888.
- */
-void LinearSample3BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @copydoc LinearSample
- *
- * Specialised for four byte per pixel formats like RGBA8888.
- * @note, If used on RGBA8888, the A component will be blended independently.
- */
-void LinearSample4BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @brief Resamples the input image with the Lanczos algorithm.
- *
- * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
- * separate buffer from the output buffer.
- *
- * @param[in] inPixels Pointer to the input image buffer.
- * @param[in] inputDimensions The input dimensions of the image.
- * @param[out] outPixels Pointer to the output image buffer.
- * @param[in] desiredDimensions The output dimensions of the image.
- */
-void LanczosSample4BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @brief Resamples the input image with the Lanczos algorithm.
- *
- * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
- * separate buffer from the output buffer.
- *
- * @param[in] inPixels Pointer to the input image buffer.
- * @param[in] inputDimensions The input dimensions of the image.
- * @param[out] outPixels Pointer to the output image buffer.
- * @param[in] desiredDimensions The output dimensions of the image.
- */
-void LanczosSample1BPP( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions );
-
-/**
- * @brief Resamples the input image with the Lanczos algorithm.
- *
- * @pre @p inPixels must not alias @p outPixels. The input image should be a totally
- * separate buffer from the output buffer.
- *
- * @param[in] inPixels Pointer to the input image buffer.
- * @param[in] inputDimensions The input dimensions of the image.
- * @param[out] outPixels Pointer to the output image buffer.
- * @param[in] desiredDimensions The output dimensions of the image.
- */
-void Resample( const unsigned char * __restrict__ inPixels,
- ImageDimensions inputDimensions,
- unsigned char * __restrict__ outPixels,
- ImageDimensions desiredDimensions,
- Resampler::Filter filterType,
- int numChannels, bool hasAlpha );
-
-
-/**@}*/
-
-/**
- * @defgroup ScalingAlgorithmFragments Composable subunits of the scaling algorithms.
- * @{
- */
-
-/**
- * @brief Average adjacent pairs of pixels, overwriting the input array.
- * @param[in,out] pixels The array of pixels to work on.
- * @param[i] width The number of pixels in the array passed-in.
- */
-void HalveScanlineInPlaceRGB888( unsigned char * pixels, unsigned int width );
-
-/**
- * @copydoc HalveScanlineInPlaceRGB888
- */
-void HalveScanlineInPlaceRGBA8888( unsigned char * pixels, unsigned int width );
-
-/**
- * @copydoc HalveScanlineInPlaceRGB888
- */
-void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width );
-
-/**
- * @copydoc HalveScanlineInPlaceRGB888
- */
-void HalveScanlineInPlace2Bytes( unsigned char * pixels, unsigned int width );
-
-/**
- * @copydoc HalveScanlineInPlaceRGB888
- */
-void HalveScanlineInPlace1Byte( unsigned char * pixels, unsigned int width );
-
-/**
- * @brief Average pixels at corresponding offsets in two scanlines.
- *
- * outputScanline is allowed to alias scanline1.
- * @param[in] scanline1 First scanline of pixels to average.
- * @param[in] scanline2 Second scanline of pixels to average.
- * @param[out] outputScanline Destination for the averaged pixels.
- * @param[in] width The widths of all the scanlines passed-in.
- */
-void AverageScanlines1( const unsigned char * scanline1,
- const unsigned char * scanline2,
- unsigned char* outputScanline,
- /** Image width in pixels (1 byte == 1 pixel: e.g. lum8 or alpha8).*/
- unsigned int width );
-
-/**
- * @copydoc AverageScanlines1
- */
-void AverageScanlines2( const unsigned char * scanline1,
- const unsigned char * scanline2,
- unsigned char* outputScanline,
- /** Image width in pixels (2 bytes == 1 pixel: e.g. lum8alpha8).*/
- unsigned int width );
-
-/**
- * @copydoc AverageScanlines1
- */
-void AverageScanlines3( const unsigned char * scanline1,
- const unsigned char * scanline2,
- unsigned char* outputScanline,
- /** Image width in pixels (3 bytes == 1 pixel: e.g. RGB888).*/
- unsigned int width );
-
-/**
- * @copydoc AverageScanlines1
- */
-void AverageScanlinesRGBA8888( const unsigned char * scanline1,
- const unsigned char * scanline2,
- unsigned char * outputScanline,
- unsigned int width );
-
-/**
- * @copydoc AverageScanlines1
- */
-void AverageScanlinesRGB565( const unsigned char * scanline1,
- const unsigned char * scanline2,
- unsigned char* outputScanline,
- unsigned int width );
-/**@}*/
-
-/**
- * @defgroup TestableInlines Inline functions exposed in header to allow unit testing.
- * @{
- */
-
-/**
- * @brief Average two integer arguments.
- * @return The average of two uint arguments.
- * @param[in] a First component to average.
- * @param[in] b Second component to average.
- **/
-inline unsigned int AverageComponent( unsigned int a, unsigned int b )
-{
- unsigned int avg = (a + b) >> 1u;
- return avg;
-}
-
-/**
- * @brief Average a pair of RGBA8888 pixels.
- * @return The average of two RGBA8888 pixels.
- * @param[in] a First pixel to average.
- * @param[in] b Second pixel to average
- **/
-inline uint32_t AveragePixelRGBA8888( uint32_t a, uint32_t b )
-{
- const unsigned int avg =
- ((AverageComponent( (a & 0xff000000) >> 1u, (b & 0xff000000) >> 1u ) << 1u) & 0xff000000 ) +
- (AverageComponent( a & 0x00ff0000, b & 0x00ff0000 ) & 0x00ff0000 ) +
- (AverageComponent( a & 0x0000ff00, b & 0x0000ff00 ) & 0x0000ff00 ) +
- (AverageComponent( a & 0x000000ff, b & 0x000000ff ) );
- return avg;
- ///@ToDo: Optimise by trying return (((a ^ b) & 0xfefefefeUL) >> 1) + (a & b);
- ///@ToDo: Optimise for ARM using the single ARMV6 instruction: UHADD8 R4, R0, R5. This is not Neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro.
-}
-
-/**
- * @brief Average a pair of RGB565 pixels.
- * @param a[in] Low 16 bits hold a color value as RGB565 to average with parameter b.
- * @param b[in] Low 16 bits hold a color value as RGB565 to average with parameter a.
- * @return The average color of the two RGB565 pixels passed in, in the low 16 bits of the returned value.
- **/
-inline uint32_t AveragePixelRGB565( uint32_t a, uint32_t b )
-{
- const unsigned int avg =
- (AverageComponent( a & 0xf800, b & 0xf800 ) & 0xf800 ) +
- (AverageComponent( a & 0x7e0, b & 0x7e0 ) & 0x7e0 ) +
- (AverageComponent( a & 0x1f, b & 0x1f ) );
- return avg;
-}
-
-/** @return The weighted blend of two integers as a 16.16 fixed-point number, given a 0.16 fixed-point blending factor. */
-inline unsigned int WeightedBlendIntToFixed1616(unsigned int a, unsigned int b, unsigned int fractBlend )
-{
- DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." );
- const unsigned int weightedAFixed = a * (65535u - fractBlend);
- const unsigned int weightedBFixed = b * fractBlend;
- const unsigned blended = (weightedAFixed + weightedBFixed);
- return blended;
-}
-
-/** @brief Blend two 16.16 inputs to give a 16.32 output. */
-inline uint64_t WeightedBlendFixed1616ToFixed1632(unsigned int a, unsigned int b, unsigned int fractBlend )
-{
- DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." );
- // Blend while promoting intermediates to 16.32 fixed point:
- const uint64_t weightedAFixed = uint64_t(a) * (65535u - fractBlend);
- const uint64_t weightedBFixed = uint64_t(b) * fractBlend;
- const uint64_t blended = (weightedAFixed + weightedBFixed);
- return blended;
-}
-
-/**
- * @brief Blend 4 taps into one value using horizontal and vertical weights.
- */
-inline unsigned int BilinearFilter1Component(unsigned int tl, unsigned int tr, unsigned int bl, unsigned int br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical )
-{
- DALI_ASSERT_DEBUG( fractBlendHorizontal <= 65535u && "Factor should be in 0.16 fixed-point." );
- DALI_ASSERT_DEBUG( fractBlendVertical <= 65535u && "Factor should be in 0.16 fixed-point." );
-
- const unsigned int topBlend = WeightedBlendIntToFixed1616( tl, tr, fractBlendHorizontal );
- const unsigned int botBlend = WeightedBlendIntToFixed1616( bl, br, fractBlendHorizontal );
- const uint64_t blended2x2 = WeightedBlendFixed1616ToFixed1632( topBlend, botBlend, fractBlendVertical );
- const unsigned int rounded = (blended2x2 + (1u << 31u) ) >> 32u;
- return rounded;
-}
-
-/**@}*/
-
-} /* namespace Platform */
-} /* namespace Internal */
-} /* namespace Dali */
-
-#endif /* DALI_INTERNAL_PLATFORM_IMAGE_OPERATIONS_H_ */
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include "pixel-manipulation.h"
-
-// INTERNAL HEADERS
-#include <dali/public-api/images/pixel.h>
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-namespace Internal
-{
-namespace Adaptor
-{
-
-struct Location
-{
- unsigned int bitShift;
- unsigned int bitMask;
- bool available;
-};
-
-struct Locations
-{
- Location luminance;
- Location alpha;
- Location red;
- Location green;
- Location blue;
-};
-
-
-bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel )
-{
- switch (pixelFormat)
- {
- case Dali::Pixel::A8:
- {
- return (channel == ALPHA);
- }
- case Dali::Pixel::L8:
- {
- return (channel == LUMINANCE);
- }
- case Dali::Pixel::LA88:
- {
- return ( channel == LUMINANCE || channel == ALPHA );
- }
- case Dali::Pixel::RGB565:
- case Dali::Pixel::BGR565:
- case Dali::Pixel::RGB888:
- case Dali::Pixel::RGB8888:
- case Dali::Pixel::BGR8888:
- case Dali::Pixel::RGB16F:
- case Dali::Pixel::RGB32F:
- {
- return ( channel == RED || channel == GREEN || channel == BLUE );
- }
-
- case Dali::Pixel::RGBA8888:
- case Dali::Pixel::BGRA8888:
- case Dali::Pixel::RGBA4444:
- case Dali::Pixel::BGRA4444:
- case Dali::Pixel::RGBA5551:
- case Dali::Pixel::BGRA5551:
- {
- return ( channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA );
- }
-
- case Dali::Pixel::INVALID:
- case Dali::Pixel::COMPRESSED_R11_EAC:
- case Dali::Pixel::COMPRESSED_SIGNED_R11_EAC:
- case Dali::Pixel::COMPRESSED_RG11_EAC:
- case Dali::Pixel::COMPRESSED_SIGNED_RG11_EAC:
- case Dali::Pixel::COMPRESSED_RGB8_ETC2:
- case Dali::Pixel::COMPRESSED_SRGB8_ETC2:
- case Dali::Pixel::COMPRESSED_RGB8_ETC1:
- case Dali::Pixel::COMPRESSED_RGB_PVRTC_4BPPV1:
- case Dali::Pixel::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
- case Dali::Pixel::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
- case Dali::Pixel::COMPRESSED_RGBA8_ETC2_EAC:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR:
- case Dali::Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
- case Dali::Pixel::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
- {
- DALI_LOG_ERROR("Pixel formats for compressed images are not compatible with simple channels.\n");
- break;
- }
- }
-
- return false;
-}
-
-unsigned int ReadChannel( unsigned char* pixelData,
- Dali::Pixel::Format pixelFormat,
- Channel channel )
-{
- switch (pixelFormat)
- {
- case Dali::Pixel::A8:
- {
- if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else return 0u;
- }
- case Dali::Pixel::L8:
- {
- if( channel == LUMINANCE )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else return 0u;
- }
- case Dali::Pixel::LA88:
- {
- if( channel == LUMINANCE )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*(pixelData+1));
- }
- else return 0u;
- }
- case Dali::Pixel::RGB565:
- {
- if( channel == RED )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
- }
- else if( channel == GREEN )
- {
- return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
- ((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
- }
- else if( channel == BLUE )
- {
- return static_cast<unsigned int>(*(pixelData+1)) & 0x1F;
- }
- else return 0u;
- }
-
- case Dali::Pixel::BGR565:
- {
- if( channel == BLUE )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
- }
- else if( channel == GREEN )
- {
- return ((static_cast<unsigned int>(*pixelData) & 0x07) << 3) |
- ((static_cast<unsigned int>(*(pixelData+1)) & 0xE0) >> 5);
- }
- else if( channel == RED )
- {
- return (static_cast<unsigned int>(*(pixelData+1) & 0x1F) );
- }
- else return 0u;
- }
-
- case Dali::Pixel::RGB888:
- case Dali::Pixel::RGB8888:
- {
- if( channel == RED )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else if( channel == GREEN )
- {
- return static_cast<unsigned int>(*(pixelData+1));
- }
- else if( channel == BLUE )
- {
- return static_cast<unsigned int>(*(pixelData+2));
- }
- else return 0u;
- }
-
- case Dali::Pixel::BGR8888:
- {
- if( channel == BLUE )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else if( channel == GREEN )
- {
- return static_cast<unsigned int>(*(pixelData+1));
- }
- else if( channel == RED )
- {
- return static_cast<unsigned int>(*(pixelData+2));
- }
- else return 0u;
- }
-
- case Dali::Pixel::RGBA8888:
- {
- if( channel == RED )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else if( channel == GREEN )
- {
- return static_cast<unsigned int>(*(pixelData+1));
- }
- else if( channel == BLUE )
- {
- return static_cast<unsigned int>(*(pixelData+2));
- }
- else if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*(pixelData+3));
- }
- else return 0u;
- }
-
- case Dali::Pixel::BGRA8888:
- {
- if( channel == BLUE )
- {
- return static_cast<unsigned int>(*pixelData);
- }
- else if( channel == GREEN )
- {
- return static_cast<unsigned int>(*(pixelData+1));
- }
- else if( channel == RED )
- {
- return static_cast<unsigned int>(*(pixelData+2));
- }
- else if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*(pixelData+3));
- }
- else return 0u;
- }
-
- case Dali::Pixel::RGBA4444:
- {
- if( channel == RED )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
- }
- else if( channel == GREEN )
- {
- return (static_cast<unsigned int>(*pixelData) & 0x0F);
- }
- else if( channel == BLUE )
- {
- return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
- }
- else if( channel == ALPHA )
- {
- return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
- }
- else return 0u;
- }
-
- case Dali::Pixel::BGRA4444:
- {
- if( channel == BLUE )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF0) >> 4;
- }
- else if( channel == GREEN )
- {
- return (static_cast<unsigned int>(*pixelData) & 0x0F);
- }
- else if( channel == RED )
- {
- return (static_cast<unsigned int>(*(pixelData+1)) & 0xF0) >> 4;
- }
- else if( channel == ALPHA )
- {
- return (static_cast<unsigned int>(*(pixelData+1)) & 0x0F);
- }
- else return 0u;
- }
-
- case Dali::Pixel::RGBA5551:
- {
- if( channel == RED )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
- }
- else if( channel == GREEN )
- {
- return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
- ((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
- }
- else if( channel == BLUE )
- {
- return (static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
- }
- else if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
- }
-
- else return 0u;
- }
-
- case Dali::Pixel::BGRA5551:
- {
- if( channel == BLUE )
- {
- return (static_cast<unsigned int>(*pixelData) & 0xF8) >> 3;
- }
- else if( channel == GREEN )
- {
- return ((static_cast<unsigned int>(*pixelData) & 0x07) << 2) |
- ((static_cast<unsigned int>(*(pixelData+1)) & 0xC0) >> 6);
- }
- else if( channel == RED )
- {
- return ( static_cast<unsigned int>(*(pixelData+1)) & 0x3E) >> 1;
- }
- else if( channel == ALPHA )
- {
- return static_cast<unsigned int>(*(pixelData+1)) & 0x01;
- }
-
- else return 0u;
- }
-
- default:
- {
- return 0u;
- }
- }
-}
-
-void WriteChannel( unsigned char* pixelData,
- Dali::Pixel::Format pixelFormat,
- Channel channel,
- unsigned int channelValue )
-{
- switch (pixelFormat)
- {
- case Dali::Pixel::A8:
- {
- if( channel == ALPHA )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
- case Dali::Pixel::L8:
- {
- if( channel == LUMINANCE )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
- case Dali::Pixel::LA88:
- {
- if( channel == LUMINANCE )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
- case Dali::Pixel::RGB565:
- {
- if( channel == RED )
- {
- *pixelData &= ~0xF8;
- *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x07;
- *pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
-
- *(pixelData+1) &= ~0xE0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
- }
- else if( channel == BLUE )
- {
- *(pixelData+1) &= ~0x1F;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
- }
- break;
- }
-
- case Dali::Pixel::BGR565:
- {
- if( channel == BLUE )
- {
- *pixelData &= ~0xF8;
- *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x07;
- *pixelData |= static_cast<unsigned char>( (channelValue >> 3) & 0x07 );
-
- *(pixelData+1) &= ~0xE0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 5) & 0xE0 );
- }
- else if( channel == RED )
- {
- *(pixelData+1) &= ~0x1F;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x1F );
- }
- break;
- }
-
- case Dali::Pixel::RGB888:
- case Dali::Pixel::RGB8888:
- {
- if( channel == RED )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == GREEN )
- {
- *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == BLUE )
- {
- *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
-
- case Dali::Pixel::BGR8888:
- {
- if( channel == BLUE )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == GREEN )
- {
- *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == RED )
- {
- *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
-
- case Dali::Pixel::RGBA8888:
- {
- if( channel == RED )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == GREEN )
- {
- *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == BLUE )
- {
- *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
-
- case Dali::Pixel::BGRA8888:
- {
- if( channel == BLUE )
- {
- *pixelData = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == GREEN )
- {
- *(pixelData+1) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == RED )
- {
- *(pixelData+2) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+3) = static_cast<unsigned char>( channelValue & 0xFF );
- }
- break;
- }
-
- case Dali::Pixel::RGBA4444:
- {
- if( channel == RED )
- {
- *pixelData &= ~0xF0;
- *pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x0F;
- *pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
- }
- else if( channel == BLUE )
- {
- *(pixelData+1) &= ~0xF0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+1) &= ~0x0F;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
- }
- break;
- }
-
- case Dali::Pixel::BGRA4444:
- {
- if( channel == BLUE )
- {
- *pixelData &= ~0xF0;
- *pixelData |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x0F;
- *pixelData |= static_cast<unsigned char>( channelValue & 0x0F );
- }
- else if( channel == RED )
- {
- *(pixelData+1) &= ~0xF0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 4) & 0xF0 );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+1) &= ~0x0F;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x0F );
- }
- break;
- }
-
- case Dali::Pixel::RGBA5551:
- {
- // rrrrrggg ggbbbbba
- // F8 7 C0 3E 1
- if( channel == RED )
- {
- *pixelData &= ~0xF8;
- *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x07;
- *pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
-
- *(pixelData+1) &= ~0xC0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
- }
- else if( channel == BLUE )
- {
- *(pixelData+1) &= ~0x3E;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1) & 0x3E );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+1) &= ~0x01;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
- }
- break;
- }
-
- case Dali::Pixel::BGRA5551:
- {
- if( channel == BLUE )
- {
- *pixelData &= ~0xF8;
- *pixelData |= static_cast<unsigned char>( (channelValue << 3) & 0xF8 );
- }
- else if( channel == GREEN )
- {
- *pixelData &= ~0x07;
- *pixelData |= static_cast<unsigned char>( (channelValue >> 2) & 0x07 );
-
- *(pixelData+1) &= ~0xC0;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 6) & 0xC0 );
- }
- else if( channel == RED )
- {
- *(pixelData+1) &= ~0x3E;
- *(pixelData+1) |= static_cast<unsigned char>( (channelValue << 1 ) & 0x3E );
- }
- else if( channel == ALPHA )
- {
- *(pixelData+1) &= ~0x01;
- *(pixelData+1) |= static_cast<unsigned char>( channelValue & 0x01 );
- }
- break;
- }
-
- default:
- break;
- }
-}
-
-void ConvertColorChannelsToRGBA8888(
- unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat,
- unsigned char* destPixel, int destOffset )
-{
- int red = ReadChannel(srcPixel+srcOffset, srcFormat, RED );
- int green = ReadChannel(srcPixel+srcOffset, srcFormat, GREEN );
- int blue = ReadChannel(srcPixel+srcOffset, srcFormat, BLUE );
- switch( srcFormat )
- {
- case Dali::Pixel::RGB565:
- case Dali::Pixel::BGR565:
- {
- red = (red<<3) | (red & 0x07);
- green = (green << 2) | (green & 0x03);
- blue = (blue<<3) | (blue & 0x07);
- break;
- }
- case Dali::Pixel::RGBA4444:
- case Dali::Pixel::BGRA4444:
- {
- red = (red<<4) | (red&0x0F);
- green = (green<<4) | (green&0x0F);
- blue = (blue<<4) | (blue&0x0F);
- break;
- }
- case Dali::Pixel::RGBA5551:
- case Dali::Pixel::BGRA5551:
- {
- red = (red<<3) | (red&0x07);
- green = (green<<3) | (green&0x07);
- blue = (blue<<3) | (blue&0x07);
- break;
- }
- default:
- break;
- }
- WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, RED, red);
- WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, GREEN, green);
- WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, BLUE, blue);
-}
-
-
-int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat )
-{
- int alpha = ReadChannel(srcPixel+srcOffset, srcFormat, ALPHA );
- int destAlpha = alpha;
- switch( srcFormat )
- {
- case Pixel::RGBA5551:
- case Pixel::BGRA5551:
- {
- destAlpha = (alpha==0)?0:255;
- break;
- }
- case Pixel::RGBA4444:
- case Pixel::BGRA4444:
- {
- destAlpha = (alpha<<4) | (alpha&0x0F);
- break;
- }
- default:
- break;
- }
- return destAlpha;
-}
-
-} // Adaptor
-} // Internal
-} // Dali
+++ /dev/null
-# Add local source files here:
-
-tizen_platform_abstraction_src_files = \
- $(tizen_platform_abstraction_src_dir)/tizen-platform-abstraction.cpp \
- $(tizen_platform_abstraction_src_dir)/tizen-logging.cpp \
- \
- $(tizen_platform_abstraction_src_dir)/resource-loader/network/file-download.cpp \
- $(tizen_platform_abstraction_src_dir)/resource-loader/network/http-utils.cpp \
- \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-astc.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-bmp.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-gif.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-ico.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-jpeg-turbo.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-ktx.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-png.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/loader-wbmp.cpp \
- $(tizen_platform_abstraction_src_dir)/image-loaders/image-loader.cpp \
- \
- $(portable_platform_abstraction_src_dir)/image-operations.cpp \
- $(portable_platform_abstraction_src_dir)/pixel-manipulation.cpp \
- $(portable_platform_abstraction_src_dir)/alpha-mask.cpp \
- $(portable_platform_abstraction_src_dir)/gaussian-blur.cpp
-
-# Add public headers here:
-
-# platform_abstraction_header_files =
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "image-loader.h"
-
-#include <dali/devel-api/common/ref-counted-dali-vector.h>
-#include <adaptors/common/pixel-buffer-impl.h>
-
-
-#include "loader-astc.h"
-#include "loader-bmp.h"
-#include "loader-gif.h"
-#include "loader-ico.h"
-#include "loader-jpeg.h"
-#include "loader-ktx.h"
-#include "loader-png.h"
-#include "loader-wbmp.h"
-#include "image-operations.h"
-#include "portable/file-reader.h"
-
-using namespace Dali::Integration;
-
-namespace Dali
-{
-namespace TizenPlatform
-{
-
-namespace
-{
-typedef bool (*LoadBitmapFunction)( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& pixelData );
-typedef bool (*LoadBitmapHeaderFunction)( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-#if defined(DEBUG_ENABLED)
-Integration::Log::Filter* gLogFilter = Debug::Filter::New( Debug::Concise, false, "LOG_IMAGE_LOADING" );
-#endif
-
-/**
- * Stores the magic bytes, and the loader and header functions used for each image loader.
- */
-struct BitmapLoader
-{
- unsigned char magicByte1; ///< The first byte in the file should be this
- unsigned char magicByte2; ///< The second byte in the file should be this
- LoadBitmapFunction loader; ///< The function which decodes the file
- LoadBitmapHeaderFunction header; ///< The function which decodes the header of the file
- Bitmap::Profile profile; ///< The kind of bitmap to be created
- /// (addressable packed pixels or an opaque compressed blob).
-};
-
-/**
- * Enum for file formats, has to be in sync with BITMAP_LOADER_LOOKUP_TABLE
- */
-enum FileFormats
-{
- // Unknown file format
- FORMAT_UNKNOWN = -1,
-
- // formats that use magic bytes
- FORMAT_PNG = 0,
- FORMAT_JPEG,
- FORMAT_BMP,
- FORMAT_GIF,
- FORMAT_KTX,
- FORMAT_ASTC,
- FORMAT_ICO,
- FORMAT_MAGIC_BYTE_COUNT,
-
- // formats after this one do not use magic bytes
- FORMAT_WBMP = FORMAT_MAGIC_BYTE_COUNT,
- FORMAT_TOTAL_COUNT
-};
-
-/**
- * A lookup table containing all the bitmap loaders with the appropriate information.
- * Has to be in sync with enum FileFormats
- */
-const BitmapLoader BITMAP_LOADER_LOOKUP_TABLE[FORMAT_TOTAL_COUNT] =
-{
- { Png::MAGIC_BYTE_1, Png::MAGIC_BYTE_2, LoadBitmapFromPng, LoadPngHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
- { Jpeg::MAGIC_BYTE_1, Jpeg::MAGIC_BYTE_2, LoadBitmapFromJpeg, LoadJpegHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
- { Bmp::MAGIC_BYTE_1, Bmp::MAGIC_BYTE_2, LoadBitmapFromBmp, LoadBmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
- { Gif::MAGIC_BYTE_1, Gif::MAGIC_BYTE_2, LoadBitmapFromGif, LoadGifHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
- { Ktx::MAGIC_BYTE_1, Ktx::MAGIC_BYTE_2, LoadBitmapFromKtx, LoadKtxHeader, Bitmap::BITMAP_COMPRESSED },
- { Astc::MAGIC_BYTE_1, Astc::MAGIC_BYTE_2, LoadBitmapFromAstc, LoadAstcHeader, Bitmap::BITMAP_COMPRESSED },
- { Ico::MAGIC_BYTE_1, Ico::MAGIC_BYTE_2, LoadBitmapFromIco, LoadIcoHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
- { 0x0, 0x0, LoadBitmapFromWbmp, LoadWbmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS },
-};
-
-const unsigned int MAGIC_LENGTH = 2;
-
-/**
- * This code tries to predict the file format from the filename to help with format picking.
- */
-struct FormatExtension
-{
- const std::string extension;
- FileFormats format;
-};
-
-const FormatExtension FORMAT_EXTENSIONS[] =
-{
- { ".png", FORMAT_PNG },
- { ".jpg", FORMAT_JPEG },
- { ".bmp", FORMAT_BMP },
- { ".gif", FORMAT_GIF },
- { ".ktx", FORMAT_KTX },
- { ".astc", FORMAT_ASTC },
- { ".ico", FORMAT_ICO },
- { ".wbmp", FORMAT_WBMP }
-};
-
-const unsigned int FORMAT_EXTENSIONS_COUNT = sizeof(FORMAT_EXTENSIONS) / sizeof(FormatExtension);
-
-FileFormats GetFormatHint( const std::string& filename )
-{
- FileFormats format = FORMAT_UNKNOWN;
-
- for ( unsigned int i = 0; i < FORMAT_EXTENSIONS_COUNT; ++i )
- {
- unsigned int length = FORMAT_EXTENSIONS[i].extension.size();
- if ( ( filename.size() > length ) &&
- ( 0 == filename.compare( filename.size() - length, length, FORMAT_EXTENSIONS[i].extension ) ) )
- {
- format = FORMAT_EXTENSIONS[i].format;
- break;
- }
- }
-
- return format;
-}
-
-/**
- * Checks the magic bytes of the file first to determine which Image decoder to use to decode the
- * bitmap.
- * @param[in] fp The file to decode
- * @param[in] format Hint about what format to try first
- * @param[out] loader Set with the function to use to decode the image
- * @param[out] header Set with the function to use to decode the header
- * @param[out] profile The kind of bitmap to hold the bits loaded for the bitmap.
- * @return true, if we can decode the image, false otherwise
- */
-bool GetBitmapLoaderFunctions( FILE *fp,
- FileFormats format,
- LoadBitmapFunction& loader,
- LoadBitmapHeaderFunction& header,
- Bitmap::Profile& profile )
-{
- unsigned char magic[MAGIC_LENGTH];
- size_t read = fread(magic, sizeof(unsigned char), MAGIC_LENGTH, fp);
-
- // Reset to the start of the file.
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking to start of file\n");
- }
-
- if (read != MAGIC_LENGTH)
- {
- return false;
- }
-
- bool loaderFound = false;
- const BitmapLoader *lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
- ImageLoader::Input defaultInput( fp );
-
- // try hinted format first
- if ( format != FORMAT_UNKNOWN )
- {
- lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + format;
- if ( format >= FORMAT_MAGIC_BYTE_COUNT ||
- ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] ) )
- {
- unsigned int width = 0;
- unsigned int height = 0;
- loaderFound = lookupPtr->header( fp, width, height );
- }
- }
-
- // then try to get a match with formats that have magic bytes
- if ( false == loaderFound )
- {
- for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE;
- lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
- ++lookupPtr )
- {
- if ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] )
- {
- // to seperate ico file format and wbmp file format
- unsigned int width = 0;
- unsigned int height = 0;
- loaderFound = lookupPtr->header(fp, width, height);
- }
- if (loaderFound)
- {
- break;
- }
- }
- }
-
- // finally try formats that do not use magic bytes
- if ( false == loaderFound )
- {
- for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT;
- lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_TOTAL_COUNT;
- ++lookupPtr )
- {
- // to seperate ico file format and wbmp file format
- unsigned int width = 0;
- unsigned int height = 0;
- loaderFound = lookupPtr->header(fp, width, height);
- if (loaderFound)
- {
- break;
- }
- }
- }
-
- // if a loader was found set the outputs
- if ( loaderFound )
- {
- loader = lookupPtr->loader;
- header = lookupPtr->header;
- profile = lookupPtr->profile;
- }
-
- // Reset to the start of the file.
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking to start of file\n");
- }
-
- return loaderFound;
-}
-
-} // anonymous namespace
-
-
-namespace ImageLoader
-{
-
-bool ConvertStreamToBitmap( const BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer )
-{
- DALI_LOG_TRACE_METHOD( gLogFilter );
-
- bool result = false;
-
- if (fp != NULL)
- {
- LoadBitmapFunction function;
- LoadBitmapHeaderFunction header;
-
- Bitmap::Profile profile;
-
- if ( GetBitmapLoaderFunctions( fp,
- GetFormatHint( path ),
- function,
- header,
- profile ) )
- {
- const ScalingParameters scalingParameters( resource.size, resource.scalingMode, resource.samplingMode );
- const ImageLoader::Input input( fp, scalingParameters, resource.orientationCorrection );
-
- // Run the image type decoder:
- result = function( input, pixelBuffer );
-
- if (!result)
- {
- DALI_LOG_WARNING( "Unable to convert %s\n", path.c_str() );
- pixelBuffer.Reset();
- }
-
- pixelBuffer = Internal::Platform::ApplyAttributesToBitmap( pixelBuffer, resource.size, resource.scalingMode, resource.samplingMode );
- }
- else
- {
- DALI_LOG_WARNING( "Image Decoder for %s unavailable\n", path.c_str() );
- }
- }
-
- return result;
-}
-
-ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path )
-{
- ResourcePointer result;
- Dali::Devel::PixelBuffer bitmap;
-
- Internal::Platform::FileReader fileReader( path );
- FILE * const fp = fileReader.GetFile();
- if( fp != NULL )
- {
- bool success = ConvertStreamToBitmap(resource, path, fp, bitmap);
- if (success && bitmap)
- {
- Bitmap::Profile profile{Bitmap::Profile::BITMAP_2D_PACKED_PIXELS};
-
- // For backward compatibility the Bitmap must be created
- auto retval = Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD);
-
- DALI_LOG_SET_OBJECT_STRING( retval, path );
-
- retval->GetPackedPixelsProfile()->ReserveBuffer(
- bitmap.GetPixelFormat(),
- bitmap.GetWidth(),
- bitmap.GetHeight(),
- bitmap.GetWidth(),
- bitmap.GetHeight()
- );
-
- auto& impl = Dali::GetImplementation(bitmap);
-
- std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer());
- result.Reset(retval);
- }
- }
- return result;
-}
-
-///@ToDo: Rename GetClosestImageSize() functions. Make them use the orientation correction and scaling information. Requires jpeg loader to tell us about reorientation. [Is there still a requirement for this functionality at all?]
-ImageDimensions GetClosestImageSize( const std::string& filename,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection )
-{
- unsigned int width = 0;
- unsigned int height = 0;
-
- Internal::Platform::FileReader fileReader( filename );
- FILE *fp = fileReader.GetFile();
- if (fp != NULL)
- {
- LoadBitmapFunction loaderFunction;
- LoadBitmapHeaderFunction headerFunction;
- Bitmap::Profile profile;
-
- if ( GetBitmapLoaderFunctions( fp,
- GetFormatHint(filename),
- loaderFunction,
- headerFunction,
- profile ) )
- {
- const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
-
- const bool read_res = headerFunction( input, width, height );
- if(!read_res)
- {
- DALI_LOG_WARNING("Image Decoder failed to read header for %s\n", filename.c_str());
- }
- }
- else
- {
- DALI_LOG_WARNING("Image Decoder for %s unavailable\n", filename.c_str());
- }
- }
- return ImageDimensions( width, height );
-}
-
-ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection )
-{
- unsigned int width = 0;
- unsigned int height = 0;
-
- // Get the blob of binary data that we need to decode:
- DALI_ASSERT_DEBUG( resourceBuffer );
- Dali::RefCountedVector<uint8_t>* const encodedBlob = reinterpret_cast<Dali::RefCountedVector<uint8_t>*>( resourceBuffer.Get() );
-
- if( encodedBlob != 0 )
- {
- if( encodedBlob->GetVector().Size() )
- {
- // Open a file handle on the memory buffer:
- Internal::Platform::FileReader fileReader( encodedBlob->GetVector() );
- FILE *fp = fileReader.GetFile();
- if ( fp != NULL )
- {
- LoadBitmapFunction loaderFunction;
- LoadBitmapHeaderFunction headerFunction;
- Bitmap::Profile profile;
-
- if ( GetBitmapLoaderFunctions( fp,
- FORMAT_UNKNOWN,
- loaderFunction,
- headerFunction,
- profile ) )
- {
- const ImageLoader::Input input( fp, ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection );
- const bool read_res = headerFunction( input, width, height );
- if( !read_res )
- {
- DALI_LOG_WARNING( "Image Decoder failed to read header for resourceBuffer\n" );
- }
- }
- }
- }
- }
- return ImageDimensions( width, height );
-}
-
-} // ImageLoader
-} // TizenPlatform
-} // Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
-#define __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// EXTERNAL INCLUDES
-#include <dali/public-api/images/image-operations.h>
-#include <dali/integration-api/resource-types.h>
-#include <dali/integration-api/bitmap.h>
-#include <dali/public-api/images/pixel-data.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#include <string>
-
-namespace Dali
-{
-namespace Integration
-{
-typedef IntrusivePtr<Dali::RefObject> ResourcePointer;
-} // Integration
-
-namespace TizenPlatform
-{
-namespace ImageLoader
-{
-/**
- * Convert a file stream into a bitmap.
- * @param[in] resource The resource to convert.
- * @param[in] path The path to the resource.
- * @param[in] fp File Pointer. Closed on exit.
- * @param[out] bitmap Pointer to write bitmap to
- * @return true on success, false on failure
- */
-bool ConvertStreamToBitmap( const Integration::BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer );
-
-/**
- * Convert a bitmap and write to a file stream.
- * @param[in] path The path to the resource.
- * @param[in] fp File Pointer. Closed on exit.
- * @param[out] pixelData Reference to PixelData object.
- * @return true on success, false on failure
- */
-bool ConvertBitmapToStream( std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer );
-
-/**
- * Loads an image synchronously
- * @param resource details of the image
- * @param path to the image
- * @return bitmap
- */
-Integration::ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path );
-
-/**
- * @returns the closest image size
- */
-ImageDimensions GetClosestImageSize( const std::string& filename,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection );
-
-/**
- * @returns the closest image size
- */
-ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection );
-
-} // ImageLoader
-} // TizenPlatform
-} // Dali
-
-#endif // __DALI_TIZEN_PLATFORM_IMAGE_LOADER_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "loader-astc.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/public-api/common/compile-time-assert.h>
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/images/pixel.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#include <adaptors/common/pixel-buffer-impl.h>
-
-namespace Dali
-{
-namespace TizenPlatform
-{
-namespace
-{
-
-// Max width or height of an image.
-const unsigned MAX_TEXTURE_DIMENSION = 4096;
-// Max bytes of image data allowed. Not a precise number, just a sanity check.
-const unsigned MAX_IMAGE_DATA_SIZE = MAX_TEXTURE_DIMENSION * MAX_TEXTURE_DIMENSION;
-
-// Minimum and maximum possible sizes for ASTC blocks.
-const unsigned int MINIMUM_ASTC_BLOCK_SIZE = 4;
-const unsigned int MAXIMUM_ASTC_BLOCK_SIZE = 12;
-
-typedef uint8_t Byte;
-
-// This bytes identify an ASTC native file.
-const Byte FileIdentifier[] = {
- 0x13, 0xAB, 0xA1, 0x5C
-};
-
-
-/**
- * @brief This struct defines the ASTC file header values. From ASTC specifications.
- * Packed attribute stops the structure from being aligned to compiler defaults
- * so we can be sure of reading the whole header from file in one call to fread().
- * Note: members to not conform to coding standards in order to be consistent with ASTC spec.
- */
-struct AstcFileHeader
-{
- unsigned char magic[ 4 ];
- unsigned char blockdim_x;
- unsigned char blockdim_y;
- unsigned char blockdim_z;
- unsigned char xsize[ 3 ];
- unsigned char ysize[ 3 ];
- unsigned char zsize[ 3 ];
-} __attribute__ ( (__packed__));
-
-using namespace Pixel;
-
-/**
- * @brief This table allows fast conversion from an ASTC block size ([height][width]) to a pixel format.
- * This could be done within a switch, but this way we have a constant time function.
- * Note: As 4 is the minimum block size, 4 is subtracted from both the width and height to optimise size.
- * IE. Table format is: Increasing order of block width from left-to-right: 4 -> 12
- * Increasing order of block height from top-to-bottom: 4 -> 12
- */
-Pixel::Format AstcLinearBlockSizeToPixelFormatTable[][( MAXIMUM_ASTC_BLOCK_SIZE - MINIMUM_ASTC_BLOCK_SIZE ) + 1] = {
- { COMPRESSED_RGBA_ASTC_4x4_KHR, COMPRESSED_RGBA_ASTC_5x4_KHR, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
- { INVALID, COMPRESSED_RGBA_ASTC_5x5_KHR, COMPRESSED_RGBA_ASTC_6x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x5_KHR, INVALID, INVALID },
- { INVALID, INVALID, COMPRESSED_RGBA_ASTC_6x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x6_KHR, INVALID, INVALID },
- { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
- { INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_8x8_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x8_KHR, INVALID, INVALID },
- { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
- { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_10x10_KHR, INVALID, COMPRESSED_RGBA_ASTC_12x10_KHR },
- { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID },
- { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_12x12_KHR }
-};
-
-/**
- * @brief Uses header information to return the respective ASTC pixel format.
- *
- * @param[in] header A populated AstcFileHeader struct
- * @return The pixel format, or INVALID if the block size was invalid
- */
-Pixel::Format GetAstcPixelFormat( AstcFileHeader& header )
-{
- // Check the block size is valid. This will also prevent an invalid read from the conversion table.
- if( ( header.blockdim_x < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_x > MAXIMUM_ASTC_BLOCK_SIZE ) ||
- ( header.blockdim_y < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_y > MAXIMUM_ASTC_BLOCK_SIZE ) )
- {
- return Pixel::INVALID;
- }
-
- // Read the equivalent pixel format from the conversion table.
- return AstcLinearBlockSizeToPixelFormatTable[ header.blockdim_y - MINIMUM_ASTC_BLOCK_SIZE ][ header.blockdim_x - MINIMUM_ASTC_BLOCK_SIZE ];
-}
-
-/**
- * @brief Internal method to load ASTC header info from a file.
- *
- * @param[in] filePointer The file pointer to the ASTC file to read
- * @param[out] width The width is output to this value
- * @param[out] height The height is output to this value
- * @param[out] fileHeader This will be populated with the header data
- * @return True if the file is valid, false otherwise
- */
-bool LoadAstcHeader( FILE * const filePointer, unsigned int& width, unsigned int& height, AstcFileHeader& fileHeader )
-{
- // Pull the bytes of the file header in as a block:
- const unsigned int readLength = sizeof( AstcFileHeader );
- if( fread( &fileHeader, 1, readLength, filePointer ) != readLength )
- {
- return false;
- }
-
- // Check the header contains the ASTC native file identifier.
- bool headerIsValid = memcmp( fileHeader.magic, FileIdentifier, sizeof( fileHeader.magic ) ) == 0;
- if( !headerIsValid )
- {
- DALI_LOG_ERROR( "File is not a valid ASTC native file\n" );
- // Return here as otherwise, if not a valid ASTC file, we are likely to pick up other header errors spuriously.
- return false;
- }
-
- // Convert the 3-byte values for width and height to a single resultant value.
- width = fileHeader.xsize[0] | ( fileHeader.xsize[1] << 8 ) | ( fileHeader.xsize[2] << 16 );
- height = fileHeader.ysize[0] | ( fileHeader.ysize[1] << 8 ) | ( fileHeader.ysize[2] << 16 );
-
- const unsigned int zDepth = fileHeader.zsize[0] + ( fileHeader.zsize[1] << 8 ) + ( fileHeader.zsize[2] << 16 );
-
- // Check image dimensions are within limits.
- if( ( width > MAX_TEXTURE_DIMENSION ) || ( height > MAX_TEXTURE_DIMENSION ) )
- {
- DALI_LOG_ERROR( "ASTC file has larger than supported dimensions: %d,%d\n", width, height );
- headerIsValid = false;
- }
-
- // Confirm the ASTC block does not have any Z depth.
- if( zDepth != 1 )
- {
- DALI_LOG_ERROR( "ASTC files with z size other than 1 are not supported. Z size is: %d\n", zDepth );
- headerIsValid = false;
- }
-
- return headerIsValid;
-}
-
-} // Unnamed namespace.
-
-
-// File loading API entry-point:
-bool LoadAstcHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- AstcFileHeader fileHeader;
- return LoadAstcHeader( input.file, width, height, fileHeader );
-}
-
-// File loading API entry-point:
-bool LoadBitmapFromAstc( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- FILE* const filePointer = input.file;
- if( !filePointer )
- {
- DALI_LOG_ERROR( "Null file handle passed to ASTC compressed bitmap file loader.\n" );
- return false;
- }
-
- // Load the header info.
- AstcFileHeader fileHeader;
- unsigned int width, height;
-
- if( !LoadAstcHeader( filePointer, width, height, fileHeader ) )
- {
- DALI_LOG_ERROR( "Could not load ASTC Header from file.\n" );
- return false;
- }
-
- // Retrieve the pixel format from the ASTC block size.
- Pixel::Format pixelFormat = GetAstcPixelFormat( fileHeader );
- if( pixelFormat == Pixel::INVALID )
- {
- DALI_LOG_ERROR( "No internal pixel format supported for ASTC file pixel format.\n" );
- return false;
- }
-
- // Retrieve the file size.
- if( fseek( filePointer, 0L, SEEK_END ) )
- {
- DALI_LOG_ERROR( "Could not seek through file.\n" );
- return false;
- }
-
- off_t fileSize = ftell( filePointer );
- if( fileSize == -1L )
- {
- DALI_LOG_ERROR( "Could not determine ASTC file size.\n" );
- return false;
- }
-
- if( fseek( filePointer, sizeof( AstcFileHeader ), SEEK_SET ) )
- {
- DALI_LOG_ERROR( "Could not seek through file.\n" );
- return false;
- }
-
- // Data size is file size - header size.
- size_t imageByteCount = fileSize - sizeof( AstcFileHeader );
-
- // Sanity-check the image data is not too large and that it is at less than 2 bytes per texel:
- if( ( imageByteCount > MAX_IMAGE_DATA_SIZE ) || ( imageByteCount > ( ( static_cast< size_t >( width ) * height ) << 1 ) ) )
- {
- DALI_LOG_ERROR( "ASTC file has too large image-data field.\n" );
- return false;
- }
-
- // allocate pixel data
- bitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
-
- // Compressed format won't allocate the buffer
- auto pixels = bitmap.GetBuffer();
- if( !pixels )
- {
- // allocate buffer manually
- auto& impl = GetImplementation( bitmap );
- impl.AllocateFixedSize( imageByteCount );
- pixels = bitmap.GetBuffer();
- }
-
- // Load the image data.
- const size_t bytesRead = fread( pixels, 1, imageByteCount, filePointer );
-
- // Check the size of loaded data is what we expected.
- if( bytesRead != imageByteCount )
- {
- DALI_LOG_ERROR( "Read of image pixel data failed.\n" );
- return false;
- }
-
- return true;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Astc
-{
-const unsigned char MAGIC_BYTE_1 = 0x13;
-const unsigned char MAGIC_BYTE_2 = 0xAB;
-} // namespace Astc
-
-
-/**
- * Loads a compressed bitmap image from a ASTC file without decoding it.
- * This function checks the header first
- * and if it is not a ASTC file, or the header contents are invalid, it will return a failure.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return True if file loaded successfully, false otherwise
- */
-bool LoadBitmapFromAstc( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a ASTC file and fills in the width and height appropriately.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] width Is set with the width of the image
- * @param[out] height Is set with the height of the image
- * @return True if the header was read successfully, false otherwise
- */
-bool LoadAstcHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_ASTC_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "loader-bmp.h"
-
-#include <dali/public-api/common/vector-wrapper.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-const unsigned int FileHeaderOffsetOfBF32V4 = 0x7A;
-const unsigned int MaskForBFRGB565 = 0x80;
-const unsigned int FileHeaderOffsetOfRGB24V5 = 0x8A;
-
-enum BmpFormat
-{
- BMP_RGB1 = 14, //BI_RGB & bpp =1
- BMP_RGB4, //BI_RGB & bpp = 4
- BMP_RGB8, //BI_RGB & bpp = 8
- BMP_RGB555, //BI_RGB & bpp = 16
- BMP_BITFIELDS555, //BI_BITFIELDS & 16bit & R:G:B = 5:5:5
- BMP_BITFIELDS32, //BI_BITFIELDS & 32bit & R:G:B:A = 8:8:8:8
- BMP_RLE8, //BI_RLE8
- BMP_RLE4, //BI_RLE4
- BMP_BITFIELDS32V4,//BI_BITFIELDS & 32bit
- BMP_RGB24V5, //BI_RGB & bpp = 24 & bmp version5
- BMP_NOTEXIST
-};
-
-struct BmpFileHeader
-{
- unsigned short signature; // Bitmap file signature
- unsigned int fileSize; // Bitmap file size in bytes
- unsigned short reserved1; // Reserved bits
- unsigned short reserved2; // Reserved bits
- unsigned int offset; // Offset from BMP file header to BMP bits
-} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes
-
-struct BmpInfoHeader
-{
- unsigned int infoHeaderSize; // Specifies the number of bytes required by the info header
- unsigned int width; // The Image Width
- int height; // The Image Height (negative value represents image data is flipped)
- unsigned short planes; // The number of color planes, must be 1
- unsigned short bitsPerPixel; // The bits per pixel
- unsigned int compression; // The type of compression used by the image
- unsigned int imageSize; // The size of the image in bytes
- unsigned int xPixelsPerMeter; // The number of pixels per meter in x axis
- unsigned int yPixelsPerMeter; // The number of pixels per meter in y axis
- unsigned int numberOfColors; // The number of colors in the color table
- unsigned int importantColors; // The important color count
-} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes
-
-/**
- * Template function to read from the file directly into our structure.
- * @param[in] fp The file to read from
- * @param[out] header The structure we want to store our information in
- * @return true, if read successful, false otherwise
- */
-template<typename T>
-inline bool ReadHeader(FILE* fp, T& header)
-{
- const unsigned int readLength = sizeof(T);
-
- // Load the information directly into our structure
- if ( fread( &header, 1, readLength, fp ) != readLength )
- {
- return false;
- }
-
- return true;
-}
-
-bool LoadBmpHeader(FILE *fp, unsigned int &width, unsigned int &height, BmpFileHeader &fileHeader, BmpInfoHeader &infoHeader)
-{
- if (!ReadHeader(fp, fileHeader))
- {
- return false;
- }
-
- if (!ReadHeader(fp, infoHeader))
- {
- return false;
- }
-
- width = infoHeader.width;
- height = abs(infoHeader.height);
-
- if( infoHeader.width == 0 )
- {
- return false;
- }
-
- return true;
-}
-
-/**
- * function to decode format BI_RGB & bpp = 24 & bmp version5.
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @param[in] padding padded to a u_int32 boundary for each line
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRGB24V5(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown,
- unsigned int rowStride,
- unsigned int padding)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RGB24V5 format\n");
- return false;
- }
- if ( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RGB24V5 data\n");
- return false;
- }
-
- for(unsigned int yPos = 0; yPos < height; yPos ++)
- {
- unsigned char* pixelsPtr = NULL;
- if(topDown)
- {
- pixelsPtr = pixels + ( yPos * rowStride);
- }
- else
- {
- pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
- }
- if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- for(unsigned int i = 0; i < rowStride; i += 3)
- {
- unsigned char temp = pixelsPtr[i];
- pixelsPtr[i] = pixelsPtr[i + 2];
- pixelsPtr[i + 2] = temp;
- }
-
- if (padding)
- {
- // move past the padding.
- if( fseek(fp, padding, SEEK_CUR) )
- {
- DALI_LOG_ERROR("Error moving past BMP_RGB24V5 padding\n");
- }
- }
- }
- return true;
-}
-
-/**
- * function to decode format BI_BITFIELDS & bpp = 32 & bmp version4.
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @param[in] rowStride bits span for each line
- * @param[in] padding padded to a u_int32 boundary for each line
- * @return true, if decode successful, false otherwise
- */
-bool DecodeBF32V4(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown,
- unsigned int rowStride,
- unsigned int padding)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32V4 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32V4 data\n");
- return false;
- }
-
- for(unsigned int yPos = 0; yPos < height; yPos ++)
- {
- unsigned char* pixelsPtr = NULL;
- if(topDown)
- {
- pixelsPtr = pixels + ( yPos * rowStride);
- }
- else
- {
- pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
- }
- if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- for(unsigned int i = 0; i < rowStride; i += 4)
- {
- unsigned char temp = pixelsPtr[i];
- pixelsPtr[i] = pixelsPtr[i + 2];
- pixelsPtr[i + 2] = temp;
- }
- if (padding)
- {
- // move past the padding.
- if( fseek(fp, padding, SEEK_CUR) )
- {
- DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32V4 padding\n");
- }
- }
-
- }
- return true;
-}
-
-/**
- * function to decode format BI_BITFIELDS & bpp = 32
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @param[in] rowStride bits span for each line
- * @param[in] padding padded to a u_int32 boundary for each line
- * @return true, if decode successful, false otherwise
- */
-bool DecodeBF32(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown,
- unsigned int rowStride,
- unsigned int padding)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32 data\n");
- return false;
- }
-
- for (unsigned int yPos = 0; yPos < height; yPos++)
- {
- unsigned char* pixelsPtr;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( yPos * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
- }
-
- if (fread(pixelsPtr, 1, rowStride, fp) != rowStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- for(unsigned int i = 0; i < rowStride; i += 4)
- {
- unsigned char temp = pixelsPtr[i];
- pixelsPtr[i] = pixelsPtr[i + 2];
- pixelsPtr[i + 2] = temp;
- }
-
- if (padding)
- {
- // move past the padding.
- if( fseek(fp, padding, SEEK_CUR) )
- {
- DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32 padding\n");
- }
- }
- }
- return true;
-}
-
-/**
- * function to decode format BI_BITFIELDS & bpp = 16 & R:G:B = 5:6:5
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeBF565(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding RGB565 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking RGB565 data\n");
- return false;
- }
-
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- unsigned int rowStride = width * 2;
-
- for(unsigned int i = 0; i < height; i++)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( i * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height - 1) - i) * rowStride);
- }
- if(fread(pixelsPtr, 1, rowStride, fp) != rowStride)
- {
- return false;
- }
- }
-
- return true;
-}
-
-/**
- * function to decode format BI_BITFIELDS & bpp = 16 & R:G:B = 5:5:5
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeBF555(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_BITFIELDS555 format\n");
- return false;
- }
-
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_BITFIELDS555 data\n");
- return false;
- }
-
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
-
- std::vector<char> raw(width * height * 2);
- unsigned int rawStride = width * 2;
- unsigned int rowStride = width * 3;
-
- char *rawPtr = NULL;
- for(unsigned int j = 0; j < height; j ++)
- {
- rawPtr = &raw[0] + ( j * rawStride);
- if(fread(rawPtr, 1, rawStride, fp) != rawStride)
- {
- return false;
- }
- }
-
- for (unsigned int yPos = 0; yPos < height; yPos++)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( yPos * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height-1)-yPos) * rowStride);
- }
-
- for(unsigned int k = 0; k < width; k ++)
- {
- int index = yPos * rawStride + 2 * k;
- pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F;
- pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F;
- pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F;
- }
- }
- return true;
-}
-
-/**
- * function to decode format BI_RGB & bpp = 16 & R:G:B = 5:5:5
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp image data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRGB555(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RGB555 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RGB555 data\n");
- return false;
- }
-
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- std::vector<char> raw(width * height * 2);
- unsigned int rawStride = width * 2;
- unsigned int rowStride = width * 3;
-
- char *rawPtr = NULL;
- for(unsigned int j = 0; j < height; j ++)
- {
- rawPtr = &raw[0] + ( j * rawStride);
- if(fread(rawPtr, 1, rawStride, fp) != rawStride)
- {
- return false;
- }
- }
- for(unsigned int i = 0; i < height; i++)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( i * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height - 1) - i) * rowStride);
- }
- for(unsigned int k = 0; k < width; k ++)
- {
- int index = i * rawStride + 2 * k;
- pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F;
- pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F;
- pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F;
- }
-
- }
- return true;
-}
-
-/**
- * function to decode format BI_RGB & bpp = 1
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp palette data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRGB1(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RGB1 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RGB1 data\n");
- return false;
- }
-
- unsigned char colorTable[8] = {0};
- char cmd;
- unsigned int fillw = ((width & 63) != 0) ? width + 64 - (width & 63) : width;
- std::vector<char> colorIndex(fillw * height);
- unsigned int rowStride = fillw * 3; // RGB
-
-
- if(fread(colorTable, 1, 8, fp) != 8)
- {
- return false;
- }
-
- for(unsigned int i = 0; i < fillw * height; i += 8)
- {
- if(fread(&cmd, 1, 1, fp) != 1)
- {
- return false;
- }
-
- colorIndex[i] = (cmd >> 7) & 0x01;
- colorIndex[i + 1] = (cmd >> 6) & 0x01;
- colorIndex[i + 2] = (cmd >> 5) & 0x01;
- colorIndex[i + 3] = (cmd >> 4) & 0x01;
- colorIndex[i + 4] = (cmd >> 3) & 0x01;
- colorIndex[i + 5] = (cmd >> 2) & 0x01;
- colorIndex[i + 6] = (cmd >> 1) & 0x01;
- colorIndex[i + 7] = (cmd & 0x01);
- }
-
- for(unsigned int index = 0; index < height; index = index + 1)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( index * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height - 1) - index) * rowStride);
- }
- for(unsigned int j = 0; j < fillw; j ++)
- {
- unsigned int ctIndex = 0;
- if((fillw * index + j ) < (fillw * height))
- {
- ctIndex = colorIndex[ fillw * index + j ];
- }
- else
- {
- break;
- }
- // temp solution for PLM bug P130411-5268, there is one mono bmp that cause DecodeRGB1 API crash.
- if( ((3 * j + 2) < height * fillw * 3) && (ctIndex < 2))
- {
- pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
- pixelsPtr[3 * j + 1] = colorTable[4 * ctIndex + 1];
- pixelsPtr[3 * j + 2] = colorTable[4 * ctIndex ];
- }
- }
- }
- return true;
-}
-
-/**
- * function to decode format BI_RGB & bpp = 4
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp palette data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRGB4(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RGB4 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RGB4 data\n");
- return false;
- }
-
- char colorTable[64];
- char cmd;
- unsigned int fillw = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- std::vector<char> colorIndex(fillw * height);
- unsigned int rowStride = fillw * 3;
-
- if(fread(colorTable, 1, 64, fp) != 64)
- {
- return false;
- }
-
- for(unsigned int i = 0; i < fillw * height; i += 2)
- {
- if (fread(&cmd, 1, 1, fp) != 1)
- {
- return false;
- }
-
- colorIndex[i] = cmd >> 4;
- colorIndex[i + 1] = cmd & (0x0F);
- }
- unsigned int ctIndex = 0;
-
- for(unsigned int index = 0; index < height; index = index + 1)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( index * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height - 1) - index) * rowStride);
- }
- for(unsigned int j = 0; j < fillw; j ++)
- {
- ctIndex = colorIndex[ fillw * index + j ];
- pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
- pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1];
- pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ];
- }
- }
-
- return true;
-}
-
-/**
- * function to decode format BI_RGB & bpp = 8
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp palette data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRGB8(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RGB8 format\n");
- return false;
- }
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RGB8 data\n");
- return false;
- }
-
- std::vector<char> colorTable(1024);
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- char cmd;
- std::vector<char> colorIndex(width * height);
- unsigned int rowStride = width * 3;//RGB8->RGB24
-
- if(fread(&colorTable[0], 1, 1024, fp) != 1024)
- {
- return false;
- }
- for(unsigned int i = 0; i < width * height; i ++)
- {
- if (fread(&cmd, 1, 1, fp) != 1)
- {
- return false;
- }
-
- colorIndex[i] = cmd;
- }
- unsigned int ctIndex = 0;
- for(unsigned int index = 0; index < height; index = index + 1)
- {
- unsigned char* pixelsPtr = NULL;
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsPtr = pixels + ( index * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsPtr = pixels + (((height - 1) - index) * rowStride);
- }
- for(unsigned int j = 0; j < width; j ++)
- {
- ctIndex = colorIndex[ width * index + j ];
- pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2];
- pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1];
- pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ];
- }
- }
- return true;
-}
-
-/**
- * function to decode format BI_RLE4 & bpp = 4
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp palette data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRLE4(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RLE4 format\n");
- return false;
- }
- unsigned char* pixelsPtr = pixels;
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- char cmd[2];
- unsigned int cmdStride = 2;
- char colorTable[64];
- std::vector<char> colorIndex(width * height >> 1);
- std::vector<char> run;
- unsigned int x = 0;
- unsigned int y = 0;
- unsigned int dx = 0;
- unsigned int dy = 0;
- width += (width & 1);
- width = width >> 1;
-
- bool finish = false;
-
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RLE4 data\n");
- return false;
- }
-
- if (fread(colorTable, 1, 64, fp) != 64)
- {
- return false;
- }
-
- while((x >> 1) + y * width < width * height)
- {
- if (finish)
- {
- break;
- }
- if (fread(cmd, 1, cmdStride, fp) != cmdStride)
- {
- return false;
- }
- if(cmd[0] == 0) // ESCAPE
- {
- switch(cmd[1])
- {
- case 1: //end of bitmap
- finish = true;
- break;
- case 0: // end of line
- x = 0;
- y ++;
- break;
- case 2: // delta
- if (fread(cmd, 1, cmdStride, fp) != cmdStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- dx = cmd[0] & (0xFF);
- dy = cmd[1] & (0xFF);
- x += dx;
- y += dy;
- break;
- default:
- // decode a literal run
- unsigned int length = cmd[1] & (0xFF);
- //size of run, which is word aligned
- unsigned int bytesize = length;
- bytesize += (bytesize & 1);
- bytesize >>= 1;
- bytesize += (bytesize & 1);
- run.resize(bytesize);
- if(fread(&run[0], 1, bytesize, fp) != bytesize)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- if((x & 1) == 0)
- {
- length += (length & 1);
- length >>= 1;
- for(unsigned int i = 0; i < length; i += 1)
- {
- colorIndex[(x >> 1) + width * (height - y - 1) + i] = run[i];
- }
- }
- else
- {
- for(unsigned int i = 0; i < length; i ++)
- {
- if((i & 1) == 0)//copy high to low
- {
- colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((run[i >> 1] & 0xF0) >> 4);
- }
- else //copy low to high
- {
- colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((run[i >> 1] & 0x0F) << 4);
- }
- }
- }
- x += cmd[1] & (0xFF);
- break;
- }
- }
- else
- {
- unsigned int length = cmd[0] & (0xFF);
- if((x & 1) == 0)
- {
- length += (length & 1);
- length >>= 1;
- for(unsigned int i = 0; i < length; i ++)
- {
- colorIndex[(height-y-1)*width + i + (x >> 1)] = cmd[1];
- }
- }
- else
- {
- for(unsigned int i = 0; i < length; i ++)
- {
- if((i & 1) == 0)
- {
- colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((cmd[1] & 0xF0) >> 4);
- }
- else
- {
- colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((cmd[1] & 0x0F) << 4);
- }
- }
- }
- x += cmd[0] & (0xFF);
- }
- }
-
- int ctIndexHigh = 0;
- int ctIndexLow = 0;
- for(unsigned int index = 0; index < (width * height ); index = index + 1)
- {
- ctIndexHigh = colorIndex[ index] >> 4;
- ctIndexLow = colorIndex[index] & (0x0F);
- pixelsPtr[6 * index ] = colorTable[4 * ctIndexHigh + 2];
- pixelsPtr[6 * index + 1] = colorTable[4 * ctIndexHigh + 1];
- pixelsPtr[6 * index + 2] = colorTable[4 * ctIndexHigh ];
- pixelsPtr[6 * index + 3] = colorTable[4 * ctIndexLow + 2];
- pixelsPtr[6 * index + 4] = colorTable[4 * ctIndexLow + 1];
- pixelsPtr[6 * index + 5] = colorTable[4 * ctIndexLow ];
- }
- return true;
-}
-
-/**
- * function to decode format BI_RLE8 & bpp = 8
- * @param[in] fp The file to read from
- * @param[out] pixels The pointer that we want to store bmp data in
- * @param[in] width bmp width
- * @param[in] height bmp height
- * @param[in] offset offset from bmp header to bmp palette data
- * @param[in] topDown indicate image data is read from bottom or from top
- * @return true, if decode successful, false otherwise
- */
-bool DecodeRLE8(FILE *fp,
- unsigned char* pixels,
- unsigned int width,
- unsigned int height,
- unsigned int offset,
- bool topDown)
-{
- if(fp == NULL || pixels == NULL)
- {
- DALI_LOG_ERROR("Error decoding BMP_RLE8 format\n");
- return false;
- }
- unsigned char* pixelsPtr = pixels;
- unsigned int x = 0;
- unsigned int y = 0;
- unsigned int cmdStride = 2;
-
- width = ((width & 3) != 0) ? width + 4 - (width & 3) : width;
- std::vector<char> colorTable(1024);
- char cmd[2];
- std::vector<char> colorIndex(width * height);
-
- if( fseek(fp, offset, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking BMP_RLE8 data\n");
- return false;
- }
-
- if (fread(&colorTable[0], 1, 1024, fp) != 1024)
- {
- return false;
- }
-
- unsigned int dx = 0;
- unsigned int dy = 0;
- bool finish = false;
- unsigned int length = 0;
- unsigned int copylength = 0;
- std::vector<char> run;
- while((x + y * width) < width * height )
- {
- if (finish)
- {
- break;
- }
- if (fread(cmd, 1, cmdStride, fp) != cmdStride)
- {
- return false;
- }
-
- if(cmd[0] == 0)//ESCAPE
- {
- switch(cmd[1])
- {
- case 1: // end of bitmap
- finish = true;
- break;
- case 0: // end of line
- x = 0;
- y ++;
- break;
- case 2: // delta
- if (fread(cmd, 1, cmdStride, fp) != cmdStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
- dx = cmd[0] & (0xFF);
- dy = cmd[1] & (0xFF);
- x += dx;
- y += dy;
- break;
- default:
- //decode a literal run
- length = cmd[1] & (0xFF);
- copylength = length;
- //absolute mode must be word-aligned
- length += (length & 1);
- run.resize(length);
- if(fread(&run[0], 1, length, fp) != length)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- return false;
- }
-
- for(unsigned int i = 0; i < length; i += 1)
- {
- colorIndex[x + width * (height - y - 1) + i] = run[i];
- }
- x += copylength;
- break;
- }
- }// end if cmd[0] ==
- else
- {
- length = cmd[0] & (0xFF);
- for(unsigned int i = 0; i < length; i ++)
- {
- colorIndex[(height - y - 1) * width + x] = cmd[1];
- x++;
- }
- }
- }
- int ctIndex = 0;
- for(unsigned int index = 0; index < width * height; index = index + 1)
- {
- ctIndex = colorIndex[ index];
- pixelsPtr[3 * index ] = colorTable[4 * ctIndex + 2];
- pixelsPtr[3 * index + 1] = colorTable[4 * ctIndex + 1];
- pixelsPtr[3 * index + 2] = colorTable[4 * ctIndex ];
- }
- return true;
-}
-
-} // unnamed namespace
-
-bool LoadBmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- BmpFileHeader fileHeader;
- BmpInfoHeader infoHeader;
-
- bool ret = LoadBmpHeader( input.file, width, height, fileHeader, infoHeader );
-
- return ret;
-}
-
-bool LoadBitmapFromBmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- //DALI_ASSERT_DEBUG( bitmap.GetPackedPixelsProfile() != 0 && "Need a packed pixel bitmap to load into." );
- FILE* const fp = input.file;
- if(fp == NULL)
- {
- DALI_LOG_ERROR("Error loading bitmap\n");
- return false;
- }
- BmpFormat customizedFormat = BMP_NOTEXIST;
- BmpFileHeader fileHeader;
- BmpInfoHeader infoHeader;
-
- // Load the header info
- unsigned int width, height;
-
- if (!LoadBmpHeader(fp, width, height, fileHeader, infoHeader))
- {
- return false;
- }
-
- Pixel::Format pixelFormat = Pixel::RGB888;
- switch(infoHeader.compression)
- {
- case 0:
- switch (infoHeader.bitsPerPixel)
- {
- case 32:
- pixelFormat = Pixel::BGR8888;
- break;
-
- case 24:
- if(fileHeader.offset == FileHeaderOffsetOfRGB24V5)//0x8A
- {
- customizedFormat = BMP_RGB24V5;
- }
- else
- {
- pixelFormat = Pixel::RGB888;
- }
- break;
-
- case 16:
- customizedFormat = BMP_RGB555;
- break;
-
- case 8:
- customizedFormat = BMP_RGB8;
- break;
-
- case 4: // RGB4
- customizedFormat = BMP_RGB4;
- break;
-
- case 1: //RGB1
- customizedFormat = BMP_RGB1;
- break;
- default:
- DALI_LOG_WARNING("%d bits per pixel not supported for BMP files\n", infoHeader.bitsPerPixel);
- return false;
- }
- break;
- case 1: //// RLE8
- {
- if(infoHeader.bitsPerPixel == 8)
- {
- customizedFormat = BMP_RLE8;
- }
- break;
- }
- case 2: // RLE4
- {
- if(infoHeader.bitsPerPixel == 4)
- {
- customizedFormat = BMP_RLE4;
- }
- break;
- }
- case 3: // // BI_BITFIELDS
- {
- if(infoHeader.bitsPerPixel == 16)
- {
- if( fseek(fp, 14 + infoHeader.infoHeaderSize + 1, SEEK_SET) )
- {
- return false;
- }
-
- char mask;
- if(fread(&mask, 1, 1, fp) != 1)
- {
- return false;
- }
-
- if((mask & 0x80) == MaskForBFRGB565) // mask is 0xF8
- {
- pixelFormat = Pixel::RGB565;
- }
- else if((mask & 0x80) == 0)// mask is 0x 7C
- {
- customizedFormat = BMP_BITFIELDS555;
- }
- else
- {
- return false;
- }
- }
- else if(infoHeader.bitsPerPixel == 32)
- {
- if(fileHeader.offset == FileHeaderOffsetOfBF32V4)// 0x7A
- {
- customizedFormat = BMP_BITFIELDS32V4;
- }
- else
- {
- customizedFormat = BMP_BITFIELDS32;
- }
- }
- break;
- }
- default:
- DALI_LOG_WARNING("Compression not supported for BMP files\n");
- return false;
- }
-
- bool topDown = false;
-
- // if height is negative, bitmap data is top down
- if (infoHeader.height<0)
- {
- infoHeader.height = abs(infoHeader.height);
- height = infoHeader.height;
- topDown = true;
- }
-
- unsigned int rowStride = infoHeader.width * (infoHeader.bitsPerPixel >>3);
-
- // bitmaps row stride is padded to 4 bytes
- unsigned int padding = (rowStride % 4);
- if (padding)
- {
- padding = 4 - padding;
- }
-
- int imageW = infoHeader.width;
- int pixelBufferW = infoHeader.width;
- int pixelBufferH = infoHeader.height;
- auto newPixelFormat = Pixel::Format::INVALID;
-
- switch(customizedFormat)
- {
- case BMP_RLE8:
- case BMP_RGB8:
- case BMP_RGB4:
- case BMP_RLE4:
- case BMP_RGB555:
- case BMP_BITFIELDS555:
- {
- pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW;
- pixelBufferH = abs(infoHeader.height);
- newPixelFormat = Pixel::RGB888;
- break;
- }
- case BMP_RGB1:
- {
- pixelBufferW = ((imageW & 63) != 0) ? imageW + 64 - (imageW & 63) : imageW;
- pixelBufferH = abs(infoHeader.height);
- newPixelFormat = Pixel::RGB888;
- break;
- }
- case BMP_BITFIELDS32:
- case BMP_BITFIELDS32V4:
- {
- pixelBufferH = abs(infoHeader.height);
- newPixelFormat = Pixel::RGB8888;
- break;
- }
- case BMP_RGB24V5:
- {
- newPixelFormat = Pixel::RGB888;
- break;
- }
- default:
- if(pixelFormat == Pixel::RGB565 )
- {
- pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW;
- pixelBufferH = abs(infoHeader.height);
- newPixelFormat = Pixel::RGB565;
- }
- else
- {
- pixelBufferW = infoHeader.width;
- pixelBufferH = infoHeader.height;
- newPixelFormat = pixelFormat;
- }
- break;
- }
-
- bitmap = Dali::Devel::PixelBuffer::New(pixelBufferW, pixelBufferH, newPixelFormat);
- auto pixels = bitmap.GetBuffer();
-
- // Read the raw bitmap data
- decltype(pixels) pixelsIterator = nullptr;
-
- bool decodeResult(false);
- switch(customizedFormat)
- {
- case BMP_RGB1:
- {
- decodeResult = DecodeRGB1( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
- break;
- }
- case BMP_RGB4:
- {
- decodeResult = DecodeRGB4(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
- break;
- }
- case BMP_RLE4:
- {
- decodeResult = DecodeRLE4( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
- break;
- }
- case BMP_BITFIELDS32:
- {
- decodeResult = DecodeBF32(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
- break;
- }
- case BMP_BITFIELDS555:
- {
- decodeResult = DecodeBF555(fp, pixels,infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
- break;
- }
- case BMP_RGB555:
- {
- decodeResult = DecodeRGB555(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
- break;
- }
- case BMP_RGB8:
- {
- decodeResult = DecodeRGB8(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
- break;
- }
- case BMP_RLE8:
- {
- decodeResult = DecodeRLE8(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown);
- break;
- }
- case BMP_RGB24V5:
- {
- decodeResult = DecodeRGB24V5(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
- break;
- }
- case BMP_BITFIELDS32V4:
- {
- decodeResult = DecodeBF32V4(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding);
- break;
- }
- default:
- {
- if(pixelFormat == Pixel::RGB565)
- {
- decodeResult = DecodeBF565(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown);
- }
- else
- {
- for (unsigned int yPos = 0; yPos < height; yPos++)
- {
- if (topDown)
- {
- // the data in the file is top down, and we store the data top down
- pixelsIterator = pixels + ( yPos * rowStride);
- }
- else
- {
- // the data in the file is bottom up, and we store the data top down
- pixelsIterator = pixels + (((height-1)-yPos) * rowStride);
- }
-
- if (fread(pixelsIterator, 1, rowStride, fp) != rowStride)
- {
- DALI_LOG_ERROR("Error reading the BMP image\n");
- break;
- }
-
- // If 24 bit mode then swap Blue and Red pixels
- // BGR888 doesn't seem to be supported by dali-core
- if (infoHeader.bitsPerPixel == 24 )
- {
- for(unsigned int i = 0; i < rowStride; i += 3)
- {
- unsigned char temp = pixelsIterator[i];
- pixelsIterator[i] = pixelsIterator[i+2];
- pixelsIterator[i+2] = temp;
- }
- }
-
- if (padding)
- {
- if( fseek(fp, padding, SEEK_CUR) ) // move past the padding.
- {
- DALI_LOG_ERROR("Error moving past BMP padding\n");
- }
- }
- }
- decodeResult = true;
- }
- break;
- }
- } // switch
-
- if( !decodeResult )
- {
- return false;
- }
-
- return true;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Bmp
-{
-const unsigned char MAGIC_BYTE_1 = 0x42;
-const unsigned char MAGIC_BYTE_2 = 0x4D;
-} // namespace Bmp
-
-/**
- * Loads the bitmap from an BMP file. This function checks the header first
- * and if it is not a BMP file, then it returns straight away.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromBmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a BMP file and fills in the width and height appropriately.
- * @param[in] fp Pointer to the Image file
- * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
- * @param[out] width Is set with the width of the image
- * @param[out] height Is set with the height of the image
- * @return true if the file's header was read successully, false otherwise
- */
-bool LoadBmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_BMP_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "loader-gif.h"
-
-#include <gif_lib.h>
-
-#include <dali/integration-api/debug.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#include <memory>
-
-// We need to check if giflib has the new open and close API (including error parameter).
-#ifdef GIFLIB_MAJOR
-#define LIBGIF_VERSION_5_1_OR_ABOVE
-#endif
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-
-// simple class to enforce clean-up of GIF structures
-struct AutoCleanupGif
-{
- AutoCleanupGif(GifFileType*& _gifInfo)
- : gifInfo(_gifInfo)
- {
- }
-
- ~AutoCleanupGif()
- {
- if(NULL != gifInfo)
- {
- // clean up GIF resources
-#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
- int errorCode = 0; //D_GIF_SUCCEEDED is 0
- DGifCloseFile( gifInfo, &errorCode );
-
- if( errorCode )
- {
- DALI_LOG_ERROR( "GIF Loader: DGifCloseFile Error. Code: %d\n", errorCode );
- }
-#else
- DGifCloseFile( gifInfo );
-#endif
- }
- }
-
- GifFileType*& gifInfo;
-};
-
-// Used in the GIF interlace algorithm to determine the starting byte and the increment required
-// for each pass.
-struct InterlacePair
-{
- unsigned int startingByte;
- unsigned int incrementalByte;
-};
-
-// Used in the GIF interlace algorithm to determine the order and which location to read data from
-// the file.
-const InterlacePair INTERLACE_PAIR_TABLE [] = {
- { 0, 8 }, // Starting at 0, read every 8 bytes.
- { 4, 8 }, // Starting at 4, read every 8 bytes.
- { 2, 4 }, // Starting at 2, read every 4 bytes.
- { 1, 2 }, // Starting at 1, read every 2 bytes.
-};
-const unsigned int INTERLACE_PAIR_TABLE_SIZE( sizeof( INTERLACE_PAIR_TABLE ) / sizeof( InterlacePair ) );
-
-/// Function used by Gif_Lib to read from the image file.
-int ReadDataFromGif(GifFileType *gifInfo, GifByteType *data, int length)
-{
- FILE *fp = reinterpret_cast<FILE*>(gifInfo->UserData);
- return fread( data, sizeof( GifByteType ), length, fp);
-}
-
-/// Loads the GIF Header.
-bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileType** gifInfo)
-{
- int errorCode = 0; //D_GIF_SUCCEEDED is 0
-
-#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
- *gifInfo = DGifOpen( reinterpret_cast<void*>(fp), ReadDataFromGif, &errorCode );
-#else
- *gifInfo = DGifOpen( reinterpret_cast<void*>(fp), ReadDataFromGif );
-#endif
-
- if ( !(*gifInfo) || errorCode )
- {
- DALI_LOG_ERROR( "GIF Loader: DGifOpen Error. Code: %d\n", errorCode );
- return false;
- }
-
- width = (*gifInfo)->SWidth;
- height = (*gifInfo)->SHeight;
-
- // No proper size in GIF.
- if ( width <= 0 || height <= 0 )
- {
- return false;
- }
-
- return true;
-}
-
-/// Decode the GIF image.
-bool DecodeImage( GifFileType* gifInfo, unsigned char* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow )
-{
- if ( gifInfo->Image.Interlace )
- {
- // If the image is interlaced, then use the GIF interlace algorithm to read the file appropriately.
-
- const InterlacePair* interlacePairPtr( INTERLACE_PAIR_TABLE );
- for ( unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr )
- {
- for( unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte )
- {
- unsigned char* row = decodedData + currentByte * bytesPerRow;
- if ( DGifGetLine( gifInfo, row, width ) == GIF_ERROR )
- {
- DALI_LOG_ERROR( "GIF Loader: Error reading Interlaced GIF\n" );
- return false;
- }
- }
- }
- }
- else
- {
- // Non-interlace does not require any erratic reading / jumping.
- unsigned char* decodedDataPtr( decodedData );
-
- for ( unsigned int row = 0; row < height; ++row )
- {
- if ( DGifGetLine( gifInfo, decodedDataPtr, width ) == GIF_ERROR)
- {
- DALI_LOG_ERROR( "GIF Loader: Error reading non-interlaced GIF\n" );
- return false;
- }
- decodedDataPtr += bytesPerRow;
- }
- }
- return true;
-}
-
-// Retrieves the colors used in the GIF image.
-GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo )
-{
- GifColorType* color( NULL );
- if ( image->ImageDesc.ColorMap )
- {
- color = image->ImageDesc.ColorMap->Colors;
- }
- else
- {
- // if there is no color map for this image use the default one
- color = gifInfo->SColorMap->Colors;
- }
- return color;
-}
-
-/// Called when we want to handle IMAGE_DESC_RECORD_TYPE
-bool HandleImageDescriptionRecordType( Dali::Devel::PixelBuffer& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished )
-{
- if ( DGifGetImageDesc( gifInfo ) == GIF_ERROR )
- {
- DALI_LOG_ERROR( "GIF Loader: Error getting Image Description\n" );
- return false;
- }
-
- // Ensure there is at least 1 image in the GIF.
- if ( gifInfo->ImageCount < 1 )
- {
- DALI_LOG_ERROR( "GIF Loader: No Images\n" );
- return false;
- }
-
- Pixel::Format pixelFormat( Pixel::RGB888 );
-
- SavedImage* image( &gifInfo->SavedImages[ gifInfo->ImageCount - 1 ] );
- const GifImageDesc& desc( image->ImageDesc );
-
- auto decodedData = new unsigned char[ width * height * sizeof( GifPixelType ) ];
-
- std::unique_ptr<unsigned char[]> ptr{ decodedData };
-
- const unsigned int bytesPerRow( width * sizeof( GifPixelType ) );
- const unsigned int actualWidth( desc.Width );
- const unsigned int actualHeight( desc.Height );
-
- // Create a buffer to store the decoded data.
- bitmap = Dali::Devel::PixelBuffer::New( actualWidth, actualHeight, pixelFormat );
-
- // Decode the GIF Image
- if ( !DecodeImage( gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow ) )
- {
- return false;
- }
-
- // Get the colormap for the GIF
- GifColorType* color( GetImageColors( image, gifInfo ) );
-
- // If it's an animated GIF, we still only read the first image
-
- // Create and populate pixel buffer.
- auto pixels = bitmap.GetBuffer();
- for (unsigned int row = 0; row < actualHeight; ++row)
- {
- for (unsigned int column = 0; column < actualWidth; ++column)
- {
- unsigned char index = decodedData[row * width + column];
-
- pixels[0] = color[index].Red;
- pixels[1] = color[index].Green;
- pixels[2] = color[index].Blue;
- pixels += 3;
- }
- }
- finished = true;
- return true;
-}
-
-/// Called when we want to handle EXTENSION_RECORD_TYPE
-bool HandleExtensionRecordType( GifFileType* gifInfo )
-{
- SavedImage image;
- GifByteType *extensionByte( NULL );
-
-#ifdef LIBGIF_VERSION_5_1_OR_ABOVE
- ExtensionBlock extensionBlocks;
- image.ExtensionBlocks = &extensionBlocks;
- image.ExtensionBlockCount = 1;
- int *extensionBlockTypePointer = &image.ExtensionBlocks->Function;
-#else
- image.ExtensionBlocks = NULL;
- image.ExtensionBlockCount = 0;
- int *extensionBlockTypePointer = &image.Function;
-#endif
-
- // Not really interested in the extensions so just skip them unless there is an error.
- for ( int extRetCode = DGifGetExtension( gifInfo, extensionBlockTypePointer, &extensionByte );
- extensionByte != NULL;
- extRetCode = DGifGetExtensionNext( gifInfo, &extensionByte ) )
- {
- if ( extRetCode == GIF_ERROR )
- {
- DALI_LOG_ERROR( "GIF Loader: Error reading GIF Extension record.\n" );
- return false;
- }
- }
-
- return true;
-}
-
-} // unnamed namespace
-
-bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- GifFileType* gifInfo = NULL;
- AutoCleanupGif autoCleanupGif(gifInfo);
- FILE* const fp = input.file;
-
- return LoadGifHeader(fp, width, height, &gifInfo);
-}
-
-bool LoadBitmapFromGif( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- FILE* const fp = input.file;
- // Load the GIF Header file.
-
- GifFileType* gifInfo( NULL );
- unsigned int width( 0 );
- unsigned int height( 0 );
- if ( !LoadGifHeader( fp, width, height, &gifInfo ) )
- {
- return false;
- }
- AutoCleanupGif autoGif( gifInfo );
-
- // Check each record in the GIF file.
-
- bool finished( false );
- GifRecordType recordType( UNDEFINED_RECORD_TYPE );
- for ( int returnCode = DGifGetRecordType( gifInfo, &recordType );
- !finished && recordType != TERMINATE_RECORD_TYPE;
- returnCode = DGifGetRecordType( gifInfo, &recordType ) )
- {
- if ( returnCode == GIF_ERROR )
- {
- DALI_LOG_ERROR( "GIF Loader: Error getting Record Type\n" );
- return false;
- }
-
- if( IMAGE_DESC_RECORD_TYPE == recordType )
- {
- if ( !HandleImageDescriptionRecordType( bitmap, gifInfo, width, height, finished ) )
- {
- return false;
- }
- }
- else if ( EXTENSION_RECORD_TYPE == recordType )
- {
- if ( !HandleExtensionRecordType( gifInfo ))
- {
- return false;
- }
- }
- }
-
- return true;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Gif
-{
-const unsigned char MAGIC_BYTE_1 = 0x47;
-const unsigned char MAGIC_BYTE_2 = 0x49;
-} // namespace Gif
-
-/**
- * Loads the bitmap from a GIF file. This function checks the header first
- * and if it is not a GIF file, then it returns straight away.
- * @note For animated GIFs, only the first image is displayed
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromGif( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a GIF file and fills in the width and height appropriately.
- * @param[in] fp Pointer to the Image file
- * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
- * @param[in/out] width Is set with the width of the image
- * @param[in/out] height Is set with the height of the image
- * @return true if the file's header was read successully, false otherwise
- */
-bool LoadGifHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_GIF_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Derived from Enlightenment file evas_image_load_ico.c[1] which is licensed
- * under the BSD 2-clause license[2] reproduced below.
- *
- * [1][http://web.archive.org/web/20141201151111/http://git.enlightenment.org/core/efl.git/tree/src/modules/evas/loaders/ico/evas_image_load_ico.c]
- * [2][http://web.archive.org/web/20140717012400/https://git.enlightenment.org/core/efl.git/about/]
- *
- * Copyright (C) 2002-2012 Carsten Haitzler, Dan Sinclair, Mike Blumenkrantz,
- * Samsung Electronics and various contributors (see AUTHORS)
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// HEADER
-#include "loader-ico.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/public-api/common/dali-vector.h>
-
-// INTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-// Reserved 2 bytes + type 2 bytes + count 2 bytes + count * 16 bytes
-const unsigned char ICO_FILE_HEADER = 22;
-// Info header 40 bytes = size 4 bytes + width 4 bytes + height 4 bytes + planes 2 bytes + bitcount 2 bytes
-// + compression 4 bytes + imagesize 4 bytes + xpixelsPerM 4 bytes + ypixelsPerM 4 bytes + colorsUsed 4 bytes + colorImportant 4 bytes
-// besides, there are rgba color data = numberOfColors * 4 bytes
-const unsigned char ICO_IMAGE_INFO_HEADER = 40;
-
-typedef unsigned char DATA8;
-#define A_VAL(p) (reinterpret_cast< DATA8 * >( p )[3])
-
-#define RGB_JOIN(r,g,b) \
- (((r) << 16) + ((g) << 8) + (b))
-
-#define ARGB_JOIN(a,r,g,b) \
- (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
-
-bool read_ushort(unsigned char *map, size_t length, size_t *position, unsigned short *ret)
-{
- unsigned char b[2];
-
- if (*position + 2 > length)
- {
- return false;
- }
- b[0] = map[(*position)++];
- b[1] = map[(*position)++];
- *ret = (b[1] << 8) | b[0];
- return true;
-}
-
-bool read_uint(unsigned char *map, size_t length, size_t *position, unsigned int *ret)
-{
- unsigned char b[4];
- unsigned int i;
-
- if (*position + 4 > length)
- {
- return false;
- }
- for (i = 0; i < 4; i++)
- {
- b[i] = map[(*position)++];
- }
- *ret = ARGB_JOIN(b[3], b[2], b[1], b[0]);
- return true;
-}
-
-bool read_uchar(unsigned char *map, size_t length, size_t *position, unsigned char *ret)
-{
- if (*position + 1 > length)
- {
- return false;
- }
- *ret = map[(*position)++];
- return true;
-}
-
-bool read_mem(unsigned char *map, size_t length, size_t *position, void *buffer, int size)
-{
- if (*position + size > length)
- {
- return false;
- }
- memcpy(buffer, map + *position, size);
- *position += size;
- return true;
-}
-
-enum
-{
- SMALLEST,
- BIGGEST,
- SMALLER,
- BIGGER
-};
-
-enum
-{
- ICON = 1,
- CURSOR = 2
-};
-
-struct IcoData
-{
- int pdelta;
- int w, h;
- int cols;
- int bpp, planes;
- int hot_x, hot_y;
- unsigned int bmoffset, bmsize;
-};
-
-bool LoadIcoHeaderHelper( FILE* fp,
- IcoData& chosen,
- Dali::Vector<unsigned char>& map,
- unsigned int& fsize )
-{
- memset( &chosen, 0, sizeof(chosen) );
-
- if(fp == NULL)
- {
- DALI_LOG_ERROR("Error loading bitmap\n");
- return false;
- }
- size_t position = 0;
- unsigned short word;
- unsigned char byte;
-
- if( fseek(fp,0,SEEK_END) )
- {
- DALI_LOG_ERROR("Error seeking ICO data\n");
- return false;
- }
-
- long positionIndicator = ftell(fp);
- fsize = 0u;
-
- if( positionIndicator > -1L )
- {
- fsize = static_cast<unsigned int>(positionIndicator);
- }
-
- if( 0u == fsize )
- {
- return false;
- }
-
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking ICO data\n");
- return false;
- }
-
- if (fsize < (ICO_FILE_HEADER + ICO_IMAGE_INFO_HEADER)) //6 + 16 + 40
- {
- return false;
- }
- map.Resize(fsize);
-
- if(fread(&map[0], 1, fsize, fp) != fsize)
- {
- DALI_LOG_WARNING("image file read opeation error!\n");
- return false;
- }
-
- int search = BIGGEST;
- unsigned short reserved, type, count;
- if (!read_ushort(&map[0], fsize, &position, &reserved))
- {
- return false;
- }
- if (!read_ushort(&map[0], fsize, &position, &type))
- {
- return false;
- }
- if (!read_ushort(&map[0], fsize, &position, &count))
- {
- return false;
- }
- if (!((reserved == 0) &&
- ((type == ICON) || (type == CURSOR)) && (count != 0)))
- {
- return false;
- }
- search = BIGGEST;
- chosen.pdelta = 0;
- bool have_choice = false;
-
- for (unsigned short i = 0; i < count; i++)
- {
- unsigned char tw = 0, th = 0, tcols = 0;
- if (!read_uchar(&map[0], fsize, &position, &tw))
- {
- return false;
- }
- int w = tw;
- if (w <= 0)
- {
- w = 256;
- }
- if (!read_uchar(&map[0], fsize, &position, &th))
- {
- return false;
-
- }
- int h = th;
- if (h <= 0)
- {
- h = 256;
- }
- if (!read_uchar(&map[0], fsize, &position, &tcols))
- {
- return false;
- }
- int cols = tcols;
- if (!read_uchar(&map[0], fsize, &position, &byte))
- {
- return false;
- }
- if (!read_ushort(&map[0], fsize, &position, &word))
- {
- return false;
- }
- int planes=0;
- if (type == 1)
- {
- planes = word;
- }
- //else hot_x = word;
- if (!read_ushort(&map[0], fsize, &position, &word))
- {
- return false;
- }
- int bpp=0;
- if (type == 1)
- {
- bpp = word;
- }
-
- // 0 colors means 256 for paletized modes.
- // Note: We must not do this conversion for bpp greater than 8, as there is no palette.
- if( bpp <= 8 && cols == 0 )
- {
- cols = 256;
- }
-
- //else hot_y = word;
- unsigned int bmoffset, bmsize;
- if (!read_uint(&map[0], fsize, &position, &bmsize))
- {
- return false;
- }
- if (!read_uint(&map[0], fsize, &position, &bmoffset))
- {
- return false;
- }
- if ((bmsize <= 0) || (bmoffset <= 0) || (bmoffset >= fsize))
- {
- return false;
- }
- if (search == BIGGEST)
- {
- int pdelta = w * h;
- if ((!have_choice) ||
- ((pdelta >= chosen.pdelta) &&
- (((bpp >= 3) && (bpp >= chosen.bpp)) ||
- ((bpp < 3) && (cols >= chosen.cols)))))
- {
- have_choice = true;
- chosen.pdelta = pdelta;
- chosen.w = w;
- chosen.h = h;
- chosen.cols = cols;
- chosen.bpp = bpp;
- chosen.planes = planes;
- chosen.bmsize = bmsize;
- chosen.bmoffset = bmoffset;
- }
- }
- }
-
- if (chosen.bmoffset == 0)
- {
- return false;
- }
-
- return true;
-}
-
-}//unnamed namespace
-
-bool LoadIcoHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- IcoData chosen;
- Dali::Vector<unsigned char> map;
- unsigned int fsize;
- FILE* const fp = input.file;
-
- if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) )
- {
- return false;
- }
-
- width = chosen.w;
- height = chosen.h;
-
- return true;
-}
-
-bool LoadBitmapFromIco( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- IcoData chosen;
- Dali::Vector<unsigned char> map;
- unsigned int fsize;
- FILE* const fp = input.file;
-
- if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) )
- {
- return false;
- }
-
- Dali::Vector<unsigned int> pal;
- Dali::Vector<unsigned int> surface;
- Dali::Vector<unsigned char> maskbuf;
- Dali::Vector<unsigned char> pixbuf;
- pal.Resize(256 * 4);
-
- unsigned int dword;
- unsigned short word;
-
- int diff_size = 0;
- unsigned int* pix;
-
- size_t position = chosen.bmoffset;//22 == position
-
- unsigned int w = chosen.w;
- unsigned int h = chosen.h;
- unsigned int cols = chosen.cols;
-
- // read bmp header time... let's do some checking
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // headersize - dont care
- }
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // width
- }
- if (dword > 0)
- {
- if (dword != w)
- {
- w = dword;
- diff_size = 1;
- }
- }
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // height
- }
- if (dword > 0)
- {
- if (dword != (h * 2))
- {
- h = dword / 2;
- diff_size = 1;
- }
- }
- if (diff_size)
- {
- DALI_LOG_WARNING("Broken ICO file!\n");
- }
-
- // Set up the surface as soon as we have the width and height, so we have a black image if there are any further errors.
- surface.Resize( w * h * 4 );
- memset( &surface[0], 0, w * h * 4 );
-
- if (!read_ushort(&map[0], fsize, &position, &word))
- {
- return false; // planes
- }
- //planes2 = word;
- if (!read_ushort(&map[0], fsize, &position, &word))
- {
- return false; // bitcount
- }
- unsigned int bitcount = word;
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // compression
- }
- //compression = dword;
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // imagesize
- }
- //imagesize = dword;
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // z pixels per m
- }
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // y pizels per m
- }
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // colors used
- }
- //colorsused = dword;
- if (!read_uint(&map[0], fsize, &position, &dword))
- {
- return false; // colors important
- }
-
- for( unsigned int i = 0; i < cols ; i ++ )
- {
- unsigned char a, r, g, b;
-
- if (!read_uchar(&map[0], fsize, &position, &b))
- {
- return false;
- }
- if (!read_uchar(&map[0], fsize, &position, &g))
- {
- return false;
- }
- if (!read_uchar(&map[0], fsize, &position, &r))
- {
- return false;
- }
- if (!read_uchar(&map[0], fsize, &position, &a))
- {
- return false;
- }
- pal[i] = ARGB_JOIN( 0xff, b, g, r );
- }
-
- // This is the reference way of calculating the total number of bytes necessary to store one row of pixels.
- unsigned int stride = ( ( ( bitcount * w ) + 31 ) / 32 ) * 4;
- unsigned int bitStride = ( ( w + 31 ) / 32 ) * 4;
-
- // Pixbuf only ever contains one scanline worth of data.
- pixbuf.Resize( stride );
- maskbuf.Resize( bitStride * h );
-
- // Handle different bits-per-pixel.
- // Note: Switch is in order of most common format first.
- switch( bitcount )
- {
- case 32:
- {
- unsigned char* p = &map[position];
- pix = &surface[0] + ( ( h - 1 ) * w );
-
- for( unsigned int i = 0; i < h; i++ )
- {
- for( unsigned int j = 0; j < w; j++ )
- {
- *pix++ = ARGB_JOIN( p[3], p[0], p[1], p[2] );
- p += 4;
- }
- // Move the output up 1 line (we subtract 2 lines because we moved forward one line while copying).
- pix -= ( w * 2 );
- }
- break;
- }
-
- case 24:
- {
- for( unsigned int i = 0; i < h; i++ )
- {
- pix = &surface[0] + ( ( h - 1 - i ) * w );
- if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
- {
- return false;
- }
- unsigned char* p = &pixbuf[0];
- for( unsigned int j = 0; j < w; j++ )
- {
- *pix++ = ARGB_JOIN( 0xff, p[0], p[1], p[2] );
- p += 3;
- }
- }
- break;
- }
-
- case 8:
- {
- for( unsigned int i = 0; i < h; i++ )
- {
- pix = &surface[0] + ( ( h - 1 - i ) * w );
- if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
- {
- return false;
- }
- unsigned char* p = &pixbuf[0];
- for( unsigned int j = 0; j < w; j++ )
- {
- *pix++ = pal[*p++];
- }
- }
- break;
- }
-
- case 4:
- {
- for( unsigned int i = 0; i < h; i++ )
- {
- pix = &surface[0] + ( ( h - 1 - i ) * w );
- if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
- {
- return false;
- }
- unsigned char* p = &pixbuf[0];
- for( unsigned int j = 0; j < w; j++ )
- {
- if( j & 0x1 )
- {
- *pix = pal[*p & 0x0f];
- p++;
- }
- else
- {
- *pix = pal[*p >> 4];
- }
- pix++;
- }
- }
- break;
- }
-
- case 1:
- {
- for( unsigned int i = 0; i < h; i++ )
- {
- pix = &surface[0] + ( ( h - 1 - i ) * w );
- if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) )
- {
- return false;
- }
- unsigned char* p = &pixbuf[0];
-
- for( unsigned int j = 0; j < w; j += 8 )
- {
- *pix++ = pal[ *p >> 7 ];
- *pix++ = pal[ *p >> 6 & 0x01 ];
- *pix++ = pal[ *p >> 5 & 0x01 ];
- *pix++ = pal[ *p >> 4 & 0x01 ];
- *pix++ = pal[ *p >> 3 & 0x01 ];
- *pix++ = pal[ *p >> 2 & 0x01 ];
- *pix++ = pal[ *p >> 1 & 0x01 ];
- *pix++ = pal[ *p >> 0 & 0x01 ];
-
- p++;
- }
- }
- break;
- }
-
- default:
- {
- DALI_LOG_WARNING( "Image file contains unsupported bits-per-pixel %d\n", bitcount );
- return false;
- }
- }
-
- // From the spec: If bpp is less than 32, there will be a 1bpp mask bitmap also.
- if( bitcount < 32 )
- {
- if( !read_mem( &map[0], fsize, &position, &maskbuf[0], bitStride * h ) )
- {
- return false;
- }
-
- // Apply mask.
- // Precalc to save time in the loops.
- unsigned int bytesPerWidth = w / 8;
- unsigned int bytesRemainingPerWidth = w - ( bytesPerWidth << 3 );
-
- // Loop for each line of the image.
- for( unsigned int i = 0; i < h; ++i )
- {
- unsigned char *m = &maskbuf[0] + ( bitStride * i );
- pix = &surface[0] + ( ( h - 1 - i ) * w );
-
- // Do chunks of 8 pixels first so mask operations can be unrolled.
- for( unsigned int j = 0; j < bytesPerWidth; ++j )
- {
- // Unrolled 8 bits of the mask to avoid many conditions and branches.
- A_VAL( pix++ ) = ( *m & ( 1 << 7 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 6 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 5 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 4 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 3 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 2 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 1 ) ) ? 0x00 : 0xff;
- A_VAL( pix++ ) = ( *m & ( 1 << 0 ) ) ? 0x00 : 0xff;
- m++;
- }
-
- // Handle any remaining width ( < 8 ) or images that are < 8 wide.
- if( bytesRemainingPerWidth > 0 )
- {
- for( unsigned int j = 0; j < bytesRemainingPerWidth; ++j )
- {
- // Note: Although we are doing less that a bytes worth of mask, we still always start on the first bit.
- // If the image is smaller than 8 pixels wide, each mask will still start on a new byte.
- A_VAL( pix++ ) = ( *m & ( 1 << ( 7 - j ) ) ) ? 0x00 : 0xff;
- }
- m++;
- }
- }
- }
-
- bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::Format::RGBA8888);
- auto pixels = bitmap.GetBuffer();
- memcpy( pixels, &surface[0], w * h * 4 );
-
- return true;
-}
-
-}
-
-}
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_ICO_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_ICO_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Ico
-{
-//00 00 01 00 01 00 20 20
-const unsigned char MAGIC_BYTE_1 = 0x00;
-const unsigned char MAGIC_BYTE_2 = 0x00;
-}
-/**
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromIco( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] width of image
- * @param[out] height of image
- * @return true if header loaded successfully, false otherwise
- */
-bool LoadIcoHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-}
-
-}
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
- // CLASS HEADER
-#include "loader-jpeg.h"
-
-// EXTERNAL HEADERS
-#include <functional>
-#include <array>
-#include <utility>
-#include <memory>
-#include <libexif/exif-data.h>
-#include <libexif/exif-loader.h>
-#include <libexif/exif-tag.h>
-#include <turbojpeg.h>
-#include <jpeglib.h>
-#include <cstring>
-#include <setjmp.h>
-
-#include <dali/public-api/object/property-map.h>
-#include <dali/public-api/object/property-array.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-
-
-// INTERNAL HEADERS
-#include "platform-capabilities.h"
-#include "image-operations.h"
-#include <image-loading.h>
-#include <adaptors/common/pixel-buffer-impl.h>
-
-namespace
-{
-using Dali::Vector;
-namespace Pixel = Dali::Pixel;
-using PixelArray = unsigned char*;
-const unsigned int DECODED_L8 = 1;
-const unsigned int DECODED_RGB888 = 3;
-const unsigned int DECODED_RGBA8888 = 4;
-
-/** Transformations that can be applied to decoded pixels to respect exif orientation
- * codes in image headers */
-enum class JpegTransform
-{
- NONE, //< no transformation 0th-Row = top & 0th-Column = left
- FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right
- FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right
- TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left
- TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top
- ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top
- ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom
- ROTATE_270, //< 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom
-};
-
-/**
- * @brief Error handling bookeeping for the JPEG Turbo library's
- * setjmp/longjmp simulated exceptions.
- */
-struct JpegErrorState
-{
- struct jpeg_error_mgr errorManager;
- jmp_buf jumpBuffer;
-};
-
-/**
- * @brief Called by the JPEG library when it hits an error.
- * We jump out of the library so our loader code can return an error.
- */
-void JpegErrorHandler ( j_common_ptr cinfo )
-{
- DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" );
- /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */
- JpegErrorState * myerr = reinterpret_cast<JpegErrorState *>( cinfo->err );
-
- /* Return control to the setjmp point */
- longjmp( myerr->jumpBuffer, 1 );
-}
-
-void JpegOutputMessageHandler( j_common_ptr cinfo )
-{
- /* Stop libjpeg from printing to stderr - Do Nothing */
-}
-
-/**
- * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow
- * the JPEG to be displayed and fatal errors.
- */
-bool IsJpegErrorFatal( const std::string& errorMessage )
-{
- if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) ||
- ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) ||
- ( errorMessage.find("Invalid JPEG file structure") != std::string::npos ) ||
- ( errorMessage.find("Unsupported JPEG process") != std::string::npos ) ||
- ( errorMessage.find("Unsupported marker type") != std::string::npos ) ||
- ( errorMessage.find("Bogus marker length") != std::string::npos ) ||
- ( errorMessage.find("Bogus DQT index") != std::string::npos ) ||
- ( errorMessage.find("Bogus Huffman table definition") != std::string::npos ))
- {
- return false;
- }
- return true;
-}
-
-// helpers for safe exif memory handling
-using ExifHandle = std::unique_ptr<ExifData, decltype(exif_data_free)*>;
-
-ExifHandle MakeNullExifData()
-{
- return ExifHandle{nullptr, exif_data_free};
-}
-
-ExifHandle MakeExifDataFromData(unsigned char* data, unsigned int size)
-{
- return ExifHandle{exif_data_new_from_data(data, size), exif_data_free};
-}
-
-// Helpers for safe Jpeg memory handling
-using JpegHandle = std::unique_ptr<void /*tjhandle*/, decltype(tjDestroy)*>;
-
-JpegHandle MakeJpegCompressor()
-{
- return JpegHandle{tjInitCompress(), tjDestroy};
-}
-
-JpegHandle MakeJpegDecompressor()
-{
- return JpegHandle{tjInitDecompress(), tjDestroy};
-}
-
-using JpegMemoryHandle = std::unique_ptr<unsigned char, decltype(tjFree)*>;
-
-JpegMemoryHandle MakeJpegMemory()
-{
- return JpegMemoryHandle{nullptr, tjFree};
-}
-
-template<class T, class Deleter>
-class UniquePointerSetter final
-{
-public:
- UniquePointerSetter(std::unique_ptr<T, Deleter>& uniquePointer)
- : mUniquePointer(uniquePointer),
- mRawPointer(nullptr)
- {}
-
- /// @brief Pointer to Pointer cast operator
- operator T** () { return &mRawPointer; }
-
- /// @brief Destructor, reset the unique_ptr
- ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); }
-
-private:
- std::unique_ptr<T, Deleter>& mUniquePointer;
- T* mRawPointer;
-};
-
-template<typename T, typename Deleter>
-UniquePointerSetter<T, Deleter> SetPointer(std::unique_ptr<T, Deleter>& uniquePointer)
-{
- return UniquePointerSetter<T, Deleter>{uniquePointer};
-}
-
-using TransformFunction = std::function<void(PixelArray,unsigned, unsigned)>;
-using TransformFunctionArray = std::array<TransformFunction, 3>; // 1, 3 and 4 bytes per pixel
-
-/// @brief Select the transform function depending on the pixel format
-TransformFunction GetTransformFunction(const TransformFunctionArray& functions,
- Pixel::Format pixelFormat)
-{
- auto function = TransformFunction{};
-
- int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat);
- switch( decodedPixelSize )
- {
- case DECODED_L8:
- {
- function = functions[0];
- break;
- }
- case DECODED_RGB888:
- {
- function = functions[1];
- break;
- }
- case DECODED_RGBA8888:
- {
- function = functions[2];
- break;
- }
- default:
- {
- DALI_LOG_ERROR("Transform operation not supported on this Pixel::Format!");
- function = functions[1];
- break;
- }
- }
- return function;
-}
-
-// Storing Exif fields as properties
-template<class R, class V>
-R ConvertExifNumeric( const ExifEntry& entry )
-{
- return static_cast<R>((*reinterpret_cast<V*>(entry.data)));
-}
-
-void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd )
-{
- auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd ));
- switch( entry.format )
- {
- case EXIF_FORMAT_ASCII:
- {
- out.Insert( shortName, std::string(reinterpret_cast<char *>(entry.data)) );
- break;
- }
- case EXIF_FORMAT_SHORT:
- {
- out.Insert( shortName, ConvertExifNumeric<int, unsigned int>(entry) );
- break;
- }
- case EXIF_FORMAT_LONG:
- {
- out.Insert( shortName, ConvertExifNumeric<int, unsigned long>(entry) );
- break;
- }
- case EXIF_FORMAT_SSHORT:
- {
- out.Insert( shortName, ConvertExifNumeric<int, int>(entry) );
- break;
- }
- case EXIF_FORMAT_SLONG:
- {
- out.Insert( shortName, ConvertExifNumeric<int, long>(entry) );
- break;
- }
- case EXIF_FORMAT_FLOAT:
- {
- out.Insert (shortName, ConvertExifNumeric<float, float>(entry) );
- break;
- }
- case EXIF_FORMAT_DOUBLE:
- {
- out.Insert( shortName, ConvertExifNumeric<float, double>(entry) );
- break;
- }
- case EXIF_FORMAT_RATIONAL:
- {
- auto values = reinterpret_cast<unsigned int*>( entry.data );
- Dali::Property::Array array;
- array.Add( static_cast<int>(values[0]) );
- array.Add( static_cast<int>(values[1]) );
- out.Insert(shortName, array);
- break;
- }
- case EXIF_FORMAT_SBYTE:
- {
- out.Insert(shortName, "EXIF_FORMAT_SBYTE Unsupported");
- break;
- }
- case EXIF_FORMAT_BYTE:
- {
- out.Insert(shortName, "EXIF_FORMAT_BYTE Unsupported");
- break;
- }
- case EXIF_FORMAT_SRATIONAL:
- {
- auto values = reinterpret_cast<int*>( entry.data );
- Dali::Property::Array array;
- array.Add(values[0]);
- array.Add(values[1]);
- out.Insert(shortName, array);
- break;
- }
- case EXIF_FORMAT_UNDEFINED:
- default:
- {
- std::stringstream ss;
- ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components;
- out.Insert( shortName, ss.str());
- }
- }
-}
-
-/// @brief Apply a transform to a buffer
-bool Transform(const TransformFunctionArray& transformFunctions,
- PixelArray buffer,
- int width,
- int height,
- Pixel::Format pixelFormat )
-{
- auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat);
- if(transformFunction)
- {
- transformFunction(buffer, width, height);
- }
- return bool(transformFunction);
-}
-
-/// @brief Auxiliar type to represent pixel data with different number of bytes
-template<size_t N>
-struct PixelType
-{
- char _[N];
-};
-
-template<size_t N>
-void FlipVertical(PixelArray buffer, int width, int height)
-{
- // Destination pixel, set as the first pixel of screen
- auto to = reinterpret_cast<PixelType<N>*>( buffer );
-
- // Source pixel, as the image is flipped horizontally and vertically,
- // the source pixel is the end of the buffer of size width * height
- auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * height - 1;
-
- for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from)
- {
- std::swap(*from, *to);
- }
-}
-
-template<size_t N>
-void FlipHorizontal(PixelArray buffer, int width, int height)
-{
- for(auto iy = 0; iy < height; ++iy)
- {
- //Set the destination pixel as the beginning of the row
- auto to = reinterpret_cast<PixelType<N>*>(buffer) + width * iy;
- //Set the source pixel as the end of the row to flip in X axis
- auto from = reinterpret_cast<PixelType<N>*>(buffer) + width * (iy + 1) - 1;
- for(auto ix = 0; ix < width / 2; ++ix, ++to, --from)
- {
- std::swap(*from, *to);
- }
- }
-}
-
-template<size_t N>
-void Transpose(PixelArray buffer, int width, int height)
-{
- //Transform vertically only
- for(auto iy = 0; iy < height / 2; ++iy)
- {
- for(auto ix = 0; ix < width; ++ix)
- {
- auto to = reinterpret_cast<PixelType<N>*>(buffer) + iy * width + ix;
- auto from = reinterpret_cast<PixelType<N>*>(buffer) + (height - 1 - iy) * width + ix;
- std::swap(*from, *to);
- }
- }
-}
-
-template<size_t N>
-void Transverse(PixelArray buffer, int width, int height)
-{
- using PixelT = PixelType<N>;
- Vector<PixelT> data;
- data.Resize( width * height );
- auto dataPtr = data.Begin();
-
- auto original = reinterpret_cast<PixelT*>(buffer);
- std::copy(original, original + width * height, dataPtr);
-
- auto to = original;
- for( auto iy = 0; iy < width; ++iy )
- {
- for( auto ix = 0; ix < height; ++ix, ++to )
- {
- auto from = dataPtr + ix * width + iy;
- *to = *from;
- }
- }
-}
-
-
-template<size_t N>
-void Rotate90(PixelArray buffer, int width, int height)
-{
- using PixelT = PixelType<N>;
- Vector<PixelT> data;
- data.Resize(width * height);
- auto dataPtr = data.Begin();
-
- auto original = reinterpret_cast<PixelT*>(buffer);
- std::copy(original, original + width * height, dataPtr);
-
- std::swap(width, height);
- auto hw = width * height;
- hw = - hw - 1;
-
- auto to = original + width - 1;
- auto from = dataPtr;
-
- for(auto ix = width; --ix >= 0;)
- {
- for(auto iy = height; --iy >= 0; ++from)
- {
- *to = *from;
- to += width;
- }
- to += hw;
- }
-}
-
-template<size_t N>
-void Rotate180(PixelArray buffer, int width, int height)
-{
- using PixelT = PixelType<N>;
- Vector<PixelT> data;
- data.Resize(width * height);
- auto dataPtr = data.Begin();
-
- auto original = reinterpret_cast<PixelT*>(buffer);
- std::copy(original, original + width * height, dataPtr);
-
- auto to = original;
- for( auto iy = 0; iy < width; iy++ )
- {
- for( auto ix = 0; ix < height; ix++ )
- {
- auto from = dataPtr + (height - ix) * width - 1 - iy;
- *to = *from;
- ++to;
- }
- }
-}
-
-
-template<size_t N>
-void Rotate270(PixelArray buffer, int width, int height)
-{
- using PixelT = PixelType<N>;
- Vector<PixelT> data;
- data.Resize(width * height);
- auto dataPtr = data.Begin();
-
- auto original = reinterpret_cast<PixelT*>(buffer);
- std::copy(original, original + width * height, dataPtr);
-
- auto w = height;
- std::swap(width, height);
- auto hw = width * height;
-
- auto* to = original + hw - width;
- auto* from = dataPtr;
-
- w = -w;
- hw = hw + 1;
- for(auto ix = width; --ix >= 0;)
- {
- for(auto iy = height; --iy >= 0;)
- {
- *to = *from;
- ++from;
- to += w;
- }
- to += hw;
- }
-}
-
-} // namespace
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-JpegTransform ConvertExifOrientation(ExifData* exifData);
-bool TransformSize( int requiredWidth, int requiredHeight,
- FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
- JpegTransform transform,
- int& preXformImageWidth, int& preXformImageHeight,
- int& postXformImageWidth, int& postXformImageHeight );
-
-bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height )
-{
- // using libjpeg API to avoid having to read the whole file in a buffer
- struct jpeg_decompress_struct cinfo;
- struct JpegErrorState jerr;
- cinfo.err = jpeg_std_error( &jerr.errorManager );
-
- jerr.errorManager.output_message = JpegOutputMessageHandler;
- jerr.errorManager.error_exit = JpegErrorHandler;
-
- // On error exit from the JPEG lib, control will pass via JpegErrorHandler
- // into this branch body for cleanup and error return:
- if(setjmp(jerr.jumpBuffer))
- {
- jpeg_destroy_decompress(&cinfo);
- return false;
- }
-
-// jpeg_create_decompress internally uses C casts
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
- jpeg_create_decompress( &cinfo );
-#pragma GCC diagnostic pop
-
- jpeg_stdio_src( &cinfo, fp );
-
- // Check header to see if it is JPEG file
- if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK )
- {
- width = height = 0;
- jpeg_destroy_decompress( &cinfo );
- return false;
- }
-
- width = cinfo.image_width;
- height = cinfo.image_height;
-
- jpeg_destroy_decompress( &cinfo );
- return true;
-}
-
-bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- const int flags= 0;
- FILE* const fp = input.file;
-
- if( fseek(fp,0,SEEK_END) )
- {
- DALI_LOG_ERROR("Error seeking to end of file\n");
- return false;
- }
-
- long positionIndicator = ftell(fp);
- unsigned int jpegBufferSize = 0u;
- if( positionIndicator > -1L )
- {
- jpegBufferSize = static_cast<unsigned int>(positionIndicator);
- }
-
- if( 0u == jpegBufferSize )
- {
- return false;
- }
-
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking to start of file\n");
- return false;
- }
-
- Vector<unsigned char> jpegBuffer;
- try
- {
- jpegBuffer.Resize( jpegBufferSize );
- }
- catch(...)
- {
- DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U );
- return false;
- }
- unsigned char * const jpegBufferPtr = jpegBuffer.Begin();
-
- // Pull the compressed JPEG image bytes out of a file and into memory:
- if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize )
- {
- DALI_LOG_WARNING("Error on image file read.\n");
- return false;
- }
-
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking to start of file\n");
- }
-
- auto jpeg = MakeJpegDecompressor();
-
- if(!jpeg)
- {
- DALI_LOG_ERROR("%s\n", tjGetErrorStr());
- return false;
- }
-
- auto transform = JpegTransform::NONE;
-
- // extract exif data
- auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize);
-
- if( exifData && input.reorientationRequested )
- {
- transform = ConvertExifOrientation(exifData.get());
- }
-
- std::unique_ptr<Property::Map> exifMap;
- exifMap.reset( new Property::Map() );
-
- for( auto k = 0u; k < EXIF_IFD_COUNT; ++k )
- {
- auto content = exifData->ifd[k];
- for (auto i = 0u; i < content->count; ++i)
- {
- auto &&tag = content->entries[i];
- const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast<ExifIfd>(k));
- if(shortName)
- {
- AddExifFieldPropertyMap(*exifMap, *tag, static_cast<ExifIfd>(k));
- }
- }
- }
-
- // Push jpeg data in memory buffer through TurboJPEG decoder to make a raw pixel array:
- int chrominanceSubsampling = -1;
- int preXformImageWidth = 0, preXformImageHeight = 0;
-
- // In Ubuntu, the turbojpeg version is not correct. so build error occurs.
- // Temporarily separate Ubuntu and other profiles.
-#ifndef DALI_PROFILE_UBUNTU
- int jpegColorspace = -1;
- if( tjDecompressHeader3( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace ) == -1 )
- {
- DALI_LOG_ERROR("%s\n", tjGetErrorStr());
- // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
- }
-#else
- if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 )
- {
- DALI_LOG_ERROR("%s\n", tjGetErrorStr());
- // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type.
- }
-#endif
-
- if(preXformImageWidth == 0 || preXformImageHeight == 0)
- {
- DALI_LOG_WARNING("Invalid Image!\n");
- return false;
- }
-
- int requiredWidth = input.scalingParameters.dimensions.GetWidth();
- int requiredHeight = input.scalingParameters.dimensions.GetHeight();
-
- // If transform is a 90 or 270 degree rotation, the logical width and height
- // request from the client needs to be adjusted to account by effectively
- // rotating that too, and the final width and height need to be swapped:
- int postXformImageWidth = preXformImageWidth;
- int postXformImageHeight = preXformImageHeight;
-
-
- int scaledPreXformWidth = preXformImageWidth;
- int scaledPreXformHeight = preXformImageHeight;
- int scaledPostXformWidth = postXformImageWidth;
- int scaledPostXformHeight = postXformImageHeight;
-
- TransformSize( requiredWidth, requiredHeight,
- input.scalingParameters.scalingMode,
- input.scalingParameters.samplingMode,
- transform,
- scaledPreXformWidth, scaledPreXformHeight,
- scaledPostXformWidth, scaledPostXformHeight );
-
-
- // Colorspace conversion options
- TJPF pixelLibJpegType = TJPF_RGB;
- Pixel::Format pixelFormat = Pixel::RGB888;
-#ifndef DALI_PROFILE_UBUNTU
- switch (jpegColorspace)
- {
- case TJCS_RGB:
- // YCbCr is not an absolute colorspace but rather a mathematical transformation of RGB designed solely for storage and transmission.
- // YCbCr images must be converted to RGB before they can actually be displayed.
- case TJCS_YCbCr:
- {
- pixelLibJpegType = TJPF_RGB;
- pixelFormat = Pixel::RGB888;
- break;
- }
- case TJCS_GRAY:
- {
- pixelLibJpegType = TJPF_GRAY;
- pixelFormat = Pixel::L8;
- break;
- }
- case TJCS_CMYK:
- case TJCS_YCCK:
- {
- pixelLibJpegType = TJPF_CMYK;
- pixelFormat = Pixel::RGBA8888;
- break;
- }
- default:
- {
- pixelLibJpegType = TJPF_RGB;
- pixelFormat = Pixel::RGB888;
- break;
- }
- }
-#endif
- // Allocate a bitmap and decompress the jpeg buffer into its pixel buffer:
- bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat);
-
- // set metadata
- GetImplementation(bitmap).SetMetadata( std::move(exifMap) );
-
- auto bitmapPixelBuffer = bitmap.GetBuffer();
-
- if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast<unsigned char*>( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 )
- {
- std::string errorString = tjGetErrorStr();
-
- if( IsJpegErrorFatal( errorString ) )
- {
- DALI_LOG_ERROR("%s\n", errorString.c_str() );
- return false;
- }
- else
- {
- DALI_LOG_WARNING("%s\n", errorString.c_str() );
- }
- }
-
- const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth );
- const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight );
-
- bool result = false;
- switch(transform)
- {
- case JpegTransform::NONE:
- {
- result = true;
- break;
- }
- // 3 orientation changes for a camera held perpendicular to the ground or upside-down:
- case JpegTransform::ROTATE_180:
- {
- static auto rotate180Functions = TransformFunctionArray {
- &Rotate180<1>,
- &Rotate180<3>,
- &Rotate180<4>,
- };
- result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- case JpegTransform::ROTATE_270:
- {
- static auto rotate270Functions = TransformFunctionArray {
- &Rotate270<1>,
- &Rotate270<3>,
- &Rotate270<4>,
- };
- result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- case JpegTransform::ROTATE_90:
- {
- static auto rotate90Functions = TransformFunctionArray {
- &Rotate90<1>,
- &Rotate90<3>,
- &Rotate90<4>,
- };
- result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- case JpegTransform::FLIP_VERTICAL:
- {
- static auto flipVerticalFunctions = TransformFunctionArray {
- &FlipVertical<1>,
- &FlipVertical<3>,
- &FlipVertical<4>,
- };
- result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- // Less-common orientation changes, since they don't correspond to a camera's physical orientation:
- case JpegTransform::FLIP_HORIZONTAL:
- {
- static auto flipHorizontalFunctions = TransformFunctionArray {
- &FlipHorizontal<1>,
- &FlipHorizontal<3>,
- &FlipHorizontal<4>,
- };
- result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- case JpegTransform::TRANSPOSE:
- {
- static auto transposeFunctions = TransformFunctionArray {
- &Transpose<1>,
- &Transpose<3>,
- &Transpose<4>,
- };
- result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- case JpegTransform::TRANSVERSE:
- {
- static auto transverseFunctions = TransformFunctionArray {
- &Transverse<1>,
- &Transverse<3>,
- &Transverse<4>,
- };
- result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat );
- break;
- }
- default:
- {
- DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform );
- break;
- }
- }
-
- return result;
-}
-
-bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels,
- const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality )
-{
-
- if( !pixelBuffer )
- {
- DALI_LOG_ERROR("Null input buffer\n");
- return false;
- }
-
- // Translate pixel format enum:
- int jpegPixelFormat = -1;
-
- switch( pixelFormat )
- {
- case Pixel::RGB888:
- {
- jpegPixelFormat = TJPF_RGB;
- break;
- }
- case Pixel::RGBA8888:
- {
- // Ignore the alpha:
- jpegPixelFormat = TJPF_RGBX;
- break;
- }
- case Pixel::BGRA8888:
- {
- // Ignore the alpha:
- jpegPixelFormat = TJPF_BGRX;
- break;
- }
- default:
- {
- DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" );
- return false;
- }
- }
-
- // Assert quality is in the documented allowable range of the jpeg-turbo lib:
- DALI_ASSERT_DEBUG( quality >= 1 );
- DALI_ASSERT_DEBUG( quality <= 100 );
- if( quality < 1 )
- {
- quality = 1;
- }
- if( quality > 100 )
- {
- quality = 100;
- }
-
- // Initialise a JPEG codec:
- {
- auto jpeg = MakeJpegCompressor();
- if( jpeg )
- {
- DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() );
- return false;
- }
-
-
- // Safely wrap the jpeg codec's buffer in case we are about to throw, then
- // save the pixels to a persistent buffer that we own and let our cleaner
- // class clean up the buffer as it goes out of scope:
- auto dstBuffer = MakeJpegMemory();
-
- // Run the compressor:
- unsigned long dstBufferSize = 0;
- const int flags = 0;
-
- if( tjCompress2( jpeg.get(),
- const_cast<unsigned char*>(pixelBuffer),
- width, 0, height,
- jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize,
- TJSAMP_444, quality, flags ) )
- {
- DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr());
- return false;
- }
-
- encodedPixels.Resize( dstBufferSize );
- memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize );
- }
- return true;
-}
-
-
-JpegTransform ConvertExifOrientation(ExifData* exifData)
-{
- auto transform = JpegTransform::NONE;
- ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION);
- int orientation = 0;
- if( entry )
- {
- orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent));
- switch( orientation )
- {
- case 1:
- {
- transform = JpegTransform::NONE;
- break;
- }
- case 2:
- {
- transform = JpegTransform::FLIP_HORIZONTAL;
- break;
- }
- case 3:
- {
- transform = JpegTransform::FLIP_VERTICAL;
- break;
- }
- case 4:
- {
- transform = JpegTransform::TRANSPOSE;
- break;
- }
- case 5:
- {
- transform = JpegTransform::TRANSVERSE;
- break;
- }
- case 6:
- {
- transform = JpegTransform::ROTATE_90;
- break;
- }
- case 7:
- {
- transform = JpegTransform::ROTATE_180;
- break;
- }
- case 8:
- {
- transform = JpegTransform::ROTATE_270;
- break;
- }
- default:
- {
- // Try to keep loading the file, but let app developer know there was something fishy:
- DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry );
- break;
- }
- }
- }
- return transform;
-}
-
-bool TransformSize( int requiredWidth, int requiredHeight,
- FittingMode::Type fittingMode, SamplingMode::Type samplingMode,
- JpegTransform transform,
- int& preXformImageWidth, int& preXformImageHeight,
- int& postXformImageWidth, int& postXformImageHeight )
-{
- bool success = true;
-
- if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE)
- {
- std::swap( requiredWidth, requiredHeight );
- std::swap( postXformImageWidth, postXformImageHeight );
- }
-
- // Apply the special rules for when there are one or two zeros in requested dimensions:
- const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) );
- requiredWidth = correctedDesired.GetWidth();
- requiredHeight = correctedDesired.GetHeight();
-
- // Rescale image during decode using one of the decoder's built-in rescaling
- // ratios (expected to be powers of 2), keeping the final image at least as
- // wide and high as was requested:
-
- int numFactors = 0;
- tjscalingfactor* factors = tjGetScalingFactors( &numFactors );
- if( factors == NULL )
- {
- DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n");
- success = false;
- }
- else
- {
- // Internal jpeg downscaling is the same as our BOX_X sampling modes so only
- // apply it if the application requested one of those:
- // (use a switch case here so this code will fail to compile if other modes are added)
- bool downscale = true;
- switch( samplingMode )
- {
- case SamplingMode::BOX:
- case SamplingMode::BOX_THEN_NEAREST:
- case SamplingMode::BOX_THEN_LINEAR:
- case SamplingMode::DONT_CARE:
- {
- downscale = true;
- break;
- }
- case SamplingMode::NO_FILTER:
- case SamplingMode::NEAREST:
- case SamplingMode::LINEAR:
- {
- downscale = false;
- break;
- }
- }
-
- int scaleFactorIndex( 0 );
- if( downscale )
- {
- // Find nearest supported scaling factor (factors are in sequential order, getting smaller)
- for( int i = 1; i < numFactors; ++i )
- {
- bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth;
- bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight;
- // If either scaled dimension is smaller than the desired one, we were done at the last iteration
- if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) )
- {
- break;
- }
- // If both dimensions are smaller than the desired one, we were done at the last iteration:
- if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) )
- {
- break;
- }
- // If the width is smaller than the desired one, we were done at the last iteration:
- if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired )
- {
- break;
- }
- // If the width is smaller than the desired one, we were done at the last iteration:
- if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired )
- {
- break;
- }
- // This factor stays is within our fitting mode constraint so remember it:
- scaleFactorIndex = i;
- }
- }
-
- // Regardless of requested size, downscale to avoid exceeding the maximum texture size:
- for( int i = scaleFactorIndex; i < numFactors; ++i )
- {
- // Continue downscaling to below maximum texture size (if possible)
- scaleFactorIndex = i;
-
- if( TJSCALED(postXformImageWidth, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) &&
- TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) )
- {
- // Current scale-factor downscales to below maximum texture size
- break;
- }
- }
-
- // We have finally chosen the scale-factor, return width/height values
- if( scaleFactorIndex > 0 )
- {
- preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex]));
- preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex]));
- postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex]));
- postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex]));
- }
- }
-
- return success;
-}
-
-ExifHandle LoadExifData( FILE* fp )
-{
- auto exifData = MakeNullExifData();
- unsigned char dataBuffer[1024];
-
- if( fseek( fp, 0, SEEK_SET ) )
- {
- DALI_LOG_ERROR("Error seeking to start of file\n");
- }
- else
- {
- auto exifLoader = std::unique_ptr<ExifLoader, decltype(exif_loader_unref)*>{
- exif_loader_new(), exif_loader_unref };
-
- while( !feof(fp) )
- {
- int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp );
- if( size <= 0 )
- {
- break;
- }
- if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) )
- {
- break;
- }
- }
-
- exifData.reset( exif_loader_get_data( exifLoader.get() ) );
- }
-
- return exifData;
-}
-
-bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth();
- unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight();
- FILE* const fp = input.file;
-
- bool success = false;
- if( requiredWidth == 0 && requiredHeight == 0 )
- {
- success = LoadJpegHeader( fp, width, height );
- }
- else
- {
- // Double check we get the same width/height from the header
- unsigned int headerWidth;
- unsigned int headerHeight;
- if( LoadJpegHeader( fp, headerWidth, headerHeight ) )
- {
- auto transform = JpegTransform::NONE;
-
- if( input.reorientationRequested )
- {
- auto exifData = LoadExifData( fp );
- if( exifData )
- {
- transform = ConvertExifOrientation(exifData.get());
- }
-
- int preXformImageWidth = headerWidth;
- int preXformImageHeight = headerHeight;
- int postXformImageWidth = headerWidth;
- int postXformImageHeight = headerHeight;
-
- success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight );
- if(success)
- {
- width = postXformImageWidth;
- height = postXformImageHeight;
- }
- }
- else
- {
- success = true;
- width = headerWidth;
- height = headerHeight;
- }
- }
- }
- return success;
-}
-
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <stdio.h>
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/public-api/images/pixel.h>
-#include "image-encoder.h"
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Jpeg
-{
-const unsigned char MAGIC_BYTE_1 = 0xFF;
-const unsigned char MAGIC_BYTE_2 = 0xD8;
-} // namespace Jpeg
-
-/**
- * Loads the bitmap from an JPEG file. This function checks the header first
- * and if it is not a JPEG file, then it returns straight away.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromJpeg( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a JPEG file and fills in the width and height appropriately.
- * If the width and height are set on entry, it will set the width and height
- * to the closest scaled size (exactly as will be loaded by LoadBitmapFromJpeg with the same
- * attributes)
- * @param[in] fp Pointer to the Image file
- * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
- * @param[in/out] width Is set with the width of the image
- * @param[in/out] height Is set with the height of the image
- * @return true if the file's header was read successully, false otherwise
- */
-bool LoadJpegHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-/**
- * Encode raw pixel data to JPEG format.
- * @param[in] pixelBuffer Pointer to raw pixel data to be encoded
- * @param[out] encodedPixels Encoded pixel data. Existing contents will be overwritten
- * @param[in] width Image width
- * @param[in] height Image height
- * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888)
- * @param[in] quality JPEG quality on usual 1 to 100 scale.
- */
-bool EncodeToJpeg(const unsigned char* pixelBuffer, Vector< unsigned char >& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat, unsigned quality = 80);
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_JPEG_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "loader-ktx.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/public-api/common/compile-time-assert.h>
-#include <dali/integration-api/debug.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-#include <adaptors/common/pixel-buffer-impl.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-
-/** Max width or height of an image. */
-const unsigned MAX_TEXTURE_DIMENSION = 4096;
-/** Max bytes of image data allowed. Not a precise number, just a sanity check. */
-const unsigned MAX_IMAGE_DATA_SIZE = MAX_TEXTURE_DIMENSION * MAX_TEXTURE_DIMENSION;
-/** We don't read any of this but limit it to a resonable amount in order to be
- * friendly to files from random tools. */
-const unsigned MAX_BYTES_OF_KEYVALUE_DATA = 65536U;
-
-typedef uint8_t Byte;
-
-const Byte FileIdentifier[] = {
- 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
-};
-
-
-/** The formats we support inside a KTX file container.
- * Currently only compressed formats are allowed as we'd rather
- * use a PNG or JPEG with their own compression for the general
- * cases. */
-enum KtxInternalFormat
-{
- KTX_NOTEXIST = 0,
-
- // GLES 2 Extension formats:
- KTX_ETC1_RGB8_OES = 0x8D64,
- KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00,
-
- // GLES 3 Standard compressed formats (values same as in gl3.h):
- KTX_COMPRESSED_R11_EAC = 0x9270,
- KTX_COMPRESSED_SIGNED_R11_EAC = 0x9271,
- KTX_COMPRESSED_RG11_EAC = 0x9272,
- KTX_COMPRESSED_SIGNED_RG11_EAC = 0x9273,
- KTX_COMPRESSED_RGB8_ETC2 = 0x9274,
- KTX_COMPRESSED_SRGB8_ETC2 = 0x9275,
- KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
- KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277,
- KTX_COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
- KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
-
- // GLES 3.1 compressed formats:
- KTX_COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0,
- KTX_COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1,
- KTX_COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2,
- KTX_COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3,
- KTX_COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4,
- KTX_COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5,
- KTX_COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6,
- KTX_COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7,
- KTX_COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8,
- KTX_COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9,
- KTX_COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA,
- KTX_COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB,
- KTX_COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC,
- KTX_COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD,
-
- // Uncompressed Alpha format
- KTX_UNCOMPRESSED_ALPHA8 = 0x1906,
-
- KTX_SENTINEL = ~0u
-};
-
-const unsigned KtxInternalFormats[] =
-{
- // GLES 2 Extension formats:
- KTX_ETC1_RGB8_OES,
- KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
-
- // GLES 3 Standard compressed formats:
- KTX_COMPRESSED_R11_EAC,
- KTX_COMPRESSED_SIGNED_R11_EAC,
- KTX_COMPRESSED_RG11_EAC,
- KTX_COMPRESSED_SIGNED_RG11_EAC,
- KTX_COMPRESSED_RGB8_ETC2,
- KTX_COMPRESSED_SRGB8_ETC2,
- KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
- KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
- KTX_COMPRESSED_RGBA8_ETC2_EAC,
- KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,
-
- // GLES 3.1 Compressed formats:
- KTX_COMPRESSED_RGBA_ASTC_4x4_KHR,
- KTX_COMPRESSED_RGBA_ASTC_5x4_KHR,
- KTX_COMPRESSED_RGBA_ASTC_5x5_KHR,
- KTX_COMPRESSED_RGBA_ASTC_6x5_KHR,
- KTX_COMPRESSED_RGBA_ASTC_6x6_KHR,
- KTX_COMPRESSED_RGBA_ASTC_8x5_KHR,
- KTX_COMPRESSED_RGBA_ASTC_8x6_KHR,
- KTX_COMPRESSED_RGBA_ASTC_8x8_KHR,
- KTX_COMPRESSED_RGBA_ASTC_10x5_KHR,
- KTX_COMPRESSED_RGBA_ASTC_10x6_KHR,
- KTX_COMPRESSED_RGBA_ASTC_10x8_KHR,
- KTX_COMPRESSED_RGBA_ASTC_10x10_KHR,
- KTX_COMPRESSED_RGBA_ASTC_12x10_KHR,
- KTX_COMPRESSED_RGBA_ASTC_12x12_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,
- KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR,
-
- // Uncompressed Alpha format
- KTX_UNCOMPRESSED_ALPHA8,
-
- KTX_SENTINEL
-};
-
-struct KtxFileHeader
-{
- Byte identifier[12];
- uint32_t endianness;
- uint32_t glType;
- uint32_t glTypeSize;
- uint32_t glFormat;
- uint32_t glInternalFormat;
- uint32_t glBaseInternalFormat;
- uint32_t pixelWidth;
- uint32_t pixelHeight;
- uint32_t pixelDepth;
- uint32_t numberOfArrayElements;
- uint32_t numberOfFaces;
- uint32_t numberOfMipmapLevels;
- uint32_t bytesOfKeyValueData;
-} __attribute__ ( (__packed__));
-// Packed attribute stops the structure from being aligned to compiler defaults
-// so we can be sure of reading the whole thing from file in one call to fread.
-
-/**
- * Function to read from the file directly into our structure.
- * @param[in] fp The file to read from
- * @param[out] header The structure we want to store our information in
- * @return true, if read successful, false otherwise
- */
-inline bool ReadHeader( FILE* filePointer, KtxFileHeader& header )
-{
- const unsigned int readLength = sizeof( KtxFileHeader );
-
- // Load the information directly into our structure
- if( fread( &header, 1, readLength, filePointer ) != readLength )
- {
- return false;
- }
-
- return true;
-}
-
-/** Check whether the array passed in is the right size and matches the magic
- * values defined to be at the start of a KTX file by the specification.*/
-template<int BYTES_IN_SIGNATURE>
-bool CheckFileIdentifier(const Byte * const signature)
-{
- const unsigned signatureSize = BYTES_IN_SIGNATURE;
- const unsigned identifierSize = sizeof(FileIdentifier);
- DALI_COMPILE_TIME_ASSERT(signatureSize == identifierSize);
- const bool signatureGood = 0 == memcmp( signature, FileIdentifier, std::min( signatureSize, identifierSize ) );
- return signatureGood;
-}
-
-/**
- * @returns True if the argument is a GLES compressed texture format that we support.
- */
-bool ValidInternalFormat(const unsigned format)
-{
- unsigned candidateFormat = 0;
- for(unsigned iFormat = 0; (candidateFormat = KtxInternalFormats[iFormat]) != KTX_SENTINEL; ++iFormat)
- {
- if(format == candidateFormat)
- {
- return true;
- }
- }
- DALI_LOG_ERROR("Rejecting unsupported compressed format when loading compressed texture from KTX file: 0x%x.\n", format);
- return false;
-}
-
-/**
- * @returns The Pixel::Format Dali enum corresponding to the KTX internal format
- * passed in, or Pixel::INVALID_PIXEL_FORMAT if the format is not valid.
- **/
-bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
-{
- using namespace Dali::Pixel;
- switch(ktxPixelFormat)
- {
- // GLES 2 extension compressed formats:
- case KTX_ETC1_RGB8_OES:
- {
- format = COMPRESSED_RGB8_ETC1;
- break;
- }
- case KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
- {
- format = COMPRESSED_RGB_PVRTC_4BPPV1;
- break;
- }
-
- // GLES 3 extension compressed formats:
- case KTX_COMPRESSED_R11_EAC:
- {
- format = COMPRESSED_R11_EAC;
- break;
- }
- case KTX_COMPRESSED_SIGNED_R11_EAC:
- {
- format = COMPRESSED_SIGNED_R11_EAC;
- break;
- }
- case KTX_COMPRESSED_RG11_EAC:
- {
- format = COMPRESSED_RG11_EAC;
- break;
- }
- case KTX_COMPRESSED_SIGNED_RG11_EAC:
- {
- format = COMPRESSED_SIGNED_RG11_EAC;
- break;
- }
- case KTX_COMPRESSED_RGB8_ETC2:
- {
- format = COMPRESSED_RGB8_ETC2;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ETC2:
- {
- format = COMPRESSED_SRGB8_ETC2;
- break;
- }
- case KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
- {
- format = COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
- break;
- }
- case KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
- {
- format = COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
- break;
- }
- case KTX_COMPRESSED_RGBA8_ETC2_EAC:
- {
- format = COMPRESSED_RGBA8_ETC2_EAC;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
- break;
- }
-
- // GLES 3.1 extension compressed formats:
- case KTX_COMPRESSED_RGBA_ASTC_4x4_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_4x4_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_5x4_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_5x4_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_5x5_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_5x5_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_6x5_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_6x5_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_6x6_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_6x6_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_8x5_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_8x5_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_8x6_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_8x6_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_8x8_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_8x8_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_10x5_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_10x5_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_10x6_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_10x6_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_10x8_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_10x8_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_10x10_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_10x10_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_12x10_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_12x10_KHR;
- break;
- }
- case KTX_COMPRESSED_RGBA_ASTC_12x12_KHR:
- {
- format = COMPRESSED_RGBA_ASTC_12x12_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
- break;
- }
- case KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
- {
- format = COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
- break;
- }
-
- // Uncompressed Alpha format
- case KTX_UNCOMPRESSED_ALPHA8:
- {
- format = A8;
- break;
- }
-
- default:
- {
- return false;
- }
- }
- return true;
-}
-
-bool LoadKtxHeader( FILE * const fp, unsigned int& width, unsigned int& height, KtxFileHeader& fileHeader )
-{
- // Pull the bytes of the file header in as a block:
- if ( !ReadHeader( fp, fileHeader ) )
- {
- return false;
- }
- width = fileHeader.pixelWidth;
- height = fileHeader.pixelHeight;
-
- if ( width > MAX_TEXTURE_DIMENSION || height > MAX_TEXTURE_DIMENSION )
- {
- return false;
- }
-
- // Validate file header contents meet our minimal subset:
- const bool signatureGood = CheckFileIdentifier<sizeof(fileHeader.identifier)>(fileHeader.identifier);
- const bool fileEndiannessMatchesSystemEndianness = fileHeader.endianness == 0x04030201; // Magic number from KTX spec.
- const bool glTypeIsCompressed = fileHeader.glType == 0;
- const bool glTypeSizeCompatibleWithCompressedTex = fileHeader.glTypeSize == 1;
- const bool glFormatCompatibleWithCompressedTex = fileHeader.glFormat == 0;
- const bool glInternalFormatIsSupportedCompressedTex = ValidInternalFormat(fileHeader.glInternalFormat);
- // Ignore glBaseInternalFormat
- const bool textureIsNot3D = fileHeader.pixelDepth == 0 || fileHeader.pixelDepth == 1;
- const bool textureIsNotAnArray = fileHeader.numberOfArrayElements == 0 || fileHeader.numberOfArrayElements == 1;
- const bool textureIsNotACubemap = fileHeader.numberOfFaces == 0 || fileHeader.numberOfFaces == 1;
- const bool textureHasNoMipmapLevels = fileHeader.numberOfMipmapLevels == 0 || fileHeader.numberOfMipmapLevels == 1;
- const bool keyValueDataNotTooLarge = fileHeader.bytesOfKeyValueData <= MAX_BYTES_OF_KEYVALUE_DATA;
-
- bool headerIsValid = signatureGood && fileEndiannessMatchesSystemEndianness &&
- glTypeSizeCompatibleWithCompressedTex && textureIsNot3D && textureIsNotAnArray &&
- textureIsNotACubemap && textureHasNoMipmapLevels && keyValueDataNotTooLarge;
-
- if( !glTypeIsCompressed ) // check for uncompressed Alpha
- {
- const bool isAlpha = ( ( fileHeader.glBaseInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) && ( fileHeader.glFormat == KTX_UNCOMPRESSED_ALPHA8 ) &&
- ( fileHeader.glInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) );
- headerIsValid = headerIsValid && isAlpha;
- }
- else
- {
- headerIsValid = headerIsValid && glFormatCompatibleWithCompressedTex && glInternalFormatIsSupportedCompressedTex;
- }
-
- if( !headerIsValid )
- {
- DALI_LOG_ERROR( "KTX file invalid or using unsupported features. Header tests: sig: %d, endian: %d, gl_type: %d, gl_type_size: %d, gl_format: %d, internal_format: %d, depth: %d, array: %d, faces: %d, mipmap: %d, vey-vals: %d.\n", 0+signatureGood, 0+fileEndiannessMatchesSystemEndianness, 0+glTypeIsCompressed, 0+glTypeSizeCompatibleWithCompressedTex, 0+glFormatCompatibleWithCompressedTex, 0+glInternalFormatIsSupportedCompressedTex, 0+textureIsNot3D, 0+textureIsNotAnArray, 0+textureIsNotACubemap, 0+textureHasNoMipmapLevels, 0+keyValueDataNotTooLarge);
- }
-
- // Warn if there is space wasted in the file:
- if( fileHeader.bytesOfKeyValueData > 0U )
- {
- DALI_LOG_WARNING("Loading of KTX file with key/value header data requested. This should be stripped in application asset/resource build.\n");
- }
-
- return headerIsValid;
-}
-
-
-} // unnamed namespace
-
-// File loading API entry-point:
-bool LoadKtxHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- KtxFileHeader fileHeader;
- FILE* const fp = input.file;
-
- bool ret = LoadKtxHeader(fp, width, height, fileHeader);
- return ret;
-}
-
-// File loading API entry-point:
-bool LoadBitmapFromKtx( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- DALI_COMPILE_TIME_ASSERT( sizeof(Byte) == 1);
- DALI_COMPILE_TIME_ASSERT( sizeof(uint32_t) == 4);
-
- FILE* const fp = input.file;
- if( fp == NULL )
- {
- DALI_LOG_ERROR( "Null file handle passed to KTX compressed bitmap file loader.\n" );
- return false;
- }
- KtxFileHeader fileHeader;
-
- // Load the header info
- unsigned int width, height;
-
- if (!LoadKtxHeader(fp, width, height, fileHeader))
- {
- return false;
- }
-
- // Skip the key-values:
- const long int imageSizeOffset = sizeof(KtxFileHeader) + fileHeader.bytesOfKeyValueData;
- if(fseek(fp, imageSizeOffset, SEEK_SET))
- {
- DALI_LOG_ERROR( "Seek past key/vals in KTX compressed bitmap file failed.\n" );
- return false;
- }
-
- // Load the size of the image data:
- uint32_t imageByteCount = 0;
- if ( fread( &imageByteCount, 1, 4, fp ) != 4 )
- {
- DALI_LOG_ERROR( "Read of image size failed.\n" );
- return false;
- }
- // Sanity-check the image size:
- if( imageByteCount > MAX_IMAGE_DATA_SIZE ||
- // A compressed texture should certainly be less than 2 bytes per texel:
- imageByteCount > width * height * 2)
- {
- DALI_LOG_ERROR( "KTX file with too-large image-data field.\n" );
- return false;
- }
-
- Pixel::Format pixelFormat;
- const bool pixelFormatKnown = ConvertPixelFormat(fileHeader.glInternalFormat, pixelFormat);
- if(!pixelFormatKnown)
- {
- DALI_LOG_ERROR( "No internal pixel format supported for KTX file pixel format.\n" );
- return false;
- }
-
- // Load up the image bytes:
- bitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
-
- // Compressed format won't allocate the buffer
- auto pixels = bitmap.GetBuffer();
- if( !pixels )
- {
- // allocate buffer manually
- auto &impl = GetImplementation(bitmap);
- impl.AllocateFixedSize(imageByteCount);
- pixels = bitmap.GetBuffer();
- }
-
- if(!pixels)
- {
- DALI_LOG_ERROR( "Unable to reserve a pixel buffer to load the requested bitmap into.\n" );
- return false;
- }
-
- const size_t bytesRead = fread(pixels, 1, imageByteCount, fp);
- if(bytesRead != imageByteCount)
- {
- DALI_LOG_ERROR( "Read of image pixel data failed.\n" );
- return false;
- }
-
- return true;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Ktx
-{
-const unsigned char MAGIC_BYTE_1 = 0xAB;
-const unsigned char MAGIC_BYTE_2 = 0x4B;
-} // namespace Ktx
-
-/**
- * Loads a compressed bitmap from a KTX file without decoding it.
- * This function checks the header first
- * and if it is not a KTX file, then it returns straight away.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file loaded successfully, false otherwise
- */
-bool LoadBitmapFromKtx( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a KTX file and fills in the width and height appropriately.
- * @param[in] fp Pointer to the Image file
- * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
- * @param[out] width Is set with the width of the image
- * @param[out] height Is set with the height of the image
- * @return true if the file's header was read successully, false otherwise
- */
-bool LoadKtxHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_KTX_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "loader-png.h"
-
-#include <cstring>
-
-#include <zlib.h>
-#include <png.h>
-
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/images/image.h>
-#include "platform-capabilities.h"
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-
-namespace Dali
-{
-namespace TizenPlatform
-{
-
-namespace
-{
-
-// simple class to enforce clean-up of PNG structures
-struct auto_png
-{
- auto_png(png_structp& _png, png_infop& _info)
- : png(_png),
- info(_info)
- {
- }
-
- ~auto_png()
- {
- if(NULL != png)
- {
- png_destroy_read_struct(&png, &info, NULL);
- }
- }
-
- png_structp& png;
- png_infop& info;
-}; // struct auto_png;
-
-bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info)
-{
- png_byte header[8] = { 0 };
-
- // Check header to see if it is a PNG file
- size_t size = fread(header, 1, 8, fp);
- if(size != 8)
- {
- return false;
- }
-
- if(png_sig_cmp(header, 0, 8))
- {
- return false;
- }
-
- png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
-
- if(!png)
- {
- DALI_LOG_WARNING("Can't create PNG read structure\n");
- return false;
- }
-
- info = png_create_info_struct(png);
- if(!info)
- {
- DALI_LOG_WARNING("png_create_info_struct failed\n");
- return false;
- }
-
- png_set_expand(png);
-
- if(setjmp(png_jmpbuf(png)))
- {
- DALI_LOG_WARNING("error during png_init_io\n");
- return false;
- }
-
- png_init_io(png, fp);
- png_set_sig_bytes(png, 8);
-
- // read image info
- png_read_info(png, info);
-
- // dimensions
- width = png_get_image_width(png, info);
- height = png_get_image_height(png, info);
-
- return true;
-}
-
-} // namespace - anonymous
-
-bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- png_structp png = NULL;
- png_infop info = NULL;
- auto_png autoPng(png, info);
-
- bool success = LoadPngHeader( input.file, width, height, png, info );
-
- return success;
-}
-
-bool LoadBitmapFromPng( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- png_structp png = NULL;
- png_infop info = NULL;
- auto_png autoPng(png, info);
-
- /// @todo: consider parameters
- unsigned int y;
- unsigned int width, height;
- png_bytep *rows;
- unsigned int bpp = 0; // bytes per pixel
- bool valid = false;
-
- // Load info from the header
- if( !LoadPngHeader( input.file, width, height, png, info ) )
- {
- return false;
- }
-
- Pixel::Format pixelFormat = Pixel::RGBA8888;
-
- // decide pixel format
- unsigned int colordepth = png_get_bit_depth(png, info);
-
- // Ask PNGLib to convert high precision images into something we can use:
- if (colordepth == 16)
- {
- png_set_strip_16(png);
- colordepth = 8;
- }
-
- png_byte colortype = png_get_color_type(png, info);
-
- if( colortype == PNG_COLOR_TYPE_GRAY ||
- colortype == PNG_COLOR_TYPE_GRAY_ALPHA )
- {
- if( colortype == PNG_COLOR_TYPE_GRAY )
- {
- pixelFormat = Pixel::L8;
- if( png_get_valid(png, info, PNG_INFO_tRNS) )
- {
- colortype = PNG_COLOR_TYPE_GRAY_ALPHA;
- /* expand transparency entry -> alpha channel if present */
- png_set_tRNS_to_alpha(png);
- pixelFormat = Pixel::LA88;
- }
- }
- else
- {
- pixelFormat = Pixel::LA88;
- }
-
- if( colordepth < 8 )
- {
- /* expand gray (w/reduced bits) -> 8-bit RGB if necessary */
- png_set_expand_gray_1_2_4_to_8(png);
- /* pack all pixels to byte boundaries */
- png_set_packing(png);
- }
- valid = true;
- }
- else if(colortype == PNG_COLOR_TYPE_RGB )
- {
- switch(colordepth)
- {
- case 8:
- {
- pixelFormat = Pixel::RGB888;
- valid = true;
- break;
- }
- case 5: /// @todo is this correct for RGB16 5-6-5 ?
- {
- pixelFormat = Pixel::RGB565;
- valid = true;
- break;
- }
- default:
- {
- break;
- }
- }
- }
- else if(colortype == PNG_COLOR_TYPE_RGBA)
- {
- switch(colordepth)
- {
- case 8:
- {
- pixelFormat = Pixel::RGBA8888;
- valid = true;
- break;
- }
- default:
- {
- break;
- }
- }
- }
- else if(colortype == PNG_COLOR_TYPE_PALETTE)
- {
- switch(colordepth)
- {
- case 1:
- {
- pixelFormat = Pixel::LA88;
- valid = true;
- break;
- }
-
- case 2:
- case 4:
- case 8:
- {
- /* Expand paletted or RGB images with transparency to full alpha channels
- * so the data will be available as RGBA quartets. PNG_INFO_tRNS = 0x10
- */
- if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10)
- {
- pixelFormat = Pixel::RGBA8888;
- valid = true;
- }
- else
- {
- pixelFormat = Pixel::RGB888;
- png_set_packing(png);
- png_set_packswap(png);
- png_set_palette_to_rgb(png);
- valid = true;
- }
- break;
- }
- default:
- {
- break;
- }
- }
- }
-
- if( !valid )
- {
- DALI_LOG_WARNING( "Unsupported png format\n" );
- return false;
- }
-
- // bytes per pixel
- bpp = Pixel::GetBytesPerPixel(pixelFormat);
-
- png_read_update_info(png, info);
-
- if(setjmp(png_jmpbuf(png)))
- {
- DALI_LOG_WARNING("error during png_read_image\n");
- return false;
- }
-
- unsigned int rowBytes = png_get_rowbytes(png, info);
-
- unsigned int bufferWidth = GetTextureDimension(width);
- unsigned int bufferHeight = GetTextureDimension(height);
- unsigned int stride = bufferWidth*bpp;
-
- // not sure if this ever happens
- if( rowBytes > stride )
- {
- stride = GetTextureDimension(rowBytes);
-
- bpp = stride / bufferWidth;
- switch(bpp)
- {
- case 3:
- pixelFormat = Pixel::RGB888;
- break;
- case 4:
- pixelFormat = Pixel::RGBA8888;
- break;
- default:
- break;
- }
-
- }
-
- // decode the whole image into bitmap buffer
- auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat)).GetBuffer();
-
- DALI_ASSERT_DEBUG(pixels);
- rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) );
- for(y=0; y<height; y++)
- {
- rows[y] = pixels + y * stride;
- }
-
- // decode image
- png_read_image(png, rows);
-
- free(rows);
-
- return true;
-}
-
-// simple class to enforce clean-up of PNG structures
-struct AutoPngWrite
-{
- AutoPngWrite(png_structp& _png, png_infop& _info)
- : png(_png),
- info(_info)
- {
- }
-
- ~AutoPngWrite()
- {
- if(NULL != png)
- {
- png_destroy_write_struct(&png, &info);
- }
- }
-
- png_structp& png;
- png_infop& info;
-}; // struct AutoPngWrite;
-
-namespace
-{
- // Custom libpng write callbacks that buffer to a vector instead of a file:
-
- /**
- * extern "C" linkage is used because this is a callback that we pass to a C
- * library which is part of the underlying platform and so potentially compiled
- * as C rather than C++.
- * @see http://stackoverflow.com/a/2594222
- * */
- extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length)
- {
- DALI_ASSERT_DEBUG(png_ptr && data);
- if(!png_ptr || !data)
- {
- return;
- }
- // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library:
- try
- {
- // Recover our buffer for writing into:
- Vector<unsigned char>* const encoded_img = static_cast< Vector<unsigned char>* >( png_get_io_ptr(png_ptr) );
- if(encoded_img)
- {
- const Vector<unsigned char>::SizeType bufferSize = encoded_img->Count();
- encoded_img->Resize( bufferSize + length ); //< Can throw OOM.
- unsigned char* const bufferBack = encoded_img->Begin() + bufferSize;
- memcpy(bufferBack, data, length);
- }
- else
- {
- DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n");
- }
- }
- catch(...)
- {
- DALI_LOG_ERROR("C++ Exception caught\n");
- }
- }
-
- /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */
- extern "C" void FlushData(png_structp png_ptr)
- {
-#ifdef DEBUG_ENABLED
- Debug::LogMessage(Debug::DebugInfo, "PNG Flush");
-#endif // DEBUG_ENABLED
- }
-}
-
-/**
- * Potential improvements:
- * 1. Detect <= 256 colours and write in palette mode.
- * 2. Detect grayscale (will early-out quickly for colour images).
- * 3. Store colour space / gamma correction info related to the device screen?
- * http://www.libpng.org/pub/png/book/chapter10.html
- * 4. Refactor with callers to write straight through to disk and save keeping a big buffer around.
- * 5. Prealloc buffer (reserve) to input size / <A number greater than 2 (expexcted few realloc but without using lots of memory) | 1 (expected zero reallocs but using a lot of memory)>.
- * 6. Set the modification time with png_set_tIME(png_ptr, info_ptr, mod_time);
- * 7. If caller asks for no compression, bypass libpng and blat raw data to
- * disk, topped and tailed with header/tail blocks.
- */
-bool EncodeToPng( const unsigned char* const pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat )
-{
- // Translate pixel format enum:
- int pngPixelFormat = -1;
- unsigned pixelBytes = 0;
- bool rgbaOrder = true;
-
- // Account for RGB versus BGR and presence of alpha in input pixels:
- switch( pixelFormat )
- {
- case Pixel::RGB888:
- {
- pngPixelFormat = PNG_COLOR_TYPE_RGB;
- pixelBytes = 3;
- break;
- }
- case Pixel::BGRA8888:
- {
- rgbaOrder = false;
- ///! No break: fall through:
- }
- case Pixel::RGBA8888:
- {
- pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA;
- pixelBytes = 4;
- break;
- }
- default:
- {
- DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" );
- return false;
- }
- }
-
- const int interlace = PNG_INTERLACE_NONE;
-
- png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- if(!png_ptr)
- {
- return false;
- }
- /* Allocate/initialize the image information data. REQUIRED */
- png_infop info_ptr = png_create_info_struct( png_ptr );
- if(!info_ptr)
- {
- png_destroy_write_struct(&png_ptr, NULL);
- return false;
- }
-
- /* Set error handling. REQUIRED if you aren't supplying your own
- * error handling functions in the png_create_write_struct() call.
- */
- if(setjmp(png_jmpbuf(png_ptr)))
- {
- png_destroy_write_struct(&png_ptr, &info_ptr);
- return false;
- }
-
- // Since we are going to write to memory instead of a file, lets provide
- // libpng with a custom write function and ask it to pass back our
- // Vector buffer each time it calls back to flush data to "file":
- png_set_write_fn(png_ptr, &encodedPixels, WriteData, FlushData);
-
- // png_set_compression_level( png_ptr, Z_BEST_COMPRESSION);
- png_set_compression_level(png_ptr, Z_BEST_SPEED);
- // png_set_compression_level( png_ptr, Z_NO_COMPRESSION); //! We could just generate png directly without libpng in this case.
-
- // Explicitly limit the number of filters used per scanline to speed us up:
- // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place.
- // PNG_FILTER_SUB |
- // PNG_FILTER_UP |
- // PNG_FILTER_AVE |
- // PNG_FILTER_PAETH |
- // PNG_ALL_FILTERS);
- // Play with Zlib parameters in optimisation phase:
- // png_set_compression_mem_level(png_ptr, 8);
- // png_set_compression_strategy(png_ptr,
- // Z_DEFAULT_STRATEGY);
- // png_set_compression_window_bits(png_ptr, 15);
- // png_set_compression_method(png_ptr, 8);
- // png_set_compression_buffer_size(png_ptr, 8192)
-
- // Let lib_png know if the pixel bytes are in BGR(A) order:
- if(!rgbaOrder)
- {
- png_set_bgr( png_ptr );
- }
-
- // Set the image information:
- png_set_IHDR(png_ptr, info_ptr, width, height, 8,
- pngPixelFormat, interlace,
- PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
-
- // Start to output the PNG data to our buffer:
- png_write_info(png_ptr, info_ptr);
-
- // Walk the rows:
- const unsigned row_step = width * pixelBytes;
- png_bytep row_ptr = const_cast<png_bytep>(pixelBuffer);
- const png_bytep row_end = row_ptr + height * row_step;
- for(; row_ptr < row_end; row_ptr += row_step)
- {
- png_write_row(png_ptr, row_ptr);
- }
-
- /* It is REQUIRED to call this to finish writing the rest of the file */
- png_write_end(png_ptr, info_ptr);
- /* Clean up after the write, and free any memory allocated */
- png_destroy_write_struct(&png_ptr, &info_ptr);
- return true;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/public-api/images/pixel.h>
-#include "image-encoder.h"
-#include "image-loader-input.h"
-
-namespace Dali
-{
-namespace Devel
-{
-class PixelBuffer;
-}
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-namespace Png
-{
-const unsigned char MAGIC_BYTE_1 = 0x89;
-const unsigned char MAGIC_BYTE_2 = 0x50;
-} // namespace Png
-
-/**
- * Loads the bitmap from an PNG file. This function checks the header first
- * and if it is not a PNG file, then it returns straight away.
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromPng( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * Loads the header of a PNG file and fills in the width and height appropriately.
- * @param[in] fp Pointer to the Image file
- * @param[in] attributes Describes the dimensions, pixel format and other details for loading the image data
- * @param[out] width Is set with the width of the image
- * @param[out] height Is set with the height of the image
- * @return true if the file's header was read successully, false otherwise
- */
-bool LoadPngHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-/**
- * Encode raw pixel data to PNG format.
- * @param[in] pixelBuffer Pointer to raw pixel data to be encoded
- * @param[out] encodedPixels Encoded pixel data. Existing contents will be overwritten
- * @param[in] width Image width
- * @param[in] height Image height
- * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888)
- */
-bool EncodeToPng( const unsigned char* pixelBuffer, Vector<unsigned char>& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat );
-
-} // namespace TizenPlatform
-
-} // namespace Dali
-
-#endif // __DALI_TIZEN_PLATFORM_LOADER_PNG_H__
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// HEADER
-#include "loader-wbmp.h"
-
-// EXTERNAL INCLUDES
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-// INTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <adaptors/devel-api/adaptor-framework/pixel-buffer.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_LOADER_WBMP");
-#endif
-
-#define IMG_MAX_SIZE 65536
-
-#define IMG_TOO_BIG(w, h) \
- ((((unsigned long long)w) * ((unsigned long long)h)) >= \
- ((1ULL << (29)) - 2048))
-
-
-//extract multiple bytes integer , and saved in *data
-int extractMultiByteInteger(unsigned int *data, void *map, size_t length, size_t *position)
-{
- // the header field contains an image type indentifier of multi-byte length(TypeField), an octet of general header info(FixHeaderField)
- //, a multi-byte width field(Width) and a multi-byte height field(Height) and so on.
- // The actual organisation of the image data depends on the image type
- // for Ext Headers flag (7th bit), 1 = More will follow, 0 = Last octet
- // so in the for loop, if(buf & 0x80 == 0), loop will be exited
- int targetMultiByteInteger = 0, readBufCount;
- unsigned char buf;
-
- for (readBufCount = 0;;)
- {
- // readBufCount means the count that fetched data from map
- // extractMultiByteInteger() is to fetch wbmp type , width, and height
- // for wbmp type, when readBufCount == 1, buf = 0x00, it will exit the loop
- // for width, it have 4 bytes, so when readBufCount == 4, it must exit the loop
- // for general width and height, if(buf & 0x80) == 0, then the next byte does not need to fetch again
- // first step, readBufCount = 1 , read int(4 bytes) to buf, if buf & 0x80 !=0, the buf need to continue to fetch
- // second step, readBufCount = 2, read next( 4 bytes) to buf, if buf & 0x80 == 0, then assigned the buf to target
- if ((readBufCount ++) == 4)
- {
- return -1;
- }
- if (*position > length)
- {
- return -1;
- }
- buf = reinterpret_cast< unsigned char * >( map )[(*position)++];
- targetMultiByteInteger = (targetMultiByteInteger << 7) | (buf & 0x7f);
-
- if ((buf & 0x80) == 0)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "position: %d, readBufCount: %d\n", *position, readBufCount);
- break;
- }
- }
- *data = targetMultiByteInteger;
- return 0;
-}
-
-}// end unnamed namespace
-
-bool LoadBitmapFromWbmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap )
-{
- FILE* const fp = input.file;
- if(fp == NULL)
- {
- DALI_LOG_ERROR("Error loading bitmap\n");
- return false;
- }
- Dali::Vector<unsigned char> map;
- Dali::Vector<unsigned char> surface;//unsigned int
- size_t position = 0;
-
- unsigned int w, h;
- unsigned int type;
- unsigned int line_length;
- unsigned char *line = NULL;
- unsigned int cur = 0, x, y;
-
- if( fseek(fp,0,SEEK_END) )
- {
- DALI_LOG_ERROR("Error seeking WBMP data\n");
- return false;
- }
- long positionIndicator = ftell(fp);
-
- unsigned int fsize( 0u );
- if( positionIndicator > -1L )
- {
- fsize = static_cast<unsigned int>(positionIndicator);
- }
-
- if( 0u == fsize )
- {
- DALI_LOG_ERROR("Error: filesize is 0!\n");
- return false;
- }
-
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking WBMP data\n");
- return false;
- }
- if(fsize <= 4)
- {
- DALI_LOG_ERROR("Error: WBMP Raw Data Not Found!\n");
- return false;
- }
- if(fsize > 4096 * 4096 * 4)
- {
- DALI_LOG_ERROR("Error: WBMP size is too large!\n");
- return false;
- }
- map.Resize(fsize);
-
- if(fread(&map[0], 1, fsize, fp) != fsize)
- {
- DALI_LOG_WARNING("image file read opeation error!\n");
- return false;
- }
-
- if (extractMultiByteInteger(&type, &map[0], fsize, &position) < 0)
- {
- return false;
- }
-
- position++; /* skipping one byte */
-
- if (extractMultiByteInteger(&w, &map[0], fsize, &position) < 0)
- {
- return false;
- }
- if (extractMultiByteInteger(&h, &map[0], fsize, &position) < 0)
- {
- return false;
- }
- if(type != 0)
- {
- DALI_LOG_ERROR("Unknown Format!\n");
- return false;
- }
-
- if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE))
- {
- return false;
- }
-
- surface.Resize(w* h );//(w * h * 4);
- memset(&surface[0], 0, w * h ); // w * h * 4
-
- line_length = (w + 7) >> 3;
- for (y = 0; y < h; y ++)
- {
- if (position + line_length > fsize)
- {
- return false;
- }
- line = &map[0] + position;
- position += line_length;
- for (x = 0; x < w; x++)
- {
- int idx = x >> 3;
- int offset = 1 << (0x07 - (x & 0x07));
- if (line[idx] & offset)
- {
- surface[cur] = 0xff;//0xffffffff;
- }
- else
- {
- surface[cur] = 0x00;//0xff000000;
- }
- cur++;
- }
- }
- auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::L8)).GetBuffer();
-
- memcpy( pixels, &surface[0], w * h ); //w * h * 4
-
- return true;
-}
-
-
-bool LoadWbmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height )
-{
- FILE* const fp = input.file;
- if(fp == NULL)
- {
- DALI_LOG_ERROR("Error loading bitmap\n");
- return false;
- }
- Dali::Vector<unsigned char> map;
- size_t position = 0;
-
- unsigned int w, h;
- unsigned int type;
- if( fseek(fp,0,SEEK_END) )
- {
- DALI_LOG_ERROR("Error seeking WBMP data\n");
- return false;
- }
- long positionIndicator = ftell(fp);
-
- unsigned int fsize( 0u );
- if( positionIndicator > -1L )
- {
- fsize = static_cast<unsigned int>(positionIndicator);
- }
-
- if( 0u == fsize )
- {
- return false;
- }
-
- if( fseek(fp, 0, SEEK_SET) )
- {
- DALI_LOG_ERROR("Error seeking WBMP data\n");
- return false;
- }
- if(fsize <= 4)
- {
- DALI_LOG_ERROR("Error: WBMP Raw Data Not Found!\n");
- return false;
- }
-
- // type(1 byte) + fixedheader(1 byte) + width(uint) + height(uint)
- unsigned int headerSize = 1 + 1 + 4 + 4;// 8 + 8 + 32 + 32;
- headerSize = std::min(headerSize, fsize);
-
- map.Resize(headerSize);
- if(fread(&map[0], 1, headerSize, fp) != headerSize)
- {
- DALI_LOG_WARNING("image file read opeation error!\n");
- return false;
- }
-
- if (extractMultiByteInteger(&type, &map[0], headerSize, &position) < 0)
- {
- DALI_LOG_ERROR("Error: unable to read type!\n");
- return false;
- }
- position++; /* skipping one byte */
- if(type != 0)
- {
- DALI_LOG_ERROR("Error: unknown format!\n");
- return false;
- }
- if (extractMultiByteInteger(&w, &map[0], headerSize, &position) < 0)
- {
- DALI_LOG_ERROR("Error: can not read width!\n");
- return false;
- }
- if (extractMultiByteInteger(&h, &map[0], headerSize, &position) < 0)
- {
- DALI_LOG_ERROR("Error: can not read height!\n");
- return false;
- }
-
- if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE) )
- {
- DALI_LOG_ERROR("Error: file size is not supported!\n");
- return false;
- }
-
- width = w;
- height = h;
- return true;
-}
-
-}
-}
+++ /dev/null
-#ifndef __DALI_TIZEN_PLATFORM_LOADER_WBMP_H__
-#define __DALI_TIZEN_PLATFORM_LOADER_WBMP_H__
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <cstdio>
-#include "image-loader-input.h"
-
-namespace Dali
-{
-
-namespace Devel
-{
-class PixelBuffer;
-}
-
-namespace TizenPlatform
-{
-
-class ResourceLoadingClient;
-
-/**
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] bitmap The bitmap class where the decoded image will be stored
- * @return true if file decoded successfully, false otherwise
- */
-bool LoadBitmapFromWbmp( const ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap );
-
-/**
- * @param[in] input Information about the input image (including file pointer)
- * @param[out] width of image
- * @param[out] height of image
- * @return true if header loaded successfully, false otherwise
- */
-bool LoadWbmpHeader( const ImageLoader::Input& input, unsigned int& width, unsigned int& height );
-
-}
-
-}
-#endif
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// HEADER
-#include "file-download.h"
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <pthread.h>
-#include <curl/curl.h>
-#include <openssl/crypto.h>
-#include <cstring>
-
-// INTERNAL INCLUDES
-#include "portable/file-writer.h"
-
-#ifdef TPK_CURL_ENABLED
-#include <tpkp_curl.h>
-#endif // TPK_CURL_ENABLED
-
-using namespace Dali::Integration;
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace // unnamed namespace
-{
-
-const int CONNECTION_TIMEOUT_SECONDS( 30L );
-const long VERBOSE_MODE = 0L; // 0 == off, 1 == on
-const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on
-const long EXCLUDE_HEADER = 0L;
-const long INCLUDE_HEADER = 1L;
-const long INCLUDE_BODY = 0L;
-const long EXCLUDE_BODY = 1L;
-
-/**
- * Curl library environment. Direct initialize ensures it's constructed before adaptor
- * or application creates any threads.
- */
-static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment;
-
-void ConfigureCurlOptions( CURL* curlHandle, const std::string& url )
-{
- curl_easy_setopt( curlHandle, CURLOPT_URL, url.c_str() );
- curl_easy_setopt( curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE );
-
- // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual )
- // Removed CURLOPT_FAILONERROR option
- curl_easy_setopt( curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS );
- curl_easy_setopt( curlHandle, CURLOPT_HEADER, INCLUDE_HEADER );
- curl_easy_setopt( curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY );
-
-#ifdef TPK_CURL_ENABLED
- // Apply certificate pinning on Tizen
- curl_easy_setopt( curlHandle, CURLOPT_SSL_CTX_FUNCTION, tpkp_curl_ssl_ctx_callback );
-#endif // TPK_CURL_ENABLED
-}
-
-// Without a write function or a buffer (file descriptor) to write to, curl will pump out
-// header/body contents to stdout
-size_t DummyWrite(char *ptr, size_t size, size_t nmemb, void *userdata)
-{
- return size * nmemb;
-}
-
-struct ChunkData
-{
- std::vector< uint8_t > data;
-};
-
-size_t ChunkLoader(char *ptr, size_t size, size_t nmemb, void *userdata)
-{
- std::vector<ChunkData>* chunks = static_cast<std::vector<ChunkData>*>( userdata );
- int numBytes = size*nmemb;
- chunks->push_back( ChunkData() );
- ChunkData& chunkData = (*chunks)[chunks->size()-1];
- chunkData.data.reserve( numBytes );
- memcpy( &chunkData.data[0], ptr, numBytes );
- return numBytes;
-}
-
-
-CURLcode DownloadFileDataWithSize( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t dataSize )
-{
- CURLcode result( CURLE_OK );
-
- // create
- Dali::Internal::Platform::FileWriter fileWriter( dataBuffer, dataSize );
- FILE* dataBufferFilePointer = fileWriter.GetFile();
- if( NULL != dataBufferFilePointer )
- {
- // we only want the body which contains the file data
- curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
- curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
-
- // disable the write callback, and get curl to write directly into our data buffer
- curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, NULL );
- curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer );
-
- // synchronous request of the body data
- result = curl_easy_perform( curlHandle );
- }
- return result;
-}
-
-CURLcode DownloadFileDataByChunk( CURL* curlHandle, Dali::Vector<uint8_t>& dataBuffer, size_t& dataSize )
-{
- // create
- std::vector< ChunkData > chunks;
-
- // we only want the body which contains the file data
- curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER );
- curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY );
-
- // Enable the write callback.
- curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader );
- curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, &chunks );
-
- // synchronous request of the body data
- CURLcode result = curl_easy_perform( curlHandle );
-
- // chunks should now contain all of the chunked data. Reassemble into a single vector
- dataSize = 0;
- for( size_t i=0; i<chunks.size() ; ++i )
- {
- dataSize += chunks[i].data.capacity();
- }
- dataBuffer.Resize(dataSize);
-
- size_t offset = 0;
- for( size_t i=0; i<chunks.size() ; ++i )
- {
- memcpy( &dataBuffer[offset], &chunks[i].data[0], chunks[i].data.capacity() );
- offset += chunks[i].data.capacity();
- }
-
- return result;
-}
-
-bool DownloadFile( CURL* curlHandle,
- const std::string& url,
- Dali::Vector<uint8_t>& dataBuffer,
- size_t& dataSize,
- size_t maximumAllowedSizeBytes )
-{
- CURLcode result( CURLE_OK );
- double size(0);
-
- // setup curl to download just the header so we can extract the content length
- ConfigureCurlOptions( curlHandle, url );
-
- curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite);
-
- // perform the request to get the header
- result = curl_easy_perform( curlHandle );
-
- if( result != CURLE_OK)
- {
- DALI_LOG_WARNING( "Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result );
- return false;
- }
-
- // get the content length, -1 == size is not known
- curl_easy_getinfo( curlHandle,CURLINFO_CONTENT_LENGTH_DOWNLOAD , &size );
-
-
- if( size >= maximumAllowedSizeBytes )
- {
- DALI_LOG_WARNING( "File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str() );
- return false;
- }
- else if( size > 0 )
- {
- // If we know the size up front, allocate once and avoid chunk copies.
- dataSize = static_cast<size_t>( size );
- result = DownloadFileDataWithSize( curlHandle, dataBuffer, dataSize );
- }
- else
- {
- result = DownloadFileDataByChunk( curlHandle, dataBuffer, dataSize );
- }
-
- if( result != CURLE_OK )
- {
- DALI_LOG_WARNING( "Failed to download image file \"%s\" with error code %d\n", url.c_str(), result );
- return false;
- }
- return true;
-}
-
-
-} // unnamed namespace
-
-
-namespace Network
-{
-
-std::mutex* CurlEnvironment::mMutexs = NULL;
-
-CurlEnvironment::CurlEnvironment()
-{
- // Must be called before we attempt any loads. e.g. by using curl_easy_init()
- // and before we start any threads.
- curl_global_init(CURL_GLOBAL_ALL);
-
- // libcurl with openssl needs locking_function and thread id for threadsafe
- // https://curl.haxx.se/libcurl/c/threadsafe.html
- // https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
- // SetLockingFunction sets locking_function and get thread id by the guide.
- SetLockingFunction();
-}
-
-CurlEnvironment::~CurlEnvironment()
-{
- UnsetLockingFunction();
-
- curl_global_cleanup();
-}
-
-// libcurl with openssl needs locking_function and thread id for threadsafe
-// https://curl.haxx.se/libcurl/c/threadsafe.html
-// https://www.openssl.org/docs/man1.0.2/crypto/threads.html#DESCRIPTION
-void CurlEnvironment::OnOpenSSLLocking( int mode, int n, const char* file, int line )
-{
- if( mode & CRYPTO_LOCK )
- {
- mMutexs[n].lock();
- }
- else
- {
- mMutexs[n].unlock();
- }
-}
-
-unsigned long CurlEnvironment::GetThreadId()
-{
- // If dali uses c++ thread, we may replace pthread_self() to this_thread::get_id()
- return static_cast< unsigned long >( pthread_self() );
-}
-
-void CurlEnvironment::SetLockingFunction()
-{
- if( mMutexs != NULL )
- {
- return;
- }
-
- mMutexs = new std::mutex[ CRYPTO_num_locks() ];
-
- CRYPTO_set_id_callback( &CurlEnvironment::GetThreadId );
- CRYPTO_set_locking_callback( &CurlEnvironment::OnOpenSSLLocking );
-}
-
-void CurlEnvironment::UnsetLockingFunction()
-{
- if( mMutexs == NULL )
- {
- return;
- }
-
- CRYPTO_set_id_callback( NULL );
- CRYPTO_set_locking_callback( NULL );
- delete [] mMutexs;
- mMutexs = NULL;
-}
-
-bool DownloadRemoteFileIntoMemory( const std::string& url,
- Dali::Vector<uint8_t>& dataBuffer,
- size_t& dataSize,
- size_t maximumAllowedSizeBytes )
-{
- if( url.empty() )
- {
- DALI_LOG_WARNING("empty url requested \n");
- return false;
- }
-
- // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download
- // thread we need to explicity call curl_global_init() on startup from a single thread.
-
- CURL* curlHandle = curl_easy_init();
-
- bool result = DownloadFile( curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes);
-
- // clean up session
- curl_easy_cleanup( curlHandle );
-
-#ifdef TPK_CURL_ENABLED
- // Clean up tpkp(the module for certificate pinning) resources on Tizen
- tpkp_curl_cleanup();
-#endif // TPK_CURL_ENABLED
-
- return result;
-}
-
-} // namespace Network
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "http-utils.h"
-
-// EXTERNAL INCLUDES
-#include <cstring>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-namespace
-{
-const unsigned int MIN_HTTP_URL_LENGTH = 12; // assume we have a least http://xx/yy
-const char HTTP_URL[] = "http://";
-const char HTTPS_URL[] = "https://";
-}
-
-bool Network::IsHttpUrl( const std::string& path )
-{
- if( path.size() <= MIN_HTTP_URL_LENGTH )
- {
- return false;
- }
-
- if( ( strncasecmp( path.c_str(), HTTP_URL, sizeof(HTTP_URL) -1 ) == 0 ) ||
- ( strncasecmp( path.c_str(), HTTPS_URL, sizeof(HTTPS_URL) -1 ) == 0 ) )
- {
- return true;
- }
-
- return false;
-}
-
-} // TizenPlatform
-
-} // Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// FUNCTION HEADER
-#include "tizen-logging.h"
-
-// EXTERNAL INCLUDES
-#ifndef DALI_PROFILE_UBUNTU
-// Dlog uses C style casts internally
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <dlog.h>
-#else // DALI_PROFILE_UBUNTU
-#include <cstdio>
-#endif
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message)
-{
- const char* DALI_TAG = "DALI";
-
-#ifndef DALI_PROFILE_UBUNTU
- switch(level)
- {
- case Dali::Integration::Log::DebugInfo:
- LOG(LOG_INFO, DALI_TAG, "%s", message.c_str());
- break;
- case Dali::Integration::Log::DebugWarning:
- LOG(LOG_WARN, DALI_TAG, "%s", message.c_str());
- break;
- case Dali::Integration::Log::DebugError:
- LOG(LOG_ERROR, DALI_TAG, "%s", message.c_str());
- break;
- default:
- LOG(LOG_DEFAULT, DALI_TAG, "%s", message.c_str());
- break;
- }
-#pragma GCC diagnostic pop
-#else // DALI_PROFILE_UBUNTU
- const char *format = NULL;
- switch(level)
- {
- case Dali::Integration::Log::DebugInfo:
- format = "\e[1;34mINFO:\e[21m %s: %s\e[0m";
- break;
- case Dali::Integration::Log::DebugWarning:
- format = "\e[1;33mWARN:\e[21m %s: %s\e[0m";
- break;
- case Dali::Integration::Log::DebugError:
- format = "\e[1;91mERROR:\e[21m %s: %s\e[0m";
- break;
- default:
- format = ":\e[21m %s: %s\e[0m";
- break;
- }
- printf(format, DALI_TAG, message.c_str());
-#endif // DALI_PROFILE_UBUNTU
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "tizen-platform-abstraction.h"
-
-// EXTERNAL INCLUDES
-#include <dirent.h>
-#include <fstream>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/bitmap.h>
-#include <dali/integration-api/resource-types.h>
-
-// INTERNAL INCLUDES
-#include "image-loaders/image-loader.h"
-#include "portable/file-reader.h"
-#include <adaptors/common/pixel-buffer-impl.h>
-
-namespace Dali
-{
-
-namespace TizenPlatform
-{
-
-TizenPlatformAbstraction::TizenPlatformAbstraction()
-: mDataStoragePath( "" )
-{
-}
-
-TizenPlatformAbstraction::~TizenPlatformAbstraction()
-{
-}
-
-ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( const std::string& filename,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection )
-{
- return ImageLoader::GetClosestImageSize( filename, size, fittingMode, samplingMode, orientationCorrection );
-}
-
-ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection )
-{
- return ImageLoader::GetClosestImageSize( resourceBuffer, size, fittingMode, samplingMode, orientationCorrection );
-}
-
-Integration::ResourcePointer TizenPlatformAbstraction::LoadImageSynchronously(const Integration::BitmapResourceType& resource, const std::string& resourcePath)
-{
- return ImageLoader::LoadImageSynchronously( resource, resourcePath );
-}
-
-Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer( const Integration::BitmapResourceType& resource, uint8_t * buffer, size_t size )
-{
- Integration::BitmapPtr resultBitmap;
- Dali::Devel::PixelBuffer bitmap;
-
- Dali::Internal::Platform::FileReader fileReader( buffer, size );
- FILE * const fp = fileReader.GetFile();
- if( fp )
- {
- bool result = ImageLoader::ConvertStreamToBitmap( resource, "", fp, bitmap );
- if ( !result || !bitmap )
- {
- bitmap.Reset();
- DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" );
- }
- else
- {
- Integration::Bitmap::Profile profile{Integration::Bitmap::Profile::BITMAP_2D_PACKED_PIXELS};
-
- // For backward compatibility the Bitmap must be created
- auto retval = Integration::Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD);
-
- retval->GetPackedPixelsProfile()->ReserveBuffer(
- bitmap.GetPixelFormat(),
- bitmap.GetWidth(),
- bitmap.GetHeight(),
- bitmap.GetWidth(),
- bitmap.GetHeight()
- );
-
- auto& impl = Dali::GetImplementation(bitmap);
-
- std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer());
- resultBitmap.Reset(retval);
- }
- }
-
- return resultBitmap;
-}
-
-bool TizenPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const
-{
- bool result = false;
-
-#ifdef SHADERBIN_CACHE_ENABLED
- std::string path;
-
- // First check the system location where shaders are stored at install time:
- path = DALI_SHADERBIN_DIR;
- path += filename;
- result = LoadFile( path, buffer );
-
- // Fallback to the cache of shaders stored after previous runtime compilations:
- // On desktop this looks in the current working directory that the app was launched from.
- if( mResourceLoader && result == false )
- {
- path = mDataStoragePath;
- path += filename;
- result = LoadFile( path, buffer );
- }
-#endif
-
- return result;
-}
-
-bool TizenPlatformAbstraction::SaveShaderBinaryFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const
-{
- bool result = false;
-
-#ifdef SHADERBIN_CACHE_ENABLED
-
- // Use the cache of shaders stored after previous runtime compilations:
- // On desktop this looks in the current working directory that the app was launched from.
- std::string path = mDataStoragePath;
- path += filename;
- result = SaveFile( path, buffer, numBytes );
-
-#endif
-
- return result;
-}
-
-void TizenPlatformAbstraction::SetDataStoragePath( const std::string& path )
-{
- mDataStoragePath = path;
-}
-
-TizenPlatformAbstraction* CreatePlatformAbstraction()
-{
- return new TizenPlatformAbstraction();
-}
-
-bool SaveFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes )
-{
- DALI_ASSERT_DEBUG( 0 != filename.length());
-
- bool result = false;
-
- std::filebuf buf;
- buf.open(filename.c_str(), std::ios::out | std::ios_base::trunc | std::ios::binary);
- if( buf.is_open() )
- {
- std::ostream stream(&buf);
-
- // determine size of buffer
- int length = static_cast<int>(numBytes);
-
- // write contents of buffer to the file
- stream.write(reinterpret_cast<const char*>(buffer), length);
-
- if( !stream.bad() )
- {
- result = true;
- }
- }
-
- return result;
-}
-
-} // namespace TizenPlatform
-
-} // namespace Dali
*/
// INTERNAL INCLUDES
-#include <feedback-plugin.h>
+#include <dali/devel-api/adaptor-framework/feedback-plugin.h>
namespace Dali
{
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/devel-api/text-abstraction/bidirectional-support.h>
-
-// INTERNAL INCLUDES
-#include <dali/internal/text-abstraction/bidirectional-support-impl.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-BidirectionalSupport::BidirectionalSupport()
-{
-}
-
-BidirectionalSupport::~BidirectionalSupport()
-{
-}
-
-BidirectionalSupport::BidirectionalSupport( Internal::BidirectionalSupport* implementation )
-: BaseHandle( implementation )
-{
-}
-
-BidirectionalSupport BidirectionalSupport::Get()
-{
- return Internal::BidirectionalSupport::Get();
-}
-
-BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
- Length numberOfCharacters )
-{
- return GetImplementation( *this ).CreateInfo( paragraph,
- numberOfCharacters );
-}
-
-void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
-{
- GetImplementation( *this ).DestroyInfo( bidiInfoIndex );
-}
-
-void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
- CharacterIndex firstCharacterIndex,
- Length numberOfCharacters,
- CharacterIndex* visualToLogicalMap )
-{
- GetImplementation( *this ).Reorder( bidiInfoIndex,
- firstCharacterIndex,
- numberOfCharacters,
- visualToLogicalMap );
-}
-
-bool BidirectionalSupport::GetMirroredText( Character* text,
- CharacterDirection* directions,
- Length numberOfCharacters )
-{
- return GetImplementation( *this ).GetMirroredText( text,
- directions,
- numberOfCharacters );
-}
-
-bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
-{
- return GetImplementation( *this ).GetParagraphDirection( bidiInfoIndex );
-}
-
-void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
- CharacterDirection* directions,
- Length numberOfCharacters )
-{
- GetImplementation( *this ).GetCharactersDirection( bidiInfoIndex,
- directions,
- numberOfCharacters );
-}
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/devel-api/text-abstraction/font-client.h>
-
-// INTERNAL INCLUDES
-#include <dali/internal/text-abstraction/font-client-impl.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-const PointSize26Dot6 FontClient::DEFAULT_POINT_SIZE = 768u; // 12*64
-
-FontClient::GlyphBufferData::GlyphBufferData()
-: buffer( NULL ),
- width( 0u ),
- height( 0u ),
- format( Pixel::A8 )
-{
-}
-
-FontClient::GlyphBufferData::~GlyphBufferData()
-{
-}
-
-FontClient FontClient::Get()
-{
- return Internal::FontClient::Get();
-}
-
-FontClient::FontClient()
-{
-}
-
-FontClient::~FontClient()
-{
-}
-
-FontClient::FontClient( const FontClient& handle )
-: BaseHandle( handle )
-{
-}
-
-FontClient& FontClient::operator=( const FontClient& handle )
-{
- BaseHandle::operator=( handle );
- return *this;
-}
-
-void FontClient::SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi )
-{
- GetImplementation(*this).SetDpi( horizontalDpi, verticalDpi );
-}
-
-void FontClient::GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi )
-{
- GetImplementation(*this).GetDpi( horizontalDpi, verticalDpi );
-}
-
-int FontClient::GetDefaultFontSize()
-{
- return GetImplementation(*this).GetDefaultFontSize();
-}
-
-void FontClient::ResetSystemDefaults()
-{
- GetImplementation(*this).ResetSystemDefaults();
-}
-
-void FontClient::GetDefaultFonts( FontList& defaultFonts )
-{
- GetImplementation(*this).GetDefaultFonts( defaultFonts );
-}
-
-void FontClient::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
-{
- GetImplementation(*this).GetDefaultPlatformFontDescription( fontDescription );
-}
-
-void FontClient::GetSystemFonts( FontList& systemFonts )
-{
- GetImplementation(*this).GetSystemFonts( systemFonts );
-}
-
-void FontClient::GetDescription( FontId id, FontDescription& fontDescription )
-{
- GetImplementation(*this).GetDescription( id, fontDescription );
-}
-
-PointSize26Dot6 FontClient::GetPointSize( FontId id )
-{
- return GetImplementation(*this).GetPointSize( id );
-}
-
-bool FontClient::IsCharacterSupportedByFont( FontId fontId, Character character )
-{
- return GetImplementation(*this).IsCharacterSupportedByFont( fontId, character );
-}
-
-FontId FontClient::FindDefaultFont( Character charcode,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- return GetImplementation(*this).FindDefaultFont( charcode,
- requestedPointSize,
- preferColor );
-}
-
-FontId FontClient::FindFallbackFont( Character charcode,
- const FontDescription& preferredFontDescription,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- return GetImplementation(*this).FindFallbackFont( charcode, preferredFontDescription, requestedPointSize, preferColor );
-}
-
-FontId FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
-{
- return GetImplementation(*this).GetFontId( path, requestedPointSize, faceIndex );
-}
-
-FontId FontClient::GetFontId( const FontDescription& fontDescription,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex )
-{
- return GetImplementation(*this).GetFontId( fontDescription,
- requestedPointSize,
- faceIndex );
-}
-
-bool FontClient::IsScalable( const FontPath& path )
-{
- return GetImplementation(*this).IsScalable( path );
-}
-
-bool FontClient::IsScalable( const FontDescription& fontDescription )
-{
- return GetImplementation(*this).IsScalable( fontDescription );
-}
-
-void FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes )
-{
- GetImplementation(*this).GetFixedSizes( path, sizes );
-}
-
-void FontClient::GetFixedSizes( const FontDescription& fontDescription,
- Dali::Vector< PointSize26Dot6 >& sizes )
-{
- GetImplementation(*this).GetFixedSizes( fontDescription, sizes );
-}
-
-void FontClient::GetFontMetrics( FontId fontId, FontMetrics& metrics )
-{
- GetImplementation(*this).GetFontMetrics( fontId, metrics );
-}
-
-GlyphIndex FontClient::GetGlyphIndex( FontId fontId, Character charcode )
-{
- return GetImplementation(*this).GetGlyphIndex( fontId, charcode );
-}
-
-bool FontClient::GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal )
-{
- return GetImplementation(*this).GetGlyphMetrics( array, size, type, horizontal );
-}
-
-void FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, GlyphBufferData& data, int outlineWidth )
-{
- GetImplementation(*this).CreateBitmap( fontId, glyphIndex, data, outlineWidth );
-}
-
-PixelData FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
-{
- return GetImplementation(*this).CreateBitmap( fontId, glyphIndex, outlineWidth );
-}
-
-void FontClient::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
-{
- GetImplementation(*this).CreateVectorBlob( fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
-}
-
-const GlyphInfo& FontClient::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
-{
- return GetImplementation(*this).GetEllipsisGlyph( requestedPointSize );
-}
-
-bool FontClient::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
-{
- return GetImplementation(*this).IsColorGlyph( fontId, glyphIndex );
-}
-
-FontClient::FontClient( Internal::FontClient* internal )
-: BaseHandle( internal )
-{
-}
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/devel-api/text-abstraction/segmentation.h>
-
-// INTERNAL INCLUDES
-#include <dali/internal/text-abstraction/segmentation-impl.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-Segmentation::Segmentation()
-{
-}
-
-Segmentation::~Segmentation()
-{
-}
-
-Segmentation::Segmentation( Internal::Segmentation* implementation )
-: BaseHandle( implementation )
-{
-}
-
-Segmentation Segmentation::Get()
-{
- return Internal::Segmentation::Get();
-}
-
-void Segmentation::GetLineBreakPositions( const Character* const text,
- Length numberOfCharacters,
- LineBreakInfo* breakInfo )
-{
- GetImplementation( *this ).GetLineBreakPositions( text,
- numberOfCharacters,
- breakInfo );
-}
-
-void Segmentation::GetWordBreakPositions( const Character* const text,
- Length numberOfCharacters,
- WordBreakInfo* breakInfo )
-{
- GetImplementation( *this ).GetWordBreakPositions( text,
- numberOfCharacters,
- breakInfo );
-}
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/devel-api/text-abstraction/shaping.h>
-
-// INTERNAL INCLUDES
-#include <dali/internal/text-abstraction/shaping-impl.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-Shaping::Shaping()
-{
-}
-
-Shaping::~Shaping()
-{
-}
-
-Shaping::Shaping( Internal::Shaping *impl )
-: BaseHandle( impl )
-{
-}
-
-Shaping Shaping::Get()
-{
- return Internal::Shaping::Get();
-}
-
-Length Shaping::Shape( const Character* const text,
- Length numberOfCharacters,
- FontId fontId,
- Script script )
-{
- return GetImplementation( *this ).Shape( text,
- numberOfCharacters,
- fontId,
- script );
-}
-
-void Shaping::GetGlyphs( GlyphInfo* glyphInfo,
- CharacterIndex* glyphToCharacterMap )
-{
- GetImplementation( *this ).GetGlyphs( glyphInfo,
- glyphToCharacterMap );
-}
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-# Add local source files here:
-
-static_libraries_glyphy_src_files = \
- $(static_libraries_glyphy_src_dir)/glyphy-arcs.cc \
- $(static_libraries_glyphy_src_dir)/glyphy-blob-impl.cc \
- $(static_libraries_glyphy_src_dir)/glyphy-extents.cc \
- $(static_libraries_glyphy_src_dir)/glyphy-outline.cc \
- $(static_libraries_glyphy_src_dir)/glyphy-sdf.cc \
- $(static_libraries_glyphy_src_dir)/vector-font-cache.cpp
+++ /dev/null
-/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/internal/glyphy/vector-font-cache.h>
-
-// EXTERNAL INCLUDES
-#include <vector>
-#include <math.h>
-
-// INTERNAL INCLUDES
-#include "../glyphy/glyphy.h"
-#include "../glyphy/glyphy-freetype.h"
-
-using namespace std;
-
-namespace
-{
-
-const unsigned int INITIAL_GLYPH_CAPACITY = 50;
-const double MIN_FONT_SIZE = 10;
-
-static glyphy_bool_t
-accumulate_endpoint( glyphy_arc_endpoint_t* endpoint,
- vector<glyphy_arc_endpoint_t>* endpoints )
-{
- endpoints->push_back( *endpoint );
- return true;
-}
-
-} // unnamed namespace
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-typedef vector<VectorBlob> BlobArray;
-
-struct VectorGlyph
-{
- /**
- * @brief Create a vector-based glyph.
- */
- static VectorGlyph* New( FT_Face face,
- FontId fontId,
- GlyphIndex index,
- glyphy_arc_accumulator_t* accumulator )
- {
- VectorGlyph* newGlyph = new VectorGlyph();
- newGlyph->blobData.resize( 1024 * 16 );
-
- if( FT_Err_Ok != FT_Load_Glyph( face,
- index,
- FT_LOAD_NO_BITMAP |
- FT_LOAD_NO_HINTING |
- FT_LOAD_NO_AUTOHINT |
- FT_LOAD_NO_SCALE |
- FT_LOAD_LINEAR_DESIGN |
- FT_LOAD_IGNORE_TRANSFORM))
- {
- DALI_LOG_ERROR( "FT_Load_Glyph failed\n" );
- delete newGlyph;
- return NULL;
- }
-
- const double upem = static_cast<double>( face->units_per_EM );
- const double tolerance = upem * 1.0f/2048.0f;
-
- glyphy_arc_accumulator_reset( accumulator);
- glyphy_arc_accumulator_set_tolerance( accumulator, tolerance );
-
- vector<glyphy_arc_endpoint_t> endpoints;
- glyphy_arc_accumulator_set_callback( accumulator,
- reinterpret_cast<glyphy_arc_endpoint_accumulator_callback_t>( accumulate_endpoint ),
- &endpoints );
-
- if( FT_Err_Ok != glyphy_freetype_outline_decompose( &face->glyph->outline, accumulator ) )
- {
- DALI_LOG_ERROR( "glyphy_freetype_outline_decompose failed\n" );
- delete newGlyph;
- return NULL;
- }
-
- DALI_ASSERT_DEBUG( glyphy_arc_accumulator_get_error(accumulator) <= tolerance && "glyphy_arc_accumulator_get_error > tolerance" );
-
- if( endpoints.size() )
- {
- glyphy_outline_winding_from_even_odd( &endpoints[0], endpoints.size (), false );
- }
-
- unsigned int blobLength( 0 );
- double averageFetchAchieved( 0.0 );
- if (!glyphy_arc_list_encode_blob( endpoints.size() ? &endpoints[0] : NULL,
- endpoints.size(),
- &newGlyph->blobData[0],
- newGlyph->blobData.capacity(),
- upem / ( MIN_FONT_SIZE * M_SQRT2 ),
- 4,
- &averageFetchAchieved,
- &blobLength,
- &newGlyph->nominalWidth,
- &newGlyph->nominalHeight,
- &newGlyph->extents ) )
- {
- DALI_LOG_ERROR( "glyphy_arc_list_encode_blob failed\n" );
- delete newGlyph;
- return NULL;
- }
- newGlyph->blobData.resize( blobLength );
-
- glyphy_extents_scale( &newGlyph->extents, 1.0/upem, 1.0/upem );
-
- newGlyph->glyphInfo.fontId = fontId;
- newGlyph->glyphInfo.index = index;
-
- if( glyphy_extents_is_empty( &newGlyph->extents ) )
- {
- newGlyph->glyphInfo.width = 0.0f;
- newGlyph->glyphInfo.height = 0.0f;
-
- newGlyph->glyphInfo.xBearing = 0.0f;
- newGlyph->glyphInfo.yBearing = 0.0f;
- }
- else
- {
- newGlyph->glyphInfo.width = (newGlyph->extents.max_x - newGlyph->extents.min_x);
- newGlyph->glyphInfo.height = (newGlyph->extents.max_y - newGlyph->extents.min_y);
-
- newGlyph->glyphInfo.xBearing = newGlyph->extents.min_x;
- newGlyph->glyphInfo.yBearing = newGlyph->glyphInfo.height + (newGlyph->extents.min_y);
- }
-
- newGlyph->glyphInfo.advance = face->glyph->metrics.horiAdvance / upem;
- newGlyph->glyphInfo.scaleFactor = 0.0f;
-
- return newGlyph;
- }
-
- VectorGlyph()
- : advance( 0.0 ),
- nominalWidth( 0 ),
- nominalHeight( 0 ),
- glyphInfo(),
- blobData()
- {
- glyphy_extents_clear( &extents );
- }
-
- glyphy_extents_t extents;
- double advance;
- unsigned int nominalWidth;
- unsigned int nominalHeight;
- GlyphInfo glyphInfo;
- BlobArray blobData;
-};
-
-typedef vector<VectorGlyph*> GlyphCache;
-
-struct VectorFont
-{
- VectorFont( FT_Face face )
- : mFace( face ),
- mGlyphCache()
- {
- mGlyphCache.reserve( INITIAL_GLYPH_CAPACITY );
- }
-
- FT_Face mFace;
- GlyphCache mGlyphCache;
-};
-
-struct VectorFontCache::Impl
-{
- Impl( FT_Library freeTypeLibrary )
- : mFreeTypeLibrary( freeTypeLibrary ),
- mIdLookup(),
- mVectorFonts(),
- mAccumulator( NULL )
- {
- mAccumulator = glyphy_arc_accumulator_create();
- }
-
- ~Impl()
- {
- glyphy_arc_accumulator_destroy( mAccumulator );
- }
-
-private:
-
- // Declared private and left undefined to avoid copies.
- Impl( const Impl& );
- // Declared private and left undefined to avoid copies.
- Impl& operator=( const Impl& );
-
-public:
-
- FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance.
-
- vector<string> mIdLookup;
-
- vector<VectorFont*> mVectorFonts;
-
- glyphy_arc_accumulator_t* mAccumulator;
-};
-
-VectorFontCache::VectorFontCache( FT_Library freeTypeLibrary )
-: mImpl( NULL )
-{
- mImpl = new Impl( freeTypeLibrary );
-}
-
-VectorFontCache::~VectorFontCache()
-{
- delete mImpl;
-}
-
-FontId VectorFontCache::GetFontId( const std::string& url )
-{
- FontId id( 0 );
-
- if( mImpl )
- {
- if( ! FindFont( url, id ) )
- {
- id = CreateFont( url );
- }
- }
-
- return id;
-}
-
-void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo )
-{
- if( mImpl )
- {
- if( vectorFontId > 0 &&
- vectorFontId-1 < mImpl->mVectorFonts.size() )
- {
- VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
- GlyphCache& cache = font->mGlyphCache;
-
- bool foundGlyph( false );
- unsigned int foundIndex( 0 );
- for( unsigned int i=0; i<cache.size(); ++i )
- {
- VectorGlyph* glyph = cache[i];
-
- if( glyph->glyphInfo.index == glyphInfo.index )
- {
- foundIndex = i;
- foundGlyph = true;
- break;
- }
- }
-
- if( foundGlyph )
- {
- VectorGlyph* glyph = cache[foundIndex];
- // Note - this clobbers the original fontId, but helps avoid duplicating identical blobs
- // e.g. if when the same font family is requested in different point-sizes
- glyphInfo = glyph->glyphInfo;
- }
- else
- {
- VectorGlyph* newGlyph = VectorGlyph::New( font->mFace,
- glyphInfo.fontId,
- glyphInfo.index,
- mImpl->mAccumulator );
-
- if( newGlyph )
- {
- glyphInfo = newGlyph->glyphInfo;
-
- cache.push_back( newGlyph );
- }
- }
- }
- }
-}
-
-void VectorFontCache::GetVectorBlob( FontId vectorFontId,
- FontId fontId,
- GlyphIndex glyphIndex,
- VectorBlob*& blob,
- unsigned int& blobLength,
- unsigned int& nominalWidth,
- unsigned int& nominalHeight )
-{
- if( mImpl )
- {
- if( vectorFontId > 0 &&
- vectorFontId-1 < mImpl->mVectorFonts.size() )
- {
- VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
- GlyphCache& cache = font->mGlyphCache;
-
- bool foundGlyph( false );
- unsigned int foundIndex( 0 );
- for( unsigned int i=0; i<cache.size(); ++i )
- {
- VectorGlyph* glyph = cache[i];
-
- if( glyph->glyphInfo.index == glyphIndex )
- {
- foundIndex = i;
- foundGlyph = true;
- break;
- }
- }
-
- if( foundGlyph )
- {
- VectorGlyph* glyph = cache[foundIndex];
-
- blob = &glyph->blobData[0];
- blobLength = glyph->blobData.size();
- nominalWidth = glyph->nominalWidth;
- nominalHeight = glyph->nominalHeight;
- }
- else
- {
- VectorGlyph* newGlyph = VectorGlyph::New( font->mFace, fontId, glyphIndex, mImpl->mAccumulator );
-
- if( newGlyph )
- {
- blob = &newGlyph->blobData[0];
- blobLength = newGlyph->blobData.size();
- nominalWidth = newGlyph->nominalWidth;
- nominalHeight = newGlyph->nominalHeight;
-
- cache.push_back( newGlyph );
- }
- }
- }
- }
-}
-
-bool VectorFontCache::FindFont( const string& url, FontId& vectorFontId ) const
-{
- vectorFontId = 0u;
-
- const vector<string>& idLookup = mImpl->mIdLookup;
-
- for( unsigned int i=0; i<idLookup.size(); ++i, ++vectorFontId )
- {
- if( url == idLookup[i] )
- {
- ++vectorFontId;
- return true;
- }
- }
-
- return false;
-}
-
-FontId VectorFontCache::CreateFont( const string& url )
-{
- FontId id( 0 );
-
- // Create & cache new font face
- FT_Face face;
- int error = FT_New_Face( mImpl->mFreeTypeLibrary,
- url.c_str(),
- 0,
- &face );
-
- if( FT_Err_Ok == error )
- {
- mImpl->mIdLookup.push_back( url );
- id = mImpl->mIdLookup.size();
-
- VectorFont* newFont = new VectorFont( face );
- mImpl->mVectorFonts.push_back( newFont );
-
- DALI_ASSERT_DEBUG( mImpl->mIdLookup.size() == mImpl->mVectorFonts.size() );
- }
-
- return id;
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-# Add local source files here:
-
-static_libraries_libunibreak_src_files = \
- $(static_libraries_libunibreak_src_dir)/linebreak.c \
- $(static_libraries_libunibreak_src_dir)/linebreakdata.c \
- $(static_libraries_libunibreak_src_dir)/linebreakdef.c \
- $(static_libraries_libunibreak_src_dir)/wordbreak.c
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "bidirectional-support-impl.h"
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-// EXTERNAL INCLUDES
-#include <memory.h>
-#include <fribidi/fribidi.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-namespace
-{
- typedef unsigned char BidiDirection;
-
- // Internal charcter's direction.
- const BidiDirection LEFT_TO_RIGHT = 0u;
- const BidiDirection NEUTRAL = 1u;
- const BidiDirection RIGHT_TO_LEFT = 2u;
-
- /**
- * @param[in] paragraphDirection The FriBiDi paragraph's direction.
- *
- * @return Whether the paragraph is right to left.
- */
- bool GetBidiParagraphDirection( FriBidiParType paragraphDirection )
- {
- switch( paragraphDirection )
- {
- case FRIBIDI_PAR_RTL: // Right-To-Left paragraph.
- case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph.
- {
- return true;
- }
- case FRIBIDI_PAR_LTR: // Left-To-Right paragraph.
- case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph.
- case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph.
- {
- return false;
- }
- }
-
- return false;
- }
-
- BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection )
- {
- switch( characterDirection )
- {
- case FRIBIDI_TYPE_LTR: // Left-To-Right letter.
- case FRIBIDI_TYPE_EN: // European Numeral.
- case FRIBIDI_TYPE_AN: // Arabic Numeral.
- case FRIBIDI_TYPE_ES: // European number Separator.
- case FRIBIDI_TYPE_ET: // European number Terminator.
- {
- return LEFT_TO_RIGHT;
- }
- case FRIBIDI_TYPE_RTL: // Right-To-Left letter.
- case FRIBIDI_TYPE_AL: // Arabic Letter.
- {
- return RIGHT_TO_LEFT;
- }
- }
-
- return NEUTRAL;
- }
-}
-
-struct BidirectionalSupport::Plugin
-{
- /**
- * Stores bidirectional info per paragraph.
- */
- struct BidirectionalInfo
- {
- FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...)
- FriBidiLevel* embeddedLevels; ///< Embedded levels.
- FriBidiParType paragraphDirection; ///< The paragraph's direction.
- };
-
- Plugin()
- : mParagraphBidirectionalInfo(),
- mFreeIndices()
- {}
-
- ~Plugin()
- {
- // free all resources.
- for( Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin(),
- endIt = mParagraphBidirectionalInfo.End();
- it != endIt;
- ++it )
- {
- BidirectionalInfo* info = *it;
-
- free( info->embeddedLevels );
- free( info->characterTypes );
- delete info;
- }
- }
-
- BidiInfoIndex CreateInfo( const Character* const paragraph,
- Length numberOfCharacters )
- {
- // Reserve memory for the paragraph's bidirectional info.
- BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo();
-
- bidirectionalInfo->characterTypes = reinterpret_cast<FriBidiCharType*>( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) );
- if( !bidirectionalInfo->characterTypes )
- {
- delete bidirectionalInfo;
- return 0;
- }
-
- bidirectionalInfo->embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) );
- if( !bidirectionalInfo->embeddedLevels )
- {
- free( bidirectionalInfo->characterTypes );
- delete bidirectionalInfo;
- return 0;
- }
-
- // Retrieve the type of each character..
- fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes );
-
- // Retrieve the paragraph's direction.
- bidirectionalInfo->paragraphDirection = fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters );
-
- // Retrieve the embedding levels.
- fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels );
-
- // Store the bidirectional info and return the index.
- BidiInfoIndex index = 0u;
- if( 0u != mFreeIndices.Count() )
- {
- Vector<BidiInfoIndex>::Iterator it = mFreeIndices.End() - 1u;
-
- index = *it;
-
- mFreeIndices.Remove( it );
-
- *( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo;
- }
- else
- {
- index = static_cast<BidiInfoIndex>( mParagraphBidirectionalInfo.Count() );
-
- mParagraphBidirectionalInfo.PushBack( bidirectionalInfo );
- }
-
- return index;
- }
-
- void DestroyInfo( BidiInfoIndex bidiInfoIndex )
- {
- if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() )
- {
- return;
- }
-
- // Retrieve the paragraph's bidirectional info.
- Vector<BidirectionalInfo*>::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex;
- BidirectionalInfo* bidirectionalInfo = *it;
-
- if( NULL != bidirectionalInfo )
- {
- // Free resources and destroy the container.
- free( bidirectionalInfo->embeddedLevels );
- free( bidirectionalInfo->characterTypes );
- delete bidirectionalInfo;
-
- *it = NULL;
- }
-
- // Add the index to the free indices vector.
- mFreeIndices.PushBack( bidiInfoIndex );
- }
-
- void Reorder( BidiInfoIndex bidiInfoIndex,
- CharacterIndex firstCharacterIndex,
- Length numberOfCharacters,
- CharacterIndex* visualToLogicalMap )
- {
- const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC;
-
- // Retrieve the paragraph's bidirectional info.
- const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
-
- // Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table.
- for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
- {
- visualToLogicalMap[ index ] = index;
- }
-
- // Copy embedded levels as fribidi_reorder_line() may change them.
- const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel );
- FriBidiLevel* embeddedLevels = reinterpret_cast<FriBidiLevel*>( malloc( embeddedLevelsSize ) );
- if( embeddedLevels )
- {
- memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize );
-
- // Reorder the line.
- fribidi_reorder_line( flags,
- bidirectionalInfo->characterTypes + firstCharacterIndex,
- numberOfCharacters,
- 0u,
- bidirectionalInfo->paragraphDirection,
- embeddedLevels,
- NULL,
- reinterpret_cast<FriBidiStrIndex*>( visualToLogicalMap ) );
-
- // Free resources.
- free( embeddedLevels );
- }
- }
-
- bool GetMirroredText( Character* text,
- CharacterDirection* directions,
- Length numberOfCharacters ) const
- {
- bool updated = false;
-
- for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
- {
- // Get a reference to the character inside the text.
- Character& character = *( text + index );
-
- // Retrieve the mirrored character.
- FriBidiChar mirroredCharacter = character;
- bool mirrored = false;
- if( *( directions + index ) )
- {
- mirrored = fribidi_get_mirror_char( character, &mirroredCharacter );
- }
- updated = updated || mirrored;
-
- // Update the character inside the text.
- character = mirroredCharacter;
- }
-
- return updated;
- }
-
- bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
- {
- // Retrieve the paragraph's bidirectional info.
- const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
-
- return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
- }
-
- void GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
- CharacterDirection* directions,
- Length numberOfCharacters )
- {
- const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex );
-
- const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection );
- CharacterDirection previousDirection = paragraphDirection;
-
- for( CharacterIndex index = 0u; index < numberOfCharacters; ++index )
- {
- CharacterDirection& characterDirection = *( directions + index );
- characterDirection = false;
-
- // Get the bidi direction.
- const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) );
-
- if( RIGHT_TO_LEFT == bidiDirection )
- {
- characterDirection = true;
- }
- else if( NEUTRAL == bidiDirection )
- {
- // For neutral characters it check's the next and previous directions.
- // If they are equals set that direction. If they are not, sets the paragraph's direction.
- // If there is no next, sets the paragraph's direction.
-
- CharacterDirection nextDirection = paragraphDirection;
-
- // Look for the next non-neutral character.
- Length nextIndex = index + 1u;
- for( ; nextIndex < numberOfCharacters; ++nextIndex )
- {
- BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) );
- if( nextBidiDirection != NEUTRAL )
- {
- nextDirection = RIGHT_TO_LEFT == nextBidiDirection;
- break;
- }
- }
-
- // Calculate the direction for all the neutral characters.
- characterDirection = previousDirection == nextDirection ? previousDirection : paragraphDirection;
-
- // Set the direction to all the neutral characters.
- ++index;
- for( ; index < nextIndex; ++index )
- {
- CharacterDirection& nextCharacterDirection = *( directions + index );
- nextCharacterDirection = characterDirection;
- }
-
- // Set the direction of the next non-neutral character.
- if( nextIndex < numberOfCharacters )
- {
- *( directions + nextIndex ) = nextDirection;
- }
- }
-
- previousDirection = characterDirection;
- }
- }
-
- Vector<BidirectionalInfo*> mParagraphBidirectionalInfo; ///< Stores the bidirectional info per paragraph.
- Vector<BidiInfoIndex> mFreeIndices; ///< Stores indices of free positions in the bidirectional info vector.
-};
-
-BidirectionalSupport::BidirectionalSupport()
-: mPlugin( NULL )
-{
-}
-
-BidirectionalSupport::~BidirectionalSupport()
-{
- delete mPlugin;
-}
-
-TextAbstraction::BidirectionalSupport BidirectionalSupport::Get()
-{
- TextAbstraction::BidirectionalSupport bidirectionalSupportHandle;
-
- SingletonService service( SingletonService::Get() );
- if( service )
- {
- // Check whether the singleton is already created
- BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) );
- if(handle)
- {
- // If so, downcast the handle
- BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() );
- bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl );
- }
- else // create and register the object
- {
- bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport );
- service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle );
- }
- }
-
- return bidirectionalSupportHandle;
-}
-
-BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph,
- Length numberOfCharacters )
-{
- CreatePlugin();
-
- return mPlugin->CreateInfo( paragraph,
- numberOfCharacters );
-}
-
-void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex )
-{
- CreatePlugin();
-
- mPlugin->DestroyInfo( bidiInfoIndex );
-}
-
-void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex,
- CharacterIndex firstCharacterIndex,
- Length numberOfCharacters,
- CharacterIndex* visualToLogicalMap )
-{
- CreatePlugin();
-
- mPlugin->Reorder( bidiInfoIndex,
- firstCharacterIndex,
- numberOfCharacters,
- visualToLogicalMap );
-}
-
-bool BidirectionalSupport::GetMirroredText( Character* text,
- CharacterDirection* directions,
- Length numberOfCharacters )
-{
- CreatePlugin();
-
- return mPlugin->GetMirroredText( text, directions, numberOfCharacters );
-}
-
-bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const
-{
- if( !mPlugin )
- {
- return false;
- }
-
- return mPlugin->GetParagraphDirection( bidiInfoIndex );
-}
-
-void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex,
- CharacterDirection* directions,
- Length numberOfCharacters )
-{
- CreatePlugin();
-
- mPlugin->GetCharactersDirection( bidiInfoIndex,
- directions,
- numberOfCharacters );
-}
-
-void BidirectionalSupport::CreatePlugin()
-{
- if( !mPlugin )
- {
- mPlugin = new Plugin();
- }
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "font-client-helper.h"
-
-// INTERNAL INCLUDES
-
-#include <dali/integration-api/debug.h>
-
-namespace
-{
-#if defined(DEBUG_ENABLED)
-Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT_VALUE_TO_INDEX");
-#endif
-}
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-int ValueToIndex( int value, const int* const table, unsigned int maxIndex )
-{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->FontClient::Plugin::ValueToIndex value(%d)\n", value);
-
- if( NULL == table )
- {
- // Return an invalid index if there is no table.
- return -1;
- }
-
- if( value <= table[0] )
- {
- return 0;
- }
-
- if( value >= table[maxIndex] )
- {
- return maxIndex;
- }
-
- for( unsigned int index = 0u; index < maxIndex; ++index )
- {
- const int v1 = table[index];
- const unsigned int indexPlus = index + 1u;
- const int v2 = table[indexPlus];
- if( ( v1 < value ) && ( value <= v2 ) )
- {
- const int result = ( ( v1 > 0 ) && ( ( value - v1 ) < ( v2 - value ) ) ) ? index : indexPlus;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex result(%d)\n", result );
- return result;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex exit 0 <-- \n");
-
- return 0;
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/internal/text-abstraction/font-client-impl.h>
-
-// EXTERNAL INCLUDES
-#ifndef DALI_PROFILE_UBUNTU
-#include <vconf.h>
-#endif
-
-// INTERNAL INCLUDES
-#include <singleton-service.h>
-#include <dali/internal/text-abstraction/font-client-plugin-impl.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-FontClient::FontClient()
-: mPlugin( NULL ),
- mDpiHorizontal( 0 ),
- mDpiVertical( 0 )
-{
-}
-
-FontClient::~FontClient()
-{
- delete mPlugin;
-}
-
-Dali::TextAbstraction::FontClient FontClient::Get()
-{
- Dali::TextAbstraction::FontClient fontClientHandle;
-
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::TextAbstraction::FontClient ) );
- if(handle)
- {
- // If so, downcast the handle
- FontClient* impl = dynamic_cast< Dali::TextAbstraction::Internal::FontClient* >( handle.GetObjectPtr() );
- fontClientHandle = Dali::TextAbstraction::FontClient( impl );
- }
- else // create and register the object
- {
- fontClientHandle = Dali::TextAbstraction::FontClient( new FontClient );
- service.Register( typeid( fontClientHandle ), fontClientHandle );
- }
- }
-
- return fontClientHandle;
-}
-
-void FontClient::SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi )
-{
- mDpiHorizontal = horizontalDpi;
- mDpiVertical = verticalDpi;
-
- // Allow DPI to be set without loading plugin
- if( mPlugin )
- {
- mPlugin->SetDpi( horizontalDpi, verticalDpi );
- }
-}
-
-void FontClient::GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi )
-{
- horizontalDpi = mDpiHorizontal;
- verticalDpi = mDpiVertical;
-}
-
-int FontClient::GetDefaultFontSize()
-{
- int fontSize( -1 );
-
-#ifndef DALI_PROFILE_UBUNTU
- vconf_get_int( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, &fontSize );
-#endif // DALI_PROFILE_UBUNTU
-
- return fontSize;
-}
-
-void FontClient::ResetSystemDefaults()
-{
- CreatePlugin();
-
- mPlugin->ResetSystemDefaults();
-}
-
-void FontClient::GetDefaultFonts( FontList& defaultFonts )
-{
- CreatePlugin();
-
- mPlugin->GetDefaultFonts( defaultFonts );
-}
-
-void FontClient::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
-{
- CreatePlugin();
-
- mPlugin->GetDefaultPlatformFontDescription( fontDescription );
-}
-
-void FontClient::GetDescription( FontId id, FontDescription& fontDescription )
-{
- CreatePlugin();
-
- mPlugin->GetDescription( id, fontDescription );
-}
-
-PointSize26Dot6 FontClient::GetPointSize( FontId id )
-{
- CreatePlugin();
-
- return mPlugin->GetPointSize( id );
-}
-
-bool FontClient::IsCharacterSupportedByFont( FontId fontId, Character character )
-{
- CreatePlugin();
-
- return mPlugin->IsCharacterSupportedByFont( fontId, character );
-}
-
-void FontClient::GetSystemFonts( FontList& systemFonts )
-{
- CreatePlugin();
-
- mPlugin->GetSystemFonts( systemFonts );
-}
-
-FontId FontClient::FindDefaultFont( Character charcode,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- CreatePlugin();
-
- return mPlugin->FindDefaultFont( charcode,
- requestedPointSize,
- preferColor );
-}
-
-FontId FontClient::FindFallbackFont( Character charcode,
- const FontDescription& preferredFontDescription,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- CreatePlugin();
-
- return mPlugin->FindFallbackFont( charcode,
- preferredFontDescription,
- requestedPointSize,
- preferColor );
-}
-
-bool FontClient::IsScalable( const FontPath& path )
-{
- CreatePlugin();
-
- return mPlugin->IsScalable( path );
-}
-
-bool FontClient::IsScalable( const FontDescription& fontDescription )
-{
- CreatePlugin();
-
- return mPlugin->IsScalable( fontDescription );
-}
-
-void FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes )
-{
- CreatePlugin();
-
- mPlugin->GetFixedSizes( path, sizes );
-}
-
-void FontClient::GetFixedSizes( const FontDescription& fontDescription,
- Dali::Vector< PointSize26Dot6 >& sizes )
-{
- CreatePlugin();
-
- mPlugin->GetFixedSizes( fontDescription, sizes );
-}
-
-FontId FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
-{
- CreatePlugin();
-
- return mPlugin->GetFontId( path,
- requestedPointSize,
- faceIndex,
- true );
-}
-
-FontId FontClient::GetFontId( const FontDescription& fontDescription,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex )
-{
- CreatePlugin();
-
- return mPlugin->GetFontId( fontDescription,
- requestedPointSize,
- faceIndex );
-}
-
-void FontClient::GetFontMetrics( FontId fontId, FontMetrics& metrics )
-{
- CreatePlugin();
-
- return mPlugin->GetFontMetrics( fontId, metrics );
-}
-
-GlyphIndex FontClient::GetGlyphIndex( FontId fontId, Character charcode )
-{
- CreatePlugin();
-
- return mPlugin->GetGlyphIndex( fontId, charcode );
-}
-
-bool FontClient::GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal )
-{
- CreatePlugin();
-
- return mPlugin->GetGlyphMetrics( array, size, type, horizontal );
-}
-
-void FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
-{
- CreatePlugin();
-
- mPlugin->CreateBitmap( fontId, glyphIndex, data, outlineWidth );
-}
-
-PixelData FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
-{
- CreatePlugin();
-
- return mPlugin->CreateBitmap( fontId, glyphIndex, outlineWidth );
-}
-
-void FontClient::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
-{
- CreatePlugin();
-
- return mPlugin->CreateVectorBlob( fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
-}
-
-const GlyphInfo& FontClient::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
-{
- CreatePlugin();
-
- return mPlugin->GetEllipsisGlyph( requestedPointSize );
-}
-
-bool FontClient::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
-{
- CreatePlugin();
-
- return mPlugin->IsColorGlyph( fontId, glyphIndex );
-}
-
-void FontClient::CreatePlugin()
-{
- if( !mPlugin )
- {
- mPlugin = new Plugin( mDpiHorizontal, mDpiVertical );
- }
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali/internal/text-abstraction/font-client-plugin-impl.h>
-
-// INTERNAL INCLUDES
-#include <dali/devel-api/text-abstraction/font-list.h>
-#include <dali/public-api/common/dali-vector.h>
-#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/platform-abstraction.h>
-#include <dali/internal/text-abstraction/font-client-helper.h>
-#include <platform-abstractions/portable/image-operations.h>
-#include <adaptor-impl.h>
-
-// EXTERNAL INCLUDES
-#include <fontconfig/fontconfig.h>
-
-namespace
-{
-
-#if defined(DEBUG_ENABLED)
-Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT");
-#endif
-
-/**
- * Conversion from Fractional26.6 to float
- */
-const float FROM_266 = 1.0f / 64.0f;
-const float POINTS_PER_INCH = 72.f;
-
-const std::string FONT_FORMAT( "TrueType" );
-const std::string DEFAULT_FONT_FAMILY_NAME( "Tizen" );
-const int DEFAULT_FONT_WIDTH = 100; // normal
-const int DEFAULT_FONT_WEIGHT = 80; // normal
-const int DEFAULT_FONT_SLANT = 0; // normal
-
-const uint32_t ELLIPSIS_CHARACTER = 0x2026;
-
-// http://www.freedesktop.org/software/fontconfig/fontconfig-user.html
-
-// NONE -1 --> DEFAULT_FONT_WIDTH (NORMAL) will be used.
-// ULTRA_CONDENSED 50
-// EXTRA_CONDENSED 63
-// CONDENSED 75
-// SEMI_CONDENSED 87
-// NORMAL 100
-// SEMI_EXPANDED 113
-// EXPANDED 125
-// EXTRA_EXPANDED 150
-// ULTRA_EXPANDED 200
-const int FONT_WIDTH_TYPE_TO_INT[] = { -1, 50, 63, 75, 87, 100, 113, 125, 150, 200 };
-const unsigned int NUM_FONT_WIDTH_TYPE = sizeof( FONT_WIDTH_TYPE_TO_INT ) / sizeof( int );
-
-// NONE -1 --> DEFAULT_FONT_WEIGHT (NORMAL) will be used.
-// THIN 0
-// ULTRA_LIGHT, EXTRA_LIGHT 40
-// LIGHT 50
-// DEMI_LIGHT, SEMI_LIGHT 55
-// BOOK 75
-// NORMAL, REGULAR 80
-// MEDIUM 100
-// DEMI_BOLD, SEMI_BOLD 180
-// BOLD 200
-// ULTRA_BOLD, EXTRA_BOLD 205
-// BLACK, HEAVY, EXTRA_BLACK 210
-const int FONT_WEIGHT_TYPE_TO_INT[] = { -1, 0, 40, 50, 55, 75, 80, 100, 180, 200, 205, 210 };
-const unsigned int NUM_FONT_WEIGHT_TYPE = sizeof( FONT_WEIGHT_TYPE_TO_INT ) / sizeof( int );
-
-// NONE -1 --> DEFAULT_FONT_SLANT (NORMAL) will be used.
-// NORMAL, ROMAN 0
-// ITALIC 100
-// OBLIQUE 110
-const int FONT_SLANT_TYPE_TO_INT[] = { -1, 0, 100, 110 };
-const unsigned int NUM_FONT_SLANT_TYPE = sizeof( FONT_SLANT_TYPE_TO_INT ) / sizeof( int );
-
-} // namespace
-
-using Dali::Vector;
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-/**
- * @brief Returns the FontWidth's enum index for the given width value.
- *
- * @param[in] width The width value.
- *
- * @return The FontWidth's enum index.
- */
-FontWidth::Type IntToWidthType( int width )
-{
- return static_cast<FontWidth::Type>( ValueToIndex( width, FONT_WIDTH_TYPE_TO_INT, NUM_FONT_WIDTH_TYPE - 1u ) );
-}
-
-/**
- * @brief Returns the FontWeight's enum index for the given weight value.
- *
- * @param[in] weight The weight value.
- *
- * @return The FontWeight's enum index.
- */
-FontWeight::Type IntToWeightType( int weight )
-{
- return static_cast<FontWeight::Type>( ValueToIndex( weight, FONT_WEIGHT_TYPE_TO_INT, NUM_FONT_WEIGHT_TYPE - 1u ) );
-}
-
-/**
- * @brief Returns the FontSlant's enum index for the given slant value.
- *
- * @param[in] slant The slant value.
- *
- * @return The FontSlant's enum index.
- */
-FontSlant::Type IntToSlantType( int slant )
-{
- return static_cast<FontSlant::Type>( ValueToIndex( slant, FONT_SLANT_TYPE_TO_INT, NUM_FONT_SLANT_TYPE - 1u ) );
-}
-
- FontClient::Plugin::FallbackCacheItem::FallbackCacheItem( const FontDescription& font, FontList* fallbackFonts, CharacterSetList* characterSets )
-: fontDescription( font ),
- fallbackFonts( fallbackFonts ),
- characterSets( characterSets )
-{
-}
-
-FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem( const FontDescription& fontDescription,
- FontDescriptionId index )
-: fontDescription( fontDescription ),
- index( index )
-{
-}
-
-FontClient::Plugin::FontIdCacheItem::FontIdCacheItem( FontDescriptionId validatedFontId,
- PointSize26Dot6 requestedPointSize,
- FontId fontId )
-: validatedFontId( validatedFontId ),
- requestedPointSize( requestedPointSize ),
- fontId( fontId )
-{
-}
-
-FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace,
- const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex face,
- const FontMetrics& metrics )
-: mFreeTypeFace( ftFace ),
- mPath( path ),
- mRequestedPointSize( requestedPointSize ),
- mFaceIndex( face ),
- mMetrics( metrics ),
- mCharacterSet( NULL ),
- mFixedWidthPixels( 0.0f ),
- mFixedHeightPixels( 0.0f ),
- mVectorFontId( 0 ),
- mIsFixedSizeBitmap( false ),
- mHasColorTables( false )
-{
-}
-
-FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace,
- const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex face,
- const FontMetrics& metrics,
- float fixedWidth,
- float fixedHeight,
- bool hasColorTables )
-: mFreeTypeFace( ftFace ),
- mPath( path ),
- mRequestedPointSize( requestedPointSize ),
- mFaceIndex( face ),
- mMetrics( metrics ),
- mCharacterSet( NULL ),
- mFixedWidthPixels( fixedWidth ),
- mFixedHeightPixels( fixedHeight ),
- mVectorFontId( 0 ),
- mIsFixedSizeBitmap( true ),
- mHasColorTables( hasColorTables )
-{
-}
-
-FontClient::Plugin::Plugin( unsigned int horizontalDpi,
- unsigned int verticalDpi )
-: mFreeTypeLibrary( NULL ),
- mDpiHorizontal( horizontalDpi ),
- mDpiVertical( verticalDpi ),
- mDefaultFontDescription(),
- mSystemFonts(),
- mDefaultFonts(),
- mFontCache(),
- mValidatedFontCache(),
- mFontDescriptionCache( 1u ),
- mCharacterSetCache(),
- mFontIdCache(),
- mVectorFontCache( NULL ),
- mEllipsisCache(),
- mDefaultFontDescriptionCached( false )
-{
- mCharacterSetCache.Resize( 1u );
-
- int error = FT_Init_FreeType( &mFreeTypeLibrary );
- if( FT_Err_Ok != error )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Init error: %d\n", error );
- }
-
-#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
- mVectorFontCache = new VectorFontCache( mFreeTypeLibrary );
-#endif
-}
-
-FontClient::Plugin::~Plugin()
-{
- for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end();
- it != endIt;
- ++it )
- {
- FallbackCacheItem& item = *it;
-
- if( item.fallbackFonts )
- {
- delete item.fallbackFonts;
- delete item.characterSets;
- item.fallbackFonts = NULL;
- item.characterSets = NULL;
- }
- }
-
-#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
- delete mVectorFontCache;
-#endif
-
- FT_Done_FreeType( mFreeTypeLibrary );
-}
-
-void FontClient::Plugin::SetDpi( unsigned int horizontalDpi,
- unsigned int verticalDpi )
-{
- mDpiHorizontal = horizontalDpi;
- mDpiVertical = verticalDpi;
-}
-
-void FontClient::Plugin::ResetSystemDefaults()
-{
- mDefaultFontDescriptionCached = false;
-}
-
-void FontClient::Plugin::SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::SetFontList\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
-
- fontList.clear();
-
- FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
-
- FcResult result = FcResultMatch;
-
- // Match the pattern.
- FcFontSet* fontSet = FcFontSort( NULL /* use default configure */,
- fontFamilyPattern,
- false /* don't trim */,
- NULL,
- &result );
-
- if( NULL != fontSet )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts found : [%d]\n", fontSet->nfont );
- // Reserve some space to avoid reallocations.
- fontList.reserve( fontSet->nfont );
-
- for( int i = 0u; i < fontSet->nfont; ++i )
- {
- FcPattern* fontPattern = fontSet->fonts[i];
-
- FontPath path;
-
- // Skip fonts with no path
- if( GetFcString( fontPattern, FC_FILE, path ) )
- {
- FcCharSet* characterSet = NULL;
- FcPatternGetCharSet( fontPattern, FC_CHARSET, 0u, &characterSet );
-
- characterSetList.PushBack( characterSet );
- fontList.push_back( FontDescription() );
- FontDescription& newFontDescription = fontList.back();
-
- newFontDescription.path = path;
-
- int width = 0;
- int weight = 0;
- int slant = 0;
- GetFcString( fontPattern, FC_FAMILY, newFontDescription.family );
- GetFcInt( fontPattern, FC_WIDTH, width );
- GetFcInt( fontPattern, FC_WEIGHT, weight );
- GetFcInt( fontPattern, FC_SLANT, slant );
- newFontDescription.width = IntToWidthType( width );
- newFontDescription.weight = IntToWeightType( weight );
- newFontDescription.slant = IntToSlantType( slant );
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", newFontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", newFontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[newFontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[newFontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[newFontDescription.slant] );
- }
- }
-
- FcFontSetDestroy( fontSet );
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " No fonts found.\n" );
- }
-
- FcPatternDestroy( fontFamilyPattern );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::SetFontList\n" );
-}
-
-void FontClient::Plugin::GetDefaultFonts( FontList& defaultFonts )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultFonts\n" );
-
- if( mDefaultFonts.empty() )
- {
- FontDescription fontDescription;
- fontDescription.family = DEFAULT_FONT_FAMILY_NAME; // todo This could be set to the Platform font
- fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH );
- fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT );
- fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT );
- SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets );
- }
-
- defaultFonts = mDefaultFonts;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " number of default fonts : [%d]\n", mDefaultFonts.size() );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultFonts\n" );
-}
-
-void FontClient::Plugin::GetDefaultPlatformFontDescription( FontDescription& fontDescription )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultPlatformFontDescription\n");
-
- if( !mDefaultFontDescriptionCached )
- {
- // Clear any font config stored info in the caches.
- mDefaultFontCharacterSets.Clear();
- mCharacterSetCache.Clear();
-
- for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end(); it != endIt; ++it )
- {
- FallbackCacheItem& item = *it;
-
- item.characterSets->Clear();
- }
-
- for( std::vector<FontFaceCacheItem>::iterator it = mFontCache.begin(), endIt = mFontCache.end(); it != endIt; ++it )
- {
- FontFaceCacheItem& item = *it;
-
- // Set the character set pointer as null. Will be created again the next time IsCharacterSupportedByFont()
- item.mCharacterSet = NULL;
- }
-
- // FcInitBringUptoDate did not seem to reload config file as was still getting old default font.
- FcInitReinitialize();
-
- FcPattern* matchPattern = FcPatternCreate();
-
- if( matchPattern )
- {
- FcConfigSubstitute( NULL, matchPattern, FcMatchPattern );
- FcDefaultSubstitute( matchPattern );
-
- FcCharSet* characterSet = NULL;
- MatchFontDescriptionToPattern( matchPattern, mDefaultFontDescription, &characterSet );
- FcPatternDestroy( matchPattern );
- }
-
- // Create again the character sets as they are not valid after FcInitReinitialize()
-
- for( FontList::const_iterator it = mDefaultFonts.begin(), endIt = mDefaultFonts.end(); it != endIt; ++it )
- {
- const FontDescription& description = *it;
-
- mDefaultFontCharacterSets.PushBack( CreateCharacterSetFromDescription( description ) );
- }
-
- for( FontList::const_iterator it = mFontDescriptionCache.begin(), endIt = mFontDescriptionCache.end(); it != endIt; ++it )
- {
- const FontDescription& description = *it;
-
- mCharacterSetCache.PushBack( CreateCharacterSetFromDescription( description ) );
- }
-
- for( std::vector<FallbackCacheItem>::iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end(); it != endIt; ++it )
- {
- FallbackCacheItem& item = *it;
-
- if( NULL != item.fallbackFonts )
- {
- if( NULL == item.characterSets )
- {
- item.characterSets = new CharacterSetList;
- }
-
- for( FontList::const_iterator flIt = item.fallbackFonts->begin(), flEndIt = item.fallbackFonts->end(); flIt != flEndIt; ++flIt )
- {
- const FontDescription& description = *flIt;
- item.characterSets->PushBack( CreateCharacterSetFromDescription( description ) );
- }
- }
- }
-
- mDefaultFontDescriptionCached = true;
- }
-
- fontDescription.path = mDefaultFontDescription.path;
- fontDescription.family = mDefaultFontDescription.family;
- fontDescription.width = mDefaultFontDescription.width;
- fontDescription.weight = mDefaultFontDescription.weight;
- fontDescription.slant = mDefaultFontDescription.slant;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultPlatformFontDescription\n");
-}
-
-void FontClient::Plugin::GetSystemFonts( FontList& systemFonts )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetSystemFonts\n");
-
- if( mSystemFonts.empty() )
- {
- InitSystemFonts();
- }
-
- systemFonts = mSystemFonts;
- DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : [%d]\n", mSystemFonts.size() );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetSystemFonts\n");
-}
-
-void FontClient::Plugin::GetDescription( FontId id,
- FontDescription& fontDescription ) const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDescription\n");
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
-
- for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
- endIt = mFontIdCache.end();
- it != endIt;
- ++it )
- {
- const FontIdCacheItem& item = *it;
-
- if( item.fontId == id )
- {
- fontDescription = *( mFontDescriptionCache.begin() + item.validatedFontId );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n");
- return;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " No description found for the font ID %d\n", id );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n");
-}
-
-PointSize26Dot6 FontClient::Plugin::GetPointSize( FontId id )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetPointSize\n");
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
- const FontId index = id - 1u;
-
- if( ( id > 0u ) &&
- ( index < mFontCache.size() ) )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " point size : %d\n", ( *( mFontCache.begin() + index ) ).mRequestedPointSize );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n");
- return ( *( mFontCache.begin() + index ) ).mRequestedPointSize;
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font ID %d\n", id );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " default point size : %d\n", TextAbstraction::FontClient::DEFAULT_POINT_SIZE );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n");
- return TextAbstraction::FontClient::DEFAULT_POINT_SIZE;
-}
-
-bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character character )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::IsCharacterSupportedByFont\n");
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character );
-
- if( ( fontId < 1u ) || ( fontId > mFontCache.size() ) )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font id. Number of items in the cache: %d\n",mFontCache.size());
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n");
- return false;
- }
-
- --fontId;
-
- bool isSupported = false;
-
- FontFaceCacheItem& cacheItem = mFontCache[fontId];
-
- if( NULL == cacheItem.mCharacterSet )
- {
- // Create again the character set.
- // It can be null if the ResetSystemDefaults() method has been called.
-
- FontDescription description;
- description.path = cacheItem.mPath;
- description.family = FontFamily( cacheItem.mFreeTypeFace->family_name );
- description.weight = FontWeight::NONE;
- description.width = FontWidth::NONE;
- description.slant = FontSlant::NONE;
-
- // Note FreeType doesn't give too much info to build a proper font style.
- if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC )
- {
- description.slant = FontSlant::ITALIC;
- }
- if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD )
- {
- description.weight = FontWeight::BOLD;
- }
-
- cacheItem.mCharacterSet = CreateCharacterSetFromDescription( description );
- }
-
- isSupported = FcCharSetHasChar( cacheItem.mCharacterSet, character );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " is supported : %s\n", (isSupported ? "true" : "false") );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n");
- return isSupported;
-}
-
-FontId FontClient::Plugin::FindFontForCharacter( const FontList& fontList,
- const CharacterSetList& characterSetList,
- Character character,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- DALI_ASSERT_DEBUG( ( fontList.size() == characterSetList.Count() ) && "FontClient::Plugin::FindFontForCharacter. Different number of fonts and character sets." );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFontForCharacter\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
- DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
-
- FontId fontId = 0u;
- bool foundColor = false;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts : %d\n", fontList.size() );
-
- // Traverse the list of fonts.
- // Check for each font if supports the character.
- for( unsigned int index = 0u, numberOfFonts = fontList.size(); index < numberOfFonts; ++index )
- {
- const FontDescription& description = fontList[index];
- const FcCharSet* const characterSet = characterSetList[index];
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", description.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] );
-
- bool foundInRanges = false;
- if( NULL != characterSet )
- {
- foundInRanges = FcCharSetHasChar( characterSet, character );
- }
-
- if( foundInRanges )
- {
- fontId = GetFontId( description,
- requestedPointSize,
- 0u );
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " font id : %d\n", fontId );
-
- if( preferColor )
- {
- if( ( fontId > 0 ) &&
- ( fontId - 1u < mFontCache.size() ) )
- {
- const FontFaceCacheItem& item = mFontCache[fontId - 1u];
-
- foundColor = item.mHasColorTables;
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " foundColor : %s\n", ( foundColor ? "true" : "false" ) );
- }
-
- // Keep going unless we prefer a different (color) font.
- if( !preferColor || foundColor )
- {
- break;
- }
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFontForCharacter\n" );
- return fontId;
-}
-
-FontId FontClient::Plugin::FindDefaultFont( Character charcode,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindDefaultFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
- DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
-
- FontId fontId(0);
-
- // Create the list of default fonts if it has not been created.
- if( mDefaultFonts.empty() )
- {
- FontDescription fontDescription;
- fontDescription.family = DEFAULT_FONT_FAMILY_NAME;
- fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH );
- fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT );
- fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT );
-
- SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets );
- }
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of default fonts : %d\n", mDefaultFonts.size() );
-
-
- // Traverse the list of default fonts.
- // Check for each default font if supports the character.
- fontId = FindFontForCharacter( mDefaultFonts, mDefaultFontCharacterSets, charcode, requestedPointSize, preferColor );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindDefaultFont\n" );
-
- return fontId;
-}
-
-FontId FontClient::Plugin::FindFallbackFont( Character charcode,
- const FontDescription& preferredFontDescription,
- PointSize26Dot6 requestedPointSize,
- bool preferColor )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
- DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) );
-
- // The font id to be returned.
- FontId fontId = 0u;
-
- FontDescription fontDescription;
-
- // Fill the font description with the preferred font description and complete with the defaults.
- fontDescription.family = preferredFontDescription.family.empty() ? DEFAULT_FONT_FAMILY_NAME : preferredFontDescription.family;
- fontDescription.weight = ( ( FontWeight::NONE == preferredFontDescription.weight ) ? IntToWeightType( DEFAULT_FONT_WEIGHT ) : preferredFontDescription.weight );
- fontDescription.width = ( ( FontWidth::NONE == preferredFontDescription.width ) ? IntToWidthType( DEFAULT_FONT_WIDTH ) : preferredFontDescription.width );
- fontDescription.slant = ( ( FontSlant::NONE == preferredFontDescription.slant ) ? IntToSlantType( DEFAULT_FONT_SLANT ) : preferredFontDescription.slant );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " preferredFontDescription --> fontDescription\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " [%s] --> [%s]\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWeight::Name[preferredFontDescription.weight], FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWidth::Name[preferredFontDescription.width], FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontSlant::Name[preferredFontDescription.slant], FontSlant::Name[fontDescription.slant] );
-
- // Check first if the font's description has been queried before.
- FontList* fontList = NULL;
- CharacterSetList* characterSetList = NULL;
-
- if( !FindFallbackFontList( fontDescription, fontList, characterSetList ) )
- {
- fontList = new FontList;
- characterSetList = new CharacterSetList;
-
- SetFontList( fontDescription, *fontList, *characterSetList );
-
- // Add the font-list to the cache.
- mFallbackCache.push_back( FallbackCacheItem( fontDescription, fontList, characterSetList ) );
- }
-
- if( fontList && characterSetList )
- {
- fontId = FindFontForCharacter( *fontList, *characterSetList, charcode, requestedPointSize, preferColor );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFont\n");
- return fontId;
-}
-
-FontId FontClient::Plugin::GetFontId( const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex,
- bool cacheDescription )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
-
- FontId id( 0 );
-
- if( NULL != mFreeTypeLibrary )
- {
- FontId foundId(0);
- if( FindFont( path, requestedPointSize, faceIndex, foundId ) )
- {
- id = foundId;
- }
- else
- {
- id = CreateFont( path, requestedPointSize, faceIndex, cacheDescription );
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" );
-
- return id;
-}
-
-FontId FontClient::Plugin::GetFontId( const FontDescription& fontDescription,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
-
- // This method uses three vectors which caches:
- // * Pairs of non validated font descriptions and an index to a vector with paths to font file names.
- // * The path to font file names.
- // * The font ids of pairs 'font point size, index to the vector with paths to font file names'.
-
- // 1) Checks in the cache if the font's description has been validated before.
- // If it was it gets an index to the vector with paths to font file names. Otherwise,
- // retrieves using font config a path to a font file name which matches with the
- // font's description. The path is stored in the cache.
- //
- // 2) Checks in the cache if the pair 'font point size, index to the vector with paths to
- // font file names' exists. If exists, it gets the font id. If it doesn't it calls
- // the GetFontId() method with the path to the font file name and the point size to
- // get the font id.
-
- // The font id to be returned.
- FontId fontId = 0u;
-
- // Check first if the font's description have been validated before.
- FontDescriptionId validatedFontId = 0u;
-
- if( !FindValidatedFont( fontDescription,
- validatedFontId ) )
- {
- // Use font config to validate the font's description.
- ValidateFont( fontDescription,
- validatedFontId );
- }
-
- // Check if exists a pair 'validatedFontId, requestedPointSize' in the cache.
- if( !FindFont( validatedFontId, requestedPointSize, fontId ) )
- {
- // Retrieve the font file name path.
- const FontDescription& description = *( mFontDescriptionCache.begin() + validatedFontId );
-
- // Retrieve the font id. Do not cache the description as it has been already cached.
- fontId = GetFontId( description.path,
- requestedPointSize,
- faceIndex,
- false );
-
- mFontCache[fontId-1u].mCharacterSet = mCharacterSetCache[validatedFontId];
-
- // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries.
- mFontIdCache.push_back( FontIdCacheItem( validatedFontId,
- requestedPointSize,
- fontId ) );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" );
-
- return fontId;
-}
-
-void FontClient::Plugin::ValidateFont( const FontDescription& fontDescription,
- FontDescriptionId& validatedFontId )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::ValidateFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
-
- // Create a font pattern.
- FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
-
- FontDescription description;
-
- FcCharSet* characterSet = NULL;
- bool matched = MatchFontDescriptionToPattern( fontFamilyPattern, description, &characterSet );
- FcPatternDestroy( fontFamilyPattern );
-
- if( matched && ( NULL != characterSet ) )
- {
- // Set the index to the vector of paths to font file names.
- validatedFontId = mFontDescriptionCache.size();
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " matched description; family : [%s]\n", description.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId );
-
- // Add the path to the cache.
- mFontDescriptionCache.push_back( description );
- mCharacterSetCache.PushBack( characterSet );
-
- // Cache the index and the matched font's description.
- FontDescriptionCacheItem item( description,
- validatedFontId );
-
- mValidatedFontCache.push_back( item );
-
- if( ( fontDescription.family != description.family ) ||
- ( fontDescription.width != description.width ) ||
- ( fontDescription.weight != description.weight ) ||
- ( fontDescription.slant != description.slant ) )
- {
- // Cache the given font's description if it's different than the matched.
- FontDescriptionCacheItem item( fontDescription,
- validatedFontId );
-
- mValidatedFontCache.push_back( item );
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " font validation failed for font [%s]\n", fontDescription.family.c_str() );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::ValidateFont\n" );
-}
-
-void FontClient::Plugin::GetFontMetrics( FontId fontId,
- FontMetrics& metrics )
-{
- if( ( fontId > 0 ) &&
- ( fontId - 1u < mFontCache.size() ) )
- {
- const FontFaceCacheItem& font = mFontCache[fontId-1];
-
- metrics = font.mMetrics;
-
- // Adjust the metrics if the fixed-size font should be down-scaled
- if( font.mIsFixedSizeBitmap )
- {
- const float desiredFixedSize = static_cast<float>( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical;
-
- if( desiredFixedSize > 0.f )
- {
- const float scaleFactor = desiredFixedSize / static_cast<float>( font.mFixedHeightPixels );
-
- metrics.ascender = floorf( metrics.ascender * scaleFactor );
- metrics.descender = floorf( metrics.descender * scaleFactor );
- metrics.height = floorf( metrics.height * scaleFactor );
- metrics.underlinePosition = floorf( metrics.underlinePosition * scaleFactor );
- metrics.underlineThickness = floorf( metrics.underlineThickness * scaleFactor );
- }
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId );
- }
-}
-
-GlyphIndex FontClient::Plugin::GetGlyphIndex( FontId fontId,
- Character charcode )
-{
- GlyphIndex index = 0u;
-
- if( ( fontId > 0u ) &&
- ( fontId - 1u < mFontCache.size() ) )
- {
- FT_Face ftFace = mFontCache[fontId-1u].mFreeTypeFace;
-
- index = FT_Get_Char_Index( ftFace, charcode );
- }
-
- return index;
-}
-
-bool FontClient::Plugin::GetGlyphMetrics( GlyphInfo* array,
- uint32_t size,
- GlyphType type,
- bool horizontal )
-{
- if( VECTOR_GLYPH == type )
- {
- return GetVectorMetrics( array, size, horizontal );
- }
-
- return GetBitmapMetrics( array, size, horizontal );
-}
-
-bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array,
- uint32_t size,
- bool horizontal )
-{
- bool success( true );
-
- for( unsigned int i=0; i<size; ++i )
- {
- GlyphInfo& glyph = array[i];
-
- FontId fontId = glyph.fontId;
-
- if( fontId > 0 &&
- fontId-1 < mFontCache.size() )
- {
- const FontFaceCacheItem& font = mFontCache[fontId-1];
-
- FT_Face ftFace = font.mFreeTypeFace;
-
-#ifdef FREETYPE_BITMAP_SUPPORT
- // Check to see if we should be loading a Fixed Size bitmap?
- if ( font.mIsFixedSizeBitmap )
- {
- int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_COLOR );
- if ( FT_Err_Ok == error )
- {
- glyph.width = font.mFixedWidthPixels;
- glyph.height = font.mFixedHeightPixels;
- glyph.advance = font.mFixedWidthPixels;
- glyph.xBearing = 0.0f;
- glyph.yBearing = font.mFixedHeightPixels;
-
- // Adjust the metrics if the fixed-size font should be down-scaled
- const float desiredFixedSize = static_cast<float>( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical;
-
- if( desiredFixedSize > 0.f )
- {
- const float scaleFactor = desiredFixedSize / static_cast<float>( font.mFixedHeightPixels );
-
- glyph.width = floorf( glyph.width * scaleFactor );
- glyph.height = floorf( glyph.height * scaleFactor );
- glyph.advance = floorf( glyph.advance * scaleFactor );
- glyph.xBearing = floorf( glyph.xBearing * scaleFactor );
- glyph.yBearing = floorf( glyph.yBearing * scaleFactor );
-
- glyph.scaleFactor = scaleFactor;
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error );
- success = false;
- }
- }
- else
-#endif
- {
- int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_DEFAULT );
-
- if( FT_Err_Ok == error )
- {
- glyph.width = static_cast< float >( ftFace->glyph->metrics.width ) * FROM_266;
- glyph.height = static_cast< float >( ftFace->glyph->metrics.height ) * FROM_266 ;
- if( horizontal )
- {
- glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingX ) * FROM_266;
- glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingY ) * FROM_266;
- }
- else
- {
- glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingX ) * FROM_266;
- glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingY ) * FROM_266;
- }
- }
- else
- {
- success = false;
- }
- }
- }
- else
- {
- success = false;
- }
- }
-
- return success;
-}
-
-bool FontClient::Plugin::GetVectorMetrics( GlyphInfo* array,
- uint32_t size,
- bool horizontal )
-{
-#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
- bool success( true );
-
- for( unsigned int i=0; i<size; ++i )
- {
- FontId fontId = array[i].fontId;
-
- if( fontId > 0 &&
- fontId-1 < mFontCache.size() )
- {
- FontFaceCacheItem& font = mFontCache[fontId-1];
-
- if( ! font.mVectorFontId )
- {
- font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath );
- }
-
- mVectorFontCache->GetGlyphMetrics( font.mVectorFontId, array[i] );
-
- // Vector metrics are in EMs, convert to pixels
- const float scale = ( static_cast<float>( font.mRequestedPointSize ) * FROM_266 ) * static_cast<float>( mDpiVertical ) / POINTS_PER_INCH;
- array[i].width *= scale;
- array[i].height *= scale;
- array[i].xBearing *= scale;
- array[i].yBearing *= scale;
- array[i].advance *= scale;
- }
- else
- {
- success = false;
- }
- }
-
- return success;
-#else
- return false;
-#endif
-}
-
-void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
-{
- if( ( fontId > 0 ) &&
- ( fontId - 1u < mFontCache.size() ) )
- {
- FT_Face ftFace = mFontCache[fontId - 1u].mFreeTypeFace;
-
- FT_Error error;
-
-#ifdef FREETYPE_BITMAP_SUPPORT
- // Check to see if this is fixed size bitmap
- if ( mFontCache[fontId - 1u].mIsFixedSizeBitmap )
- {
- error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR );
- }
- else
-#endif
- {
- error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_DEFAULT );
- }
- if( FT_Err_Ok == error )
- {
- FT_Glyph glyph;
- error = FT_Get_Glyph( ftFace->glyph, &glyph );
-
- // Convert to bitmap if necessary
- if ( FT_Err_Ok == error )
- {
- if( glyph->format != FT_GLYPH_FORMAT_BITMAP )
- {
- // Check whether we should create a bitmap for the outline
- if( glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0 )
- {
- // Set up a stroker
- FT_Stroker stroker;
- error = FT_Stroker_New(mFreeTypeLibrary, &stroker );
-
- if ( FT_Err_Ok == error )
- {
- FT_Stroker_Set( stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0 );
- error = FT_Glyph_StrokeBorder( &glyph, stroker, 0, 1 );
-
- if ( FT_Err_Ok == error )
- {
- FT_Stroker_Done( stroker );
- }
- else
- {
- DALI_LOG_ERROR( "FT_Glyph_StrokeBorder Failed with error: %d\n", error );
- }
- }
- else
- {
- DALI_LOG_ERROR( "FT_Stroker_New Failed with error: %d\n", error );
- }
- }
-
- error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 );
- if ( FT_Err_Ok == error )
- {
- FT_BitmapGlyph bitmapGlyph = reinterpret_cast< FT_BitmapGlyph >( glyph );
- ConvertBitmap( data, bitmapGlyph->bitmap );
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error );
- }
- }
- else
- {
- ConvertBitmap( data, ftFace->glyph->bitmap );
- }
-
- // Created FT_Glyph object must be released with FT_Done_Glyph
- FT_Done_Glyph( glyph );
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error );
- }
- }
-}
-
-PixelData FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
-{
- TextAbstraction::FontClient::GlyphBufferData data;
-
- CreateBitmap( fontId, glyphIndex, data, outlineWidth );
-
- return PixelData::New( data.buffer,
- data.width * data.height * Pixel::GetBytesPerPixel( data.format ),
- data.width,
- data.height,
- data.format,
- PixelData::DELETE_ARRAY );
-}
-
-void FontClient::Plugin::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight )
-{
- blob = NULL;
- blobLength = 0;
-
-#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
- if( fontId > 0 &&
- fontId-1 < mFontCache.size() )
- {
- FontFaceCacheItem& font = mFontCache[fontId-1];
-
- if( ! font.mVectorFontId )
- {
- font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath );
- }
-
- mVectorFontCache->GetVectorBlob( font.mVectorFontId, fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight );
- }
-#endif
-}
-
-const GlyphInfo& FontClient::Plugin::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetEllipsisGlyph\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize %d.\n", requestedPointSize );
-
- // First look into the cache if there is an ellipsis glyph for the requested point size.
- for( Vector<EllipsisItem>::ConstIterator it = mEllipsisCache.Begin(),
- endIt = mEllipsisCache.End();
- it != endIt;
- ++it )
- {
- const EllipsisItem& item = *it;
-
- if( fabsf( item.requestedPointSize - requestedPointSize ) < Math::MACHINE_EPSILON_1000 )
- {
- // Use the glyph in the cache.
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index );
- DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" );
-
- return item.glyph;
- }
- }
-
- // No glyph has been found. Create one.
- mEllipsisCache.PushBack( EllipsisItem() );
- EllipsisItem& item = *( mEllipsisCache.End() - 1u );
-
- item.requestedPointSize = requestedPointSize;
-
- // Find a font for the ellipsis glyph.
- item.glyph.fontId = FindDefaultFont( ELLIPSIS_CHARACTER,
- requestedPointSize,
- false );
-
- // Set the character index to access the glyph inside the font.
- item.glyph.index = FT_Get_Char_Index( mFontCache[item.glyph.fontId-1].mFreeTypeFace,
- ELLIPSIS_CHARACTER );
-
- GetBitmapMetrics( &item.glyph, 1u, true );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index );
- DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" );
-
- return item.glyph;
-}
-
-bool FontClient::Plugin::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex )
-{
- FT_Error error = -1;
-
-#ifdef FREETYPE_BITMAP_SUPPORT
- if( ( fontId > 0 ) &&
- ( fontId - 1u < mFontCache.size() ) )
- {
- const FontFaceCacheItem& item = mFontCache[fontId - 1u];
- FT_Face ftFace = item.mFreeTypeFace;
-
- // Check to see if this is fixed size bitmap
- if( item.mHasColorTables )
- {
- error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR );
- }
- }
-#endif
-
- return FT_Err_Ok == error;
-}
-
-void FontClient::Plugin::InitSystemFonts()
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::InitSystemFonts\n" );
-
- FcFontSet* fontSet = GetFcFontSet();
-
- if( fontSet )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : %d\n", fontSet->nfont );
-
- // Reserve some space to avoid reallocations.
- mSystemFonts.reserve( fontSet->nfont );
-
- for( int i = 0u; i < fontSet->nfont; ++i )
- {
- FcPattern* fontPattern = fontSet->fonts[i];
-
- FontPath path;
-
- // Skip fonts with no path
- if( GetFcString( fontPattern, FC_FILE, path ) )
- {
- mSystemFonts.push_back( FontDescription() );
- FontDescription& fontDescription = mSystemFonts.back();
-
- fontDescription.path = path;
-
- int width = 0;
- int weight = 0;
- int slant = 0;
- GetFcString( fontPattern, FC_FAMILY, fontDescription.family );
- GetFcInt( fontPattern, FC_WIDTH, width );
- GetFcInt( fontPattern, FC_WEIGHT, weight );
- GetFcInt( fontPattern, FC_SLANT, slant );
- fontDescription.width = IntToWidthType( width );
- fontDescription.weight = IntToWeightType( weight );
- fontDescription.slant = IntToSlantType( slant );
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- }
- }
-
- FcFontSetDestroy( fontSet );
- }
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::InitSystemFonts\n" );
-}
-
-bool FontClient::Plugin::MatchFontDescriptionToPattern( FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, FcCharSet** characterSet )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::MatchFontDescriptionToPattern\n" );
-
- FcResult result = FcResultMatch;
- FcPattern* match = FcFontMatch( NULL /* use default configure */, pattern, &result );
-
- const bool matched = NULL != match;
- DALI_LOG_INFO( gLogFilter, Debug::General, " pattern matched : %s\n", ( matched ? "true" : "false" ) );
-
- if( matched )
- {
- int width = 0;
- int weight = 0;
- int slant = 0;
- GetFcString( match, FC_FILE, fontDescription.path );
- GetFcString( match, FC_FAMILY, fontDescription.family );
- GetFcInt( match, FC_WIDTH, width );
- GetFcInt( match, FC_WEIGHT, weight );
- GetFcInt( match, FC_SLANT, slant );
- fontDescription.width = IntToWidthType( width );
- fontDescription.weight = IntToWeightType( weight );
- fontDescription.slant = IntToSlantType( slant );
-
- // Cache the character ranges.
- FcPatternGetCharSet( match, FC_CHARSET, 0u, characterSet );
-
- // destroyed the matched pattern
- FcPatternDestroy( match );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::MatchFontDescriptionToPattern\n" );
- return matched;
-}
-
-FcPattern* FontClient::Plugin::CreateFontFamilyPattern( const FontDescription& fontDescription ) const
-{
- // create the cached font family lookup pattern
- // a pattern holds a set of names, each name refers to a property of the font
- FcPattern* fontFamilyPattern = FcPatternCreate();
-
- if( !fontFamilyPattern )
- {
- return NULL;
- }
-
- // add a property to the pattern for the font family
- FcPatternAddString( fontFamilyPattern, FC_FAMILY, reinterpret_cast<const FcChar8*>( fontDescription.family.c_str() ) );
-
- int width = FONT_WIDTH_TYPE_TO_INT[fontDescription.width];
- if( width < 0 )
- {
- // Use default.
- width = DEFAULT_FONT_WIDTH;
- }
-
- int weight = FONT_WEIGHT_TYPE_TO_INT[fontDescription.weight];
- if( weight < 0 )
- {
- // Use default.
- weight = DEFAULT_FONT_WEIGHT;
- }
-
- int slant = FONT_SLANT_TYPE_TO_INT[fontDescription.slant];
- if( slant < 0 )
- {
- // Use default.
- slant = DEFAULT_FONT_SLANT;
- }
-
- FcPatternAddInteger( fontFamilyPattern, FC_WIDTH, width );
- FcPatternAddInteger( fontFamilyPattern, FC_WEIGHT, weight );
- FcPatternAddInteger( fontFamilyPattern, FC_SLANT, slant );
-
- // Add a property of the pattern, to say we want to match TrueType fonts
- FcPatternAddString( fontFamilyPattern , FC_FONTFORMAT, reinterpret_cast<const FcChar8*>( FONT_FORMAT.c_str() ) );
-
- // modify the config, with the mFontFamilyPatterm
- FcConfigSubstitute( NULL /* use default configure */, fontFamilyPattern, FcMatchPattern );
-
- // provide default values for unspecified properties in the font pattern
- // e.g. patterns without a specified style or weight are set to Medium
- FcDefaultSubstitute( fontFamilyPattern );
-
- return fontFamilyPattern;
-}
-
-_FcFontSet* FontClient::Plugin::GetFcFontSet() const
-{
- // create a new pattern.
- // a pattern holds a set of names, each name refers to a property of the font
- FcPattern* pattern = FcPatternCreate();
-
- // create an object set used to define which properties are to be returned in the patterns from FcFontList.
- FcObjectSet* objectSet = FcObjectSetCreate();
-
- // build an object set from a list of property names
- FcObjectSetAdd( objectSet, FC_FILE );
- FcObjectSetAdd( objectSet, FC_FAMILY );
- FcObjectSetAdd( objectSet, FC_WIDTH );
- FcObjectSetAdd( objectSet, FC_WEIGHT );
- FcObjectSetAdd( objectSet, FC_SLANT );
-
- // get a list of fonts
- // creates patterns from those fonts containing only the objects in objectSet and returns the set of unique such patterns
- FcFontSet* fontset = FcFontList( NULL /* the default configuration is checked to be up to date, and used */, pattern, objectSet );
-
- // clear up the object set
- if( objectSet )
- {
- FcObjectSetDestroy( objectSet );
- }
- // clear up the pattern
- if( pattern )
- {
- FcPatternDestroy( pattern );
- }
-
- return fontset;
-}
-
-bool FontClient::Plugin::GetFcString( const FcPattern* const pattern,
- const char* const n,
- std::string& string )
-{
- FcChar8* file = NULL;
- const FcResult retVal = FcPatternGetString( pattern, n, 0u, &file );
-
- if( FcResultMatch == retVal )
- {
- // Have to use reinterpret_cast because FcChar8 is unsigned char*, not a const char*.
- string.assign( reinterpret_cast<const char*>( file ) );
-
- return true;
- }
-
- return false;
-}
-
-bool FontClient::Plugin::GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal )
-{
- const FcResult retVal = FcPatternGetInteger( pattern, n, 0u, &intVal );
-
- if( FcResultMatch == retVal )
- {
- return true;
- }
-
- return false;
-}
-
-FontId FontClient::Plugin::CreateFont( const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex,
- bool cacheDescription )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::CreateFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
-
- FontId id = 0u;
-
- // Create & cache new font face
- FT_Face ftFace;
- int error = FT_New_Face( mFreeTypeLibrary,
- path.c_str(),
- 0,
- &ftFace );
-
- if( FT_Err_Ok == error )
- {
- // Check if a font is scalable.
- const bool isScalable = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_SCALABLE ) );
- const bool hasFixedSizedBitmaps = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_FIXED_SIZES ) ) && ( 0 != ftFace->num_fixed_sizes );
- const bool hasColorTables = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_COLOR ) );
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " isScalable : [%s]\n", ( isScalable ? "true" : "false" ) );
- DALI_LOG_INFO( gLogFilter, Debug::General, " hasFixedSizedBitmaps : [%s]\n", ( hasFixedSizedBitmaps ? "true" : "false" ) );
- DALI_LOG_INFO( gLogFilter, Debug::General, " hasColorTables : [%s]\n", ( hasColorTables ? "true" : "false" ) );
-
- // Check to see if the font contains fixed sizes?
- if( !isScalable && hasFixedSizedBitmaps )
- {
- PointSize26Dot6 actualPointSize = 0u;
- int fixedSizeIndex = 0;
- for( ; fixedSizeIndex < ftFace->num_fixed_sizes; ++fixedSizeIndex )
- {
- const PointSize26Dot6 fixedSize = ftFace->available_sizes[fixedSizeIndex].size;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, size : %d\n", fixedSizeIndex, fixedSize );
-
- if( fixedSize >= requestedPointSize )
- {
- actualPointSize = fixedSize;
- break;
- }
- }
-
- if( 0u == actualPointSize )
- {
- // The requested point size is bigger than the bigest fixed size.
- fixedSizeIndex = ftFace->num_fixed_sizes - 1;
- actualPointSize = ftFace->available_sizes[fixedSizeIndex].size;
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, actual size : %d\n", fixedSizeIndex, actualPointSize );
-
- // Tell Freetype to use this size
- error = FT_Select_Size( ftFace, fixedSizeIndex );
- if ( FT_Err_Ok != error )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Select_Size error: %d\n", error );
- }
- else
- {
- float fixedWidth = static_cast< float >( ftFace->available_sizes[ fixedSizeIndex ].width );
- float fixedHeight = static_cast< float >( ftFace->available_sizes[ fixedSizeIndex ].height );
-
- // Indicate that the font is a fixed sized bitmap
- FontMetrics metrics( fixedHeight, // The ascender in pixels.
- 0.0f,
- fixedHeight, // The height in pixels.
- 0.0f,
- 0.0f );
-
- mFontCache.push_back( FontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics, fixedWidth, fixedHeight, hasColorTables ) );
- id = mFontCache.size();
- }
- }
- else
- {
- error = FT_Set_Char_Size( ftFace,
- 0,
- requestedPointSize,
- mDpiHorizontal,
- mDpiVertical );
-
- if( FT_Err_Ok == error )
- {
-
- FT_Size_Metrics& ftMetrics = ftFace->size->metrics;
-
- FontMetrics metrics( static_cast< float >( ftMetrics.ascender ) * FROM_266,
- static_cast< float >( ftMetrics.descender ) * FROM_266,
- static_cast< float >( ftMetrics.height ) * FROM_266,
- static_cast< float >( ftFace->underline_position ) * FROM_266,
- static_cast< float >( ftFace->underline_thickness ) * FROM_266 );
-
- mFontCache.push_back( FontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics ) );
- id = mFontCache.size();
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType Set_Char_Size error: %d for pointSize %d\n", error, requestedPointSize );
- }
- }
-
- if( 0u != id )
- {
- if( cacheDescription )
- {
- CacheFontPath( ftFace, id, requestedPointSize, path );
- }
- }
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType New_Face error: %d for [%s]\n", error, path.c_str() );
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::CreateFont\n" );
-
- return id;
-}
-
-void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap )
-{
- if( srcBitmap.width*srcBitmap.rows > 0 )
- {
- switch( srcBitmap.pixel_mode )
- {
- case FT_PIXEL_MODE_GRAY:
- {
- if( srcBitmap.pitch == static_cast<int>( srcBitmap.width ) )
- {
- const unsigned int bufferSize = srcBitmap.width * srcBitmap.rows;
- data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[].
- data.width = srcBitmap.width;
- data.height = srcBitmap.rows;
- data.format = Pixel::L8;
- memcpy( data.buffer, srcBitmap.buffer, bufferSize );
- }
- break;
- }
-
-#ifdef FREETYPE_BITMAP_SUPPORT
- case FT_PIXEL_MODE_BGRA:
- {
- if( srcBitmap.pitch == static_cast<int>( srcBitmap.width << 2u ) )
- {
- // Set the input dimensions.
- const ImageDimensions inputDimensions( srcBitmap.width, srcBitmap.rows );
-
- // Set the output dimensions.
- // If the output dimension is not given, the input dimension is set
- // and won't be downscaling.
- data.width = ( data.width == 0 ) ? srcBitmap.width : data.width;
- data.height = ( data.height == 0 ) ? srcBitmap.rows : data.height;
- const ImageDimensions desiredDimensions( data.width, data.height );
-
- // Creates the output buffer
- const unsigned int bufferSize = data.width * data.height * 4u;
- data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[].
-
- if( inputDimensions == desiredDimensions )
- {
- // There isn't downscaling.
- memcpy( data.buffer, srcBitmap.buffer, bufferSize );
- }
- else
- {
- Dali::Internal::Platform::LanczosSample4BPP( srcBitmap.buffer,
- inputDimensions,
- data.buffer,
- desiredDimensions );
- }
- data.format = Pixel::BGRA8888;
- }
- break;
- }
-#endif
- default:
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::ConvertBitmap. FontClient Unable to create Bitmap of this PixelType\n" );
- break;
- }
- }
- }
-}
-
-bool FontClient::Plugin::FindFont( const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex,
- FontId& fontId ) const
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fonts in the cache : %d\n", mFontCache.size() );
-
- fontId = 0u;
- for( std::vector<FontFaceCacheItem>::const_iterator it = mFontCache.begin(),
- endIt = mFontCache.end();
- it != endIt;
- ++it, ++fontId )
- {
- const FontFaceCacheItem& cacheItem = *it;
-
- if( cacheItem.mRequestedPointSize == requestedPointSize &&
- cacheItem.mFaceIndex == faceIndex &&
- cacheItem.mPath == path )
- {
- ++fontId;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
-
- return true;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font not found\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
-
- return false;
-}
-
-bool FontClient::Plugin::FindValidatedFont( const FontDescription& fontDescription,
- FontDescriptionId& validatedFontId )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindValidatedFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of validated fonts in the cache : %d\n", mValidatedFontCache.size() );
-
- validatedFontId = 0u;
-
- for( std::vector<FontDescriptionCacheItem>::const_iterator it = mValidatedFontCache.begin(),
- endIt = mValidatedFontCache.end();
- it != endIt;
- ++it )
- {
- const FontDescriptionCacheItem& item = *it;
-
- if( !fontDescription.family.empty() &&
- ( fontDescription.family == item.fontDescription.family ) &&
- ( fontDescription.width == item.fontDescription.width ) &&
- ( fontDescription.weight == item.fontDescription.weight ) &&
- ( fontDescription.slant == item.fontDescription.slant ) )
- {
- validatedFontId = item.index;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " validated font found, id : %d\n", validatedFontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" );
- return true;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " validated font not found\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" );
- return false;
-}
-
-bool FontClient::Plugin::FindFallbackFontList( const FontDescription& fontDescription,
- FontList*& fontList,
- CharacterSetList*& characterSetList )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFontList\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fallback font lists in the cache : %d\n", mFallbackCache.size() );
-
- fontList = NULL;
-
- for( std::vector<FallbackCacheItem>::const_iterator it = mFallbackCache.begin(), endIt = mFallbackCache.end();
- it != endIt;
- ++it )
- {
- const FallbackCacheItem& item = *it;
-
- if( !fontDescription.family.empty() &&
- ( fontDescription.family == item.fontDescription.family ) &&
- ( fontDescription.width == item.fontDescription.width ) &&
- ( fontDescription.weight == item.fontDescription.weight ) &&
- ( fontDescription.slant == item.fontDescription.slant ) )
- {
- fontList = item.fallbackFonts;
- characterSetList = item.characterSets;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list found.\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" );
- return true;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list not found.\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" );
- return false;
-}
-
-bool FontClient::Plugin::FindFont( FontDescriptionId validatedFontId,
- PointSize26Dot6 requestedPointSize,
- FontId& fontId )
-{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize );
-
- fontId = 0u;
-
- for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
- endIt = mFontIdCache.end();
- it != endIt;
- ++it )
- {
- const FontIdCacheItem& item = *it;
-
- if( ( validatedFontId == item.validatedFontId ) &&
- ( requestedPointSize == item.requestedPointSize ) )
- {
- fontId = item.fontId;
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
- return true;
- }
- }
-
- DALI_LOG_INFO( gLogFilter, Debug::General, " font not found.\n" );
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" );
- return false;
-}
-
-bool FontClient::Plugin::IsScalable( const FontPath& path )
-{
- bool isScalable = false;
-
- FT_Face ftFace;
- int error = FT_New_Face( mFreeTypeLibrary,
- path.c_str(),
- 0,
- &ftFace );
- if( FT_Err_Ok != error )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: %s\n", path.c_str() );
- }
- else
- {
- isScalable = ftFace->face_flags & FT_FACE_FLAG_SCALABLE;
- }
-
- return isScalable;
-}
-
-bool FontClient::Plugin::IsScalable( const FontDescription& fontDescription )
-{
- // Create a font pattern.
- FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
-
- FcResult result = FcResultMatch;
-
- // match the pattern
- FcPattern* match = FcFontMatch( NULL /* use default configure */, fontFamilyPattern, &result );
- bool isScalable = false;
-
- if( match )
- {
- // Get the path to the font file name.
- FontPath path;
- GetFcString( match, FC_FILE, path );
- isScalable = IsScalable( path );
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() );
- }
- FcPatternDestroy( fontFamilyPattern );
- FcPatternDestroy( match );
- return isScalable;
-}
-
-void FontClient::Plugin::GetFixedSizes( const FontPath& path, Vector< PointSize26Dot6 >& sizes )
-{
- // Empty the caller container
- sizes.Clear();
-
- FT_Face ftFace;
- int error = FT_New_Face( mFreeTypeLibrary,
- path.c_str(),
- 0,
- &ftFace );
- if( FT_Err_Ok != error )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font path : [%s]\n", path.c_str() );
- }
-
- // Fetch the number of fixed sizes available
- if ( ftFace->num_fixed_sizes && ftFace->available_sizes )
- {
- for ( int i = 0; i < ftFace->num_fixed_sizes; ++i )
- {
- sizes.PushBack( ftFace->available_sizes[ i ].size );
- }
- }
-}
-
-void FontClient::Plugin::GetFixedSizes( const FontDescription& fontDescription,
- Vector< PointSize26Dot6 >& sizes )
-{
- // Create a font pattern.
- FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription );
-
- FcResult result = FcResultMatch;
-
- // match the pattern
- FcPattern* match = FcFontMatch( NULL /* use default configure */, fontFamilyPattern, &result );
-
- if( match )
- {
- // Get the path to the font file name.
- FontPath path;
- GetFcString( match, FC_FILE, path );
- GetFixedSizes( path, sizes );
- }
- else
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() );
- }
- FcPatternDestroy( match );
- FcPatternDestroy( fontFamilyPattern );
-}
-
-void FontClient::Plugin::CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path )
-{
- FontDescription description;
- description.path = path;
- description.family = FontFamily( ftFace->family_name );
- description.weight = FontWeight::NONE;
- description.width = FontWidth::NONE;
- description.slant = FontSlant::NONE;
-
- // Note FreeType doesn't give too much info to build a proper font style.
- if( ftFace->style_flags & FT_STYLE_FLAG_ITALIC )
- {
- description.slant = FontSlant::ITALIC;
- }
- if( ftFace->style_flags & FT_STYLE_FLAG_BOLD )
- {
- description.weight = FontWeight::BOLD;
- }
-
- FontDescriptionId validatedFontId = 0u;
- if( !FindValidatedFont( description,
- validatedFontId ) )
- {
- // Set the index to the vector of paths to font file names.
- validatedFontId = mFontDescriptionCache.size();
-
- FcPattern* pattern = CreateFontFamilyPattern( description );
-
- FcResult result = FcResultMatch;
- FcPattern* match = FcFontMatch( NULL, pattern, &result );
-
- FcCharSet* characterSet = NULL;
- FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet );
-
- FcPatternDestroy( match );
- FcPatternDestroy( pattern );
-
- mFontCache[id-1u].mCharacterSet = characterSet;
-
- // Add the path to the cache.
- mFontDescriptionCache.push_back( description );
- mCharacterSetCache.PushBack( characterSet );
-
- // Cache the index and the font's description.
- FontDescriptionCacheItem item( description,
- validatedFontId );
-
- mValidatedFontCache.push_back( item );
-
- // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries.
- mFontIdCache.push_back( FontIdCacheItem( validatedFontId,
- requestedPointSize,
- id ) );
- }
-}
-
-FcCharSet* FontClient::Plugin::CreateCharacterSetFromDescription( const FontDescription& description ) const
-{
- FcCharSet* characterSet = NULL;
-
- FcPattern* pattern = CreateFontFamilyPattern( description );
-
- if( NULL != pattern )
- {
- FcResult result = FcResultMatch;
- FcPattern* match = FcFontMatch( NULL, pattern, &result );
-
- FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet );
-
- FcPatternDestroy( match );
- FcPatternDestroy( pattern );
- }
-
- return characterSet;
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
-#define DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
-
-/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <dali/devel-api/text-abstraction/font-metrics.h>
-#include <dali/devel-api/text-abstraction/glyph-info.h>
-#include <dali/internal/text-abstraction/font-client-impl.h>
-
-#ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING
-#include <dali/internal/glyphy/vector-font-cache.h>
-#else
-class VectorFontCache;
-#endif
-
-// EXTERNAL INCLUDES
-#include <ft2build.h>
-#include FT_FREETYPE_H
-#include FT_GLYPH_H
-#include FT_OUTLINE_H
-#include FT_STROKER_H
-
-// forward declarations of font config types.
-struct _FcCharSet;
-struct _FcFontSet;
-struct _FcPattern;
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-/**
- *@brief Type used for indices addressing the vector with front descriptions of validated fonts.
- */
-typedef uint32_t FontDescriptionId;
-typedef Vector<_FcCharSet*> CharacterSetList;
-
-/**
- * @brief FontClient implementation.
- */
-struct FontClient::Plugin
-{
- /**
- * @brief Caches an list of fallback fonts for a given font-description
- */
- struct FallbackCacheItem
- {
- FallbackCacheItem( const FontDescription& fontDescription, FontList* fallbackFonts, CharacterSetList* characterSets );
-
- FontDescription fontDescription; ///< The font description.
- FontList* fallbackFonts; ///< The list of fallback fonts for the given font-description.
- CharacterSetList* characterSets; ///< The list of character sets for the given font-description.
- };
-
- /**
- * @brief Caches an index to the vector of font descriptions for a given font.
- */
- struct FontDescriptionCacheItem
- {
- FontDescriptionCacheItem( const FontDescription& fontDescription,
- FontDescriptionId index );
-
- FontDescription fontDescription; ///< The font description.
- FontDescriptionId index; ///< Index to the vector of font descriptions.
- };
-
- /**
- * @brief Caches the font id of the pair font point size and the index to the vector of font descriptions of validated fonts.
- */
- struct FontIdCacheItem
- {
- FontIdCacheItem( FontDescriptionId validatedFontId,
- PointSize26Dot6 requestedPointSize,
- FontId fontId );
-
- FontDescriptionId validatedFontId; ///< Index to the vector with font descriptions.
- PointSize26Dot6 requestedPointSize; ///< The font point size.
- FontId fontId; ///< The font identifier.
- };
-
- /**
- * @brief Caches the FreeType face and font metrics of the triplet 'path to the font file name, font point size and face index'.
- */
- struct FontFaceCacheItem
- {
- FontFaceCacheItem( FT_Face ftFace,
- const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex face,
- const FontMetrics& metrics );
-
- FontFaceCacheItem( FT_Face ftFace,
- const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex face,
- const FontMetrics& metrics,
- float fixedWidth,
- float fixedHeight,
- bool hasColorTables );
-
- FT_Face mFreeTypeFace; ///< The FreeType face.
- FontPath mPath; ///< The path to the font file name.
- PointSize26Dot6 mRequestedPointSize; ///< The font point size.
- FaceIndex mFaceIndex; ///< The face index.
- FontMetrics mMetrics; ///< The font metrics.
- _FcCharSet* mCharacterSet; ///< Pointer with the range of characters.
- FT_Short mFixedWidthPixels; ///< The height in pixels (fixed size bitmaps only)
- FT_Short mFixedHeightPixels; ///< The height in pixels (fixed size bitmaps only)
- unsigned int mVectorFontId; ///< The ID of the equivalent vector-based font
- bool mIsFixedSizeBitmap : 1; ///< Whether the font has fixed size bitmaps.
- bool mHasColorTables : 1; ///< Whether the font has color tables.
- };
-
- struct EllipsisItem
- {
- PointSize26Dot6 requestedPointSize;
- GlyphInfo glyph;
- };
-
- /**
- * Constructor.
- *
- * Initializes the FreeType library.
- * Initializes the dpi values.
- *
- * @param[in] horizontalDpi The horizontal dpi.
- * @param[in] verticalDpi The vertical dpi.
- */
- Plugin( unsigned int horizontalDpi, unsigned int verticalDpi );
-
- /**
- * Default destructor.
- *
- * Frees any allocated resource.
- */
- ~Plugin();
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::SetDpi()
- */
- void SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::ResetSystemDefaults()
- */
- void ResetSystemDefaults();
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::SetDefaultFont()
- */
- void SetDefaultFont( const FontDescription& preferredFontDescription );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetDefaultPlatformFontDescription()
- */
- void GetDefaultPlatformFontDescription( FontDescription& fontDescription );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetDefaultFonts()
- */
- void GetDefaultFonts( FontList& defaultFonts );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetSystemFonts()
- */
- void GetSystemFonts( FontList& systemFonts );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetDescription()
- */
- void GetDescription( FontId id, FontDescription& fontDescription ) const;
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetPointSize()
- */
- PointSize26Dot6 GetPointSize( FontId id );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::IsCharacterSupportedByFont()
- */
- bool IsCharacterSupportedByFont( FontId fontId, Character character );
-
- /**
- * @brief Finds within the @p fontList a font which support the @p carcode.
- *
- * @param[in] fontList A list of font paths, family, width, weight and slant.
- * @param[in] characterSetList A list that contains a character set for each description of the font list.
- * @param[in] charcode The character for which a font is needed.
- * @param[in] requestedPointSize The point size in 26.6 fractional points.
- * @param[in] preferColor @e true if a color font is preferred.
- *
- * @return A valid font identifier, or zero if no font is found.
- */
- FontId FindFontForCharacter( const FontList& fontList,
- const CharacterSetList& characterSetList,
- Character charcode,
- PointSize26Dot6 requestedPointSize,
- bool preferColor );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::FindDefaultFont()
- */
- FontId FindDefaultFont( Character charcode,
- PointSize26Dot6 requestedPointSize,
- bool preferColor );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::FindFallbackFont()
- */
- FontId FindFallbackFont( Character charcode,
- const FontDescription& preferredFontDescription,
- PointSize26Dot6 requestedPointSize,
- bool preferColor );
-
- /**
- * @see Dali::TextAbstraction::FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
- *
- * @param[in] cacheDescription Whether to cache the font description.
- */
- FontId GetFontId( const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex,
- bool cacheDescription );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const FontDescription& preferredFontDescription, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex )
- */
- FontId GetFontId( const FontDescription& fontDescription,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontPath& path )
- */
- bool IsScalable( const FontPath& path );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontDescription& fontDescription )
- */
- bool IsScalable( const FontDescription& fontDescription );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes()
- */
- void GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes()
- */
- void GetFixedSizes( const FontDescription& fontDescription,
- Dali::Vector< PointSize26Dot6 >& sizes );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetFontMetrics()
- */
- void GetFontMetrics( FontId fontId, FontMetrics& metrics );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetGlyphIndex()
- */
- GlyphIndex GetGlyphIndex( FontId fontId, Character charcode );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetGlyphMetrics()
- */
- bool GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal );
-
- /**
- * Helper for GetGlyphMetrics when using bitmaps
- */
- bool GetBitmapMetrics( GlyphInfo* array, uint32_t size, bool horizontal );
-
- /**
- * Helper for GetGlyphMetrics when using vectors
- */
- bool GetVectorMetrics( GlyphInfo* array, uint32_t size, bool horizontal );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth )
- */
- void CreateBitmap( FontId fontId, GlyphIndex glyphIndex, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth )
- */
- PixelData CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::CreateVectorBlob()
- */
- void CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::GetEllipsisGlyph()
- */
- const GlyphInfo& GetEllipsisGlyph( PointSize26Dot6 requestedPointSize );
-
- /**
- * @copydoc Dali::TextAbstraction::FontClient::IsColorGlyph()
- */
- bool IsColorGlyph( FontId fontId, GlyphIndex glyphIndex );
-
-private:
-
- /**
- * @brief Caches the fonts present in the platform.
- *
- * Calls GetFcFontSet() to retrieve the fonts.
- */
- void InitSystemFonts();
-
- /**
- * @brief Gets the FontDescription which matches the given pattern.
- * @param[in] pattern pattern to match against.
- * @param[out] fontDescription the resultant fontDescription that matched.
- * @param[out] characterSet The character set for that pattern.
- * @return true if match found.
- */
- bool MatchFontDescriptionToPattern( _FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, _FcCharSet** characterSet );
-
- /**
- * @brief Creates a font family pattern used to match fonts.
- *
- * @param[in] fontDescription The font to cache.
- *
- * @return The pattern.
- */
- _FcPattern* CreateFontFamilyPattern( const FontDescription& fontDescription ) const;
-
- /**
- * Retrieves the fonts present in the platform.
- *
- * @return A font fonfig data structure with the platform's fonts.
- */
- _FcFontSet* GetFcFontSet() const;
-
- /**
- * Retrieves a font config object's value from a pattern.
- *
- * @param[in] pattern The font config pattern.
- * @param[in] n The object.
- * @param[out] string The object's value.
- *
- * @return @e true if the operation is successful.
- */
- bool GetFcString( const _FcPattern* const pattern, const char* const n, std::string& string );
-
- /**
- * Retrieves a font config object's value from a pattern.
- *
- * @param[in] pattern The font config pattern.
- * @param[in] n The object.
- * @param[out] intVal The object's value.
- *
- * @return @e true if the operation is successful.
- */
- bool GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal );
-
- /**
- * @brief Creates a font.
- *
- * @param[in] path The path to the font file name.
- * @param[in] requestedPointSize The requested point size.
- * @param[in] faceIndex A face index.
- * @param[in] cacheDescription Whether to cache the font description.
- *
- * @return The font identifier.
- */
- FontId CreateFont( const FontPath& path,
- PointSize26Dot6 requestedPointSize,
- FaceIndex faceIndex,
- bool cacheDescription );
-
- /**
- * @brief Copy the FreeType bitmap to the given buffer.
- *
- * @param[out] data The bitmap data.
- * @param[in] srcBitmap The FreeType bitmap.
- */
- void ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap );
-
- /**
- * @brief Finds in the cache if there is a triplet with the path to the font file name, the font point size and the face index.
- * If there is one , if writes the font identifier in the param @p fontId.
- *
- * @param[in] path Path to the font file name.
- * @param[in] requestedPointSize The font point size.
- * @param[in] faceIndex The face index.
- * @param[out] fontId The font identifier.
- *
- * @return @e true if there triplet is found.
- */
- bool FindFont( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex, FontId& fontId ) const;
-
- /**
- * @brief Finds in the cache a cluster 'font family, font width, font weight, font slant'
- * If there is one, it writes the index to the vector with font descriptions in the param @p validatedFontId.
- *
- * @param[in] fontDescription The font to validate.
- * @param[out] validatedFontId The index to the vector with font descriptions.
- *
- * @return @e true if the pair is found.
- */
- bool FindValidatedFont( const FontDescription& fontDescription,
- FontDescriptionId& validatedFontId );
-
- /**
- * @brief Finds a fallback font list from the cache for a given font-description
- *
- * @param[in] fontDescription The font to validate.
- * @param[out] A valid pointer to a font list, or NULL if not found.
- * @param[out] characterSetList A valid pointer to a character set list, or NULL if not found.
- */
- bool FindFallbackFontList( const FontDescription& fontDescription,
- FontList*& fontList,
- CharacterSetList*& characterSetList );
-
- /**
- * @brief Finds in the cache a pair 'validated font identifier and font point size'.
- * If there is one it writes the font identifier in the param @p fontId.
- *
- * @param[in] validatedFontId Index to the vector with font descriptions.
- * @param[in] requestedPointSize The font point size.
- * @param[out] fontId The font identifier.
- *
- * @return @e true if the pair is found.
- */
- bool FindFont( FontDescriptionId validatedFontId,
- PointSize26Dot6 requestedPointSize,
- FontId& fontId );
-
- /**
- * @brief Validate a font description.
- *
- * @param[in] fontDescription The font to validate.
- * @param[out] validatedFontId Result of validation
- */
- void ValidateFont( const FontDescription& fontDescription,
- FontDescriptionId& validatedFontId );
-
- /**
- * Helper for GetDefaultFonts etc.
- *
- * @param[in] fontDescription A font description.
- * @param[out] fontList A list of the fonts which are a close match for fontDescription.
- * @param[out] characterSetList A list of the character sets which are a close match for fontDescription.
- */
- void SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList );
-
- /**
- * Caches a font path.
- *
- * @param[in] ftFace The FreeType face.
- * @param[in] id The font identifier.
- * @param[in] requestedPointSize The font point size.
- * @param[in] path Path to the font file name.
- */
- void CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path );
-
- /**
- * @brief Creates a character set from a given font's @p description.
- *
- * @param[in] description The font's description.
- *
- * @return A character set.
- */
- _FcCharSet* CreateCharacterSetFromDescription( const FontDescription& description ) const;
-
-private:
-
- // Declared private and left undefined to avoid copies.
- Plugin( const Plugin& );
- // Declared private and left undefined to avoid copies.
- Plugin& operator=( const Plugin& );
-
-private:
-
- FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance.
-
- unsigned int mDpiHorizontal; ///< Horizontal dpi.
- unsigned int mDpiVertical; ///< Vertical dpi.
-
- FontDescription mDefaultFontDescription; ///< The cached default font from the system
-
- FontList mSystemFonts; ///< Cached system fonts.
- FontList mDefaultFonts; ///< Cached default fonts.
- CharacterSetList mDefaultFontCharacterSets;
-
- std::vector<FallbackCacheItem> mFallbackCache; ///< Cached fallback font lists.
-
- std::vector<FontFaceCacheItem> mFontCache; ///< Caches the FreeType face and font metrics of the triplet 'path to the font file name, font point size and face index'.
- std::vector<FontDescriptionCacheItem> mValidatedFontCache; ///< Caches indices to the vector of font descriptions for a given font.
- FontList mFontDescriptionCache; ///< Caches font descriptions for the validated font.
- CharacterSetList mCharacterSetCache; ///< Caches character set lists for the validated font.
- std::vector<FontIdCacheItem> mFontIdCache; ///< Caches font identifiers for the pairs of font point size and the index to the vector with font descriptions of the validated fonts.
-
- VectorFontCache* mVectorFontCache; ///< Separate cache for vector data blobs etc.
-
- Vector<EllipsisItem> mEllipsisCache; ///< Caches ellipsis glyphs for a particular point size.
-
- bool mDefaultFontDescriptionCached : 1; ///< Whether the default font is cached or not
-};
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
-
-#endif // DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "segmentation-impl.h"
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-
-// EXTERNAL INCLUDES
-#include <linebreak.h>
-#include <wordbreak.h>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-struct Segmentation::Plugin
-{
- void GetLineBreakPositions( const Character* const text,
- Length numberOfCharacters,
- LineBreakInfo* breakInfo )
- {
- set_linebreaks_utf32( text, numberOfCharacters, NULL, breakInfo );
- }
-
- void GetWordBreakPositions( const Character* const text,
- Length numberOfCharacters,
- WordBreakInfo* breakInfo )
- {
- set_wordbreaks_utf32( text, numberOfCharacters, NULL, breakInfo );
- }
-};
-
-Segmentation::Segmentation()
-: mPlugin( NULL )
-{}
-
-Segmentation::~Segmentation()
-{
- delete mPlugin;
-}
-
-TextAbstraction::Segmentation Segmentation::Get()
-{
- TextAbstraction::Segmentation segmentationHandle;
-
- SingletonService service( SingletonService::Get() );
- if( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Segmentation ) );
- if( handle )
- {
- // If so, downcast the handle
- Segmentation* impl = dynamic_cast< Internal::Segmentation* >( handle.GetObjectPtr() );
- segmentationHandle = TextAbstraction::Segmentation( impl );
- }
- else // create and register the object
- {
- segmentationHandle = TextAbstraction::Segmentation( new Segmentation );
- service.Register( typeid( segmentationHandle ), segmentationHandle );
- }
- }
-
- return segmentationHandle;
-}
-
-void Segmentation::GetLineBreakPositions( const Character* const text,
- Length numberOfCharacters,
- LineBreakInfo* breakInfo )
-{
- CreatePlugin();
-
- mPlugin->GetLineBreakPositions( text, numberOfCharacters, breakInfo );
-}
-
-void Segmentation::GetWordBreakPositions( const Character* const text,
- Length numberOfCharacters,
- WordBreakInfo* breakInfo )
-{
- CreatePlugin();
-
- mPlugin->GetWordBreakPositions( text, numberOfCharacters, breakInfo );
-}
-
-void Segmentation::CreatePlugin()
-{
- if( !mPlugin )
- {
- mPlugin = new Plugin();
- }
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-/*
- * Copyright (c) 2015 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include "shaping-impl.h"
-
-// INTERNAL INCLUDES
-#include <singleton-service-impl.h>
-#include <dali/devel-api/text-abstraction/font-client.h>
-#include <dali/devel-api/text-abstraction/glyph-info.h>
-#include <dali/integration-api/debug.h>
-
-// EXTERNAL INCLUDES
-#include <harfbuzz/hb.h>
-#include <harfbuzz/hb-ft.h>
-
-#include <ft2build.h>
-#include <iostream>
-
-namespace Dali
-{
-
-namespace TextAbstraction
-{
-
-namespace Internal
-{
-
-const char* DEFAULT_LANGUAGE = "en";
-const unsigned int DEFAULT_LANGUAGE_LENGTH = 2u;
-const float FROM_266 = 1.0f / 64.0f;
-
-const hb_script_t SCRIPT_TO_HARFBUZZ[] =
-{
- HB_SCRIPT_COMMON,
-
- HB_SCRIPT_COMMON, // ASCII_DIGITS
- HB_SCRIPT_COMMON, // ASCII_PS
-
- HB_SCRIPT_COMMON, // C1_CONTROLS
- HB_SCRIPT_COMMON, // C1_PS
- HB_SCRIPT_COMMON, // C1_MATH
- HB_SCRIPT_COMMON, // SML_P
- HB_SCRIPT_COMMON, // PHONETIC_U
- HB_SCRIPT_COMMON, // PHONETIC_SS
- HB_SCRIPT_COMMON, // NUMERIC_SS
- HB_SCRIPT_COMMON, // LETTER_LIKE
- HB_SCRIPT_COMMON, // NUMBER_FORMS
- HB_SCRIPT_COMMON, // FRACTIONS_NF
- HB_SCRIPT_COMMON, // NON_LATIN_LED
- HB_SCRIPT_COMMON, // HWFW_S
-
- HB_SCRIPT_CYRILLIC,
- HB_SCRIPT_GREEK,
- HB_SCRIPT_LATIN,
-
- HB_SCRIPT_ARABIC,
- HB_SCRIPT_HEBREW,
-
- HB_SCRIPT_ARMENIAN,
- HB_SCRIPT_GEORGIAN,
-
- HB_SCRIPT_HAN,
- HB_SCRIPT_HANGUL,
- HB_SCRIPT_HIRAGANA,
- HB_SCRIPT_KATAKANA,
- HB_SCRIPT_BOPOMOFO,
-
- HB_SCRIPT_BENGALI,
- HB_SCRIPT_MYANMAR,
- HB_SCRIPT_DEVANAGARI,
- HB_SCRIPT_GUJARATI,
- HB_SCRIPT_GURMUKHI,
- HB_SCRIPT_KANNADA,
- HB_SCRIPT_MALAYALAM,
- HB_SCRIPT_ORIYA,
- HB_SCRIPT_SINHALA,
- HB_SCRIPT_TAMIL,
- HB_SCRIPT_TELUGU,
-
- HB_SCRIPT_LAO,
- HB_SCRIPT_THAI,
- HB_SCRIPT_KHMER,
- HB_SCRIPT_JAVANESE,
- HB_SCRIPT_SUNDANESE,
-
- HB_SCRIPT_ETHIOPIC,
- HB_SCRIPT_OL_CHIKI,
- HB_SCRIPT_TAGALOG,
- HB_SCRIPT_MEETEI_MAYEK,
-
- HB_SCRIPT_UNKNOWN, // EMOJI
- HB_SCRIPT_UNKNOWN, // SYMBOLS1
- HB_SCRIPT_UNKNOWN, // SYMBOLS2
- HB_SCRIPT_UNKNOWN, // SYMBOLS3
- HB_SCRIPT_UNKNOWN, // SYMBOLS4
- HB_SCRIPT_UNKNOWN, // SYMBOLS5
- HB_SCRIPT_UNKNOWN
-};
-
-struct Shaping::Plugin
-{
- Plugin()
- : mFreeTypeLibrary( NULL ),
- mIndices(),
- mAdvance(),
- mCharacterMap(),
- mFontId( 0u )
- {
- }
-
- ~Plugin()
- {
- FT_Done_FreeType( mFreeTypeLibrary );
- }
-
- void Initialize()
- {
- int error = FT_Init_FreeType( &mFreeTypeLibrary );
- if( FT_Err_Ok != error )
- {
- DALI_LOG_ERROR( "FreeType Init error: %d\n", error );
- }
- }
-
- Length Shape( const Character* const text,
- Length numberOfCharacters,
- FontId fontId,
- Script script )
- {
- // Clear previoursly shaped texts.
- mIndices.Clear();
- mAdvance.Clear();
- mCharacterMap.Clear();
- mOffset.Clear();
- mFontId = fontId;
-
- // Reserve some space to avoid reallocations.
- const Length numberOfGlyphs = static_cast<Length>( 1.3f * static_cast<float>( numberOfCharacters ) );
- mIndices.Reserve( numberOfGlyphs );
- mAdvance.Reserve( numberOfGlyphs );
- mCharacterMap.Reserve( numberOfGlyphs );
- mOffset.Reserve( 2u * numberOfGlyphs );
-
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
-
- // Get the font's path file name from the font Id.
- FontDescription fontDescription;
- fontClient.GetDescription( fontId, fontDescription );
-
- // Create a FreeType font's face.
- FT_Face face;
- FT_Error retVal = FT_New_Face( mFreeTypeLibrary, fontDescription.path.c_str(), 0u, &face );
- if( FT_Err_Ok != retVal )
- {
- DALI_LOG_ERROR( "Failed to open face: %s\n", fontDescription.path.c_str() );
- return 0u;
- }
-
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- fontClient.GetDpi( horizontalDpi, verticalDpi );
-
- FT_Set_Char_Size( face,
- 0u,
- fontClient.GetPointSize( fontId ),
- horizontalDpi,
- verticalDpi );
-
- /* Get our harfbuzz font struct */
- hb_font_t* harfBuzzFont;
- harfBuzzFont = hb_ft_font_create( face, NULL );
-
- /* Create a buffer for harfbuzz to use */
- hb_buffer_t* harfBuzzBuffer = hb_buffer_create();
-
- const bool rtlDirection = IsRightToLeftScript( script );
- hb_buffer_set_direction( harfBuzzBuffer,
- rtlDirection ? HB_DIRECTION_RTL : HB_DIRECTION_LTR ); /* or LTR */
-
- hb_buffer_set_script( harfBuzzBuffer,
- SCRIPT_TO_HARFBUZZ[ script ] ); /* see hb-unicode.h */
-
-
- char* currentLocale = setlocale(LC_MESSAGES,NULL);
-
- std::istringstream stringStream( currentLocale );
- std::string localeString;
- std::getline(stringStream, localeString, '_');
- hb_buffer_set_language( harfBuzzBuffer, hb_language_from_string( localeString.c_str(), localeString.size() ) );
-
- /* Layout the text */
- hb_buffer_add_utf32( harfBuzzBuffer, text, numberOfCharacters, 0u, numberOfCharacters );
-
- hb_shape( harfBuzzFont, harfBuzzBuffer, NULL, 0u );
-
- /* Get glyph data */
- unsigned int glyphCount;
- hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( harfBuzzBuffer, &glyphCount );
- hb_glyph_position_t *glyphPositions = hb_buffer_get_glyph_positions( harfBuzzBuffer, &glyphCount );
- const GlyphIndex lastGlyphIndex = glyphCount - 1u;
- for( GlyphIndex i = 0u; i < glyphCount; )
- {
- if( rtlDirection )
- {
- // If the direction is right to left, Harfbuzz retrieves the glyphs in the visual order.
- // The glyphs are needed in the logical order to layout the text in lines.
- // Do not change the order of the glyphs if they belong to the same cluster.
- GlyphIndex rtlIndex = lastGlyphIndex - i;
-
- unsigned int cluster = glyphInfo[rtlIndex].cluster;
- unsigned int previousCluster = cluster;
- Length numberOfGlyphsInCluster = 0u;
-
- while( ( cluster == previousCluster ) )
- {
- ++numberOfGlyphsInCluster;
- previousCluster = cluster;
-
- if( rtlIndex > 0u )
- {
- --rtlIndex;
-
- cluster = glyphInfo[rtlIndex].cluster;
- }
- else
- {
- break;
- }
- }
-
- rtlIndex = lastGlyphIndex - ( i + ( numberOfGlyphsInCluster - 1u ) );
-
- for( GlyphIndex j = 0u; j < numberOfGlyphsInCluster; ++j )
- {
- const GlyphIndex index = rtlIndex + j;
-
- mIndices.PushBack( glyphInfo[index].codepoint );
- mAdvance.PushBack( floor( glyphPositions[index].x_advance * FROM_266 ) );
- mCharacterMap.PushBack( glyphInfo[index].cluster );
- mOffset.PushBack( floor( glyphPositions[index].x_offset * FROM_266 ) );
- mOffset.PushBack( floor( glyphPositions[index].y_offset * FROM_266 ) );
- }
-
- i += numberOfGlyphsInCluster;
- }
- else
- {
- mIndices.PushBack( glyphInfo[i].codepoint );
- mAdvance.PushBack( floor( glyphPositions[i].x_advance * FROM_266 ) );
- mCharacterMap.PushBack( glyphInfo[i].cluster );
- mOffset.PushBack( floor( glyphPositions[i].x_offset * FROM_266 ) );
- mOffset.PushBack( floor( glyphPositions[i].y_offset * FROM_266 ) );
-
- ++i;
- }
- }
-
- /* Cleanup */
- hb_buffer_destroy( harfBuzzBuffer );
- hb_font_destroy( harfBuzzFont );
- FT_Done_Face( face );
-
- return mIndices.Count();
- }
-
- void GetGlyphs( GlyphInfo* glyphInfo,
- CharacterIndex* glyphToCharacterMap )
- {
- Vector<CharacterIndex>::ConstIterator indicesIt = mIndices.Begin();
- Vector<float>::ConstIterator advanceIt = mAdvance.Begin();
- Vector<float>::ConstIterator offsetIt = mOffset.Begin();
- Vector<CharacterIndex>::ConstIterator characterMapIt = mCharacterMap.Begin();
-
- for( GlyphIndex index = 0u, size = mIndices.Count(); index < size; ++index )
- {
- GlyphInfo& glyph = *( glyphInfo + index );
- CharacterIndex& glyphToCharacter = *( glyphToCharacterMap + index );
-
- glyph.fontId = mFontId;
- glyph.index = *( indicesIt + index );
- glyph.advance = *( advanceIt + index );
-
- const GlyphIndex offsetIndex = 2u * index;
- glyph.xBearing = *( offsetIt + offsetIndex );
- glyph.yBearing = *( offsetIt + offsetIndex + 1u );
-
- glyphToCharacter = *( characterMapIt + index );
- }
- }
-
- FT_Library mFreeTypeLibrary;
-
- Vector<CharacterIndex> mIndices;
- Vector<float> mAdvance;
- Vector<float> mOffset;
- Vector<CharacterIndex> mCharacterMap;
- FontId mFontId;
-};
-
-Shaping::Shaping()
-: mPlugin( NULL )
-{
-}
-
-Shaping::~Shaping()
-{
- delete mPlugin;
-}
-
-TextAbstraction::Shaping Shaping::Get()
-{
- TextAbstraction::Shaping shapingHandle;
-
- SingletonService service( SingletonService::Get() );
- if( service )
- {
- // Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Shaping ) );
- if( handle )
- {
- // If so, downcast the handle
- Shaping* impl = dynamic_cast< Internal::Shaping* >( handle.GetObjectPtr() );
- shapingHandle = TextAbstraction::Shaping( impl );
- }
- else // create and register the object
- {
- shapingHandle = TextAbstraction::Shaping( new Shaping );
- service.Register( typeid( shapingHandle ), shapingHandle );
- }
- }
-
- return shapingHandle;
-}
-
-Length Shaping::Shape( const Character* const text,
- Length numberOfCharacters,
- FontId fontId,
- Script script )
-{
- CreatePlugin();
-
- return mPlugin->Shape( text,
- numberOfCharacters,
- fontId,
- script );
-}
-
-void Shaping::GetGlyphs( GlyphInfo* glyphInfo,
- CharacterIndex* glyphToCharacterMap )
-{
- CreatePlugin();
-
- mPlugin->GetGlyphs( glyphInfo,
- glyphToCharacterMap );
-}
-
-void Shaping::CreatePlugin()
-{
- if( !mPlugin )
- {
- mPlugin = new Plugin();
- mPlugin->Initialize();
- }
-}
-
-} // namespace Internal
-
-} // namespace TextAbstraction
-
-} // namespace Dali
+++ /dev/null
-# Add local source files here
-
-text_abstraction_src_files = \
- $(text_src_dir)/dali/devel-api/text-abstraction/bidirectional-support.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-client.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-list.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-metrics.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/glyph-info.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/script.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/segmentation.cpp \
- $(text_src_dir)/dali/devel-api/text-abstraction/shaping.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/bidirectional-support-impl.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/font-client-helper.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/font-client-impl.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/font-client-plugin-impl.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/segmentation-impl.cpp \
- $(text_src_dir)/dali/internal/text-abstraction/shaping-impl.cpp
-
-text_abstraction_header_files = \
- $(text_src_dir)/dali/devel-api/text-abstraction/bidirectional-support.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-client.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-list.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/font-metrics.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/glyph-info.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/script.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/segmentation.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/shaping.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/text-abstraction.h \
- $(text_src_dir)/dali/devel-api/text-abstraction/text-abstraction-definitions.h
--- /dev/null
+static_libraries_glyphy_src_files = \
+ ${adaptor_thirdparty_dir}/glyphy/glyphy-arcs.cc \
+ ${adaptor_thirdparty_dir}/glyphy/glyphy-blob-impl.cc \
+ ${adaptor_thirdparty_dir}/glyphy/glyphy-extents.cc \
+ ${adaptor_thirdparty_dir}/glyphy/glyphy-outline.cc \
+ ${adaptor_thirdparty_dir}/glyphy/glyphy-sdf.cc \
+ ${adaptor_thirdparty_dir}/glyphy/vector-font-cache.cpp
+
+static_libraries_libunibreak_src_files = \
+ ${adaptor_thirdparty_dir}/libunibreak/linebreak.c \
+ ${adaptor_thirdparty_dir}/libunibreak/linebreakdata.c \
+ ${adaptor_thirdparty_dir}/libunibreak/linebreakdef.c \
+ ${adaptor_thirdparty_dir}/libunibreak/wordbreak.c
+
+adaptor_resampler_src_files=\
+ ${adaptor_thirdparty_dir}/resampler/resampler.cpp
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// CLASS HEADER
+#include <third-party/glyphy/vector-font-cache.h> // Replaced from: #include <dali/internal/glyphy/vector-font-cache.h>
+
+// EXTERNAL INCLUDES
+#include <vector>
+#include <math.h>
+
+// INTERNAL INCLUDES
+#include <third-party/glyphy/glyphy.h> // Replaced from: #include "../glyphy/glyphy.h"
+#include <third-party/glyphy/glyphy-freetype.h> // Replaced from: #include "../glyphy/glyphy-freetype.h"
+
+using namespace std;
+
+namespace
+{
+
+const unsigned int INITIAL_GLYPH_CAPACITY = 50;
+const double MIN_FONT_SIZE = 10;
+
+static glyphy_bool_t
+accumulate_endpoint( glyphy_arc_endpoint_t* endpoint,
+ vector<glyphy_arc_endpoint_t>* endpoints )
+{
+ endpoints->push_back( *endpoint );
+ return true;
+}
+
+} // unnamed namespace
+
+namespace Dali
+{
+
+namespace TextAbstraction
+{
+
+namespace Internal
+{
+
+typedef vector<VectorBlob> BlobArray;
+
+struct VectorGlyph
+{
+ /**
+ * @brief Create a vector-based glyph.
+ */
+ static VectorGlyph* New( FT_Face face,
+ FontId fontId,
+ GlyphIndex index,
+ glyphy_arc_accumulator_t* accumulator )
+ {
+ VectorGlyph* newGlyph = new VectorGlyph();
+ newGlyph->blobData.resize( 1024 * 16 );
+
+ if( FT_Err_Ok != FT_Load_Glyph( face,
+ index,
+ FT_LOAD_NO_BITMAP |
+ FT_LOAD_NO_HINTING |
+ FT_LOAD_NO_AUTOHINT |
+ FT_LOAD_NO_SCALE |
+ FT_LOAD_LINEAR_DESIGN |
+ FT_LOAD_IGNORE_TRANSFORM))
+ {
+ DALI_LOG_ERROR( "FT_Load_Glyph failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+
+ const double upem = static_cast<double>( face->units_per_EM );
+ const double tolerance = upem * 1.0f/2048.0f;
+
+ glyphy_arc_accumulator_reset( accumulator);
+ glyphy_arc_accumulator_set_tolerance( accumulator, tolerance );
+
+ vector<glyphy_arc_endpoint_t> endpoints;
+ glyphy_arc_accumulator_set_callback( accumulator,
+ reinterpret_cast<glyphy_arc_endpoint_accumulator_callback_t>( accumulate_endpoint ),
+ &endpoints );
+
+ if( FT_Err_Ok != glyphy_freetype_outline_decompose( &face->glyph->outline, accumulator ) )
+ {
+ DALI_LOG_ERROR( "glyphy_freetype_outline_decompose failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+
+ DALI_ASSERT_DEBUG( glyphy_arc_accumulator_get_error(accumulator) <= tolerance && "glyphy_arc_accumulator_get_error > tolerance" );
+
+ if( endpoints.size() )
+ {
+ glyphy_outline_winding_from_even_odd( &endpoints[0], endpoints.size (), false );
+ }
+
+ unsigned int blobLength( 0 );
+ double averageFetchAchieved( 0.0 );
+ if (!glyphy_arc_list_encode_blob( endpoints.size() ? &endpoints[0] : NULL,
+ endpoints.size(),
+ &newGlyph->blobData[0],
+ newGlyph->blobData.capacity(),
+ upem / ( MIN_FONT_SIZE * M_SQRT2 ),
+ 4,
+ &averageFetchAchieved,
+ &blobLength,
+ &newGlyph->nominalWidth,
+ &newGlyph->nominalHeight,
+ &newGlyph->extents ) )
+ {
+ DALI_LOG_ERROR( "glyphy_arc_list_encode_blob failed\n" );
+ delete newGlyph;
+ return NULL;
+ }
+ newGlyph->blobData.resize( blobLength );
+
+ glyphy_extents_scale( &newGlyph->extents, 1.0/upem, 1.0/upem );
+
+ newGlyph->glyphInfo.fontId = fontId;
+ newGlyph->glyphInfo.index = index;
+
+ if( glyphy_extents_is_empty( &newGlyph->extents ) )
+ {
+ newGlyph->glyphInfo.width = 0.0f;
+ newGlyph->glyphInfo.height = 0.0f;
+
+ newGlyph->glyphInfo.xBearing = 0.0f;
+ newGlyph->glyphInfo.yBearing = 0.0f;
+ }
+ else
+ {
+ newGlyph->glyphInfo.width = (newGlyph->extents.max_x - newGlyph->extents.min_x);
+ newGlyph->glyphInfo.height = (newGlyph->extents.max_y - newGlyph->extents.min_y);
+
+ newGlyph->glyphInfo.xBearing = newGlyph->extents.min_x;
+ newGlyph->glyphInfo.yBearing = newGlyph->glyphInfo.height + (newGlyph->extents.min_y);
+ }
+
+ newGlyph->glyphInfo.advance = face->glyph->metrics.horiAdvance / upem;
+ newGlyph->glyphInfo.scaleFactor = 0.0f;
+
+ return newGlyph;
+ }
+
+ VectorGlyph()
+ : advance( 0.0 ),
+ nominalWidth( 0 ),
+ nominalHeight( 0 ),
+ glyphInfo(),
+ blobData()
+ {
+ glyphy_extents_clear( &extents );
+ }
+
+ glyphy_extents_t extents;
+ double advance;
+ unsigned int nominalWidth;
+ unsigned int nominalHeight;
+ GlyphInfo glyphInfo;
+ BlobArray blobData;
+};
+
+typedef vector<VectorGlyph*> GlyphCache;
+
+struct VectorFont
+{
+ VectorFont( FT_Face face )
+ : mFace( face ),
+ mGlyphCache()
+ {
+ mGlyphCache.reserve( INITIAL_GLYPH_CAPACITY );
+ }
+
+ FT_Face mFace;
+ GlyphCache mGlyphCache;
+};
+
+struct VectorFontCache::Impl
+{
+ Impl( FT_Library freeTypeLibrary )
+ : mFreeTypeLibrary( freeTypeLibrary ),
+ mIdLookup(),
+ mVectorFonts(),
+ mAccumulator( NULL )
+ {
+ mAccumulator = glyphy_arc_accumulator_create();
+ }
+
+ ~Impl()
+ {
+ glyphy_arc_accumulator_destroy( mAccumulator );
+ }
+
+private:
+
+ // Declared private and left undefined to avoid copies.
+ Impl( const Impl& );
+ // Declared private and left undefined to avoid copies.
+ Impl& operator=( const Impl& );
+
+public:
+
+ FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance.
+
+ vector<string> mIdLookup;
+
+ vector<VectorFont*> mVectorFonts;
+
+ glyphy_arc_accumulator_t* mAccumulator;
+};
+
+VectorFontCache::VectorFontCache( FT_Library freeTypeLibrary )
+: mImpl( NULL )
+{
+ mImpl = new Impl( freeTypeLibrary );
+}
+
+VectorFontCache::~VectorFontCache()
+{
+ delete mImpl;
+}
+
+FontId VectorFontCache::GetFontId( const std::string& url )
+{
+ FontId id( 0 );
+
+ if( mImpl )
+ {
+ if( ! FindFont( url, id ) )
+ {
+ id = CreateFont( url );
+ }
+ }
+
+ return id;
+}
+
+void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo )
+{
+ if( mImpl )
+ {
+ if( vectorFontId > 0 &&
+ vectorFontId-1 < mImpl->mVectorFonts.size() )
+ {
+ VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
+ GlyphCache& cache = font->mGlyphCache;
+
+ bool foundGlyph( false );
+ unsigned int foundIndex( 0 );
+ for( unsigned int i=0; i<cache.size(); ++i )
+ {
+ VectorGlyph* glyph = cache[i];
+
+ if( glyph->glyphInfo.index == glyphInfo.index )
+ {
+ foundIndex = i;
+ foundGlyph = true;
+ break;
+ }
+ }
+
+ if( foundGlyph )
+ {
+ VectorGlyph* glyph = cache[foundIndex];
+ // Note - this clobbers the original fontId, but helps avoid duplicating identical blobs
+ // e.g. if when the same font family is requested in different point-sizes
+ glyphInfo = glyph->glyphInfo;
+ }
+ else
+ {
+ VectorGlyph* newGlyph = VectorGlyph::New( font->mFace,
+ glyphInfo.fontId,
+ glyphInfo.index,
+ mImpl->mAccumulator );
+
+ if( newGlyph )
+ {
+ glyphInfo = newGlyph->glyphInfo;
+
+ cache.push_back( newGlyph );
+ }
+ }
+ }
+ }
+}
+
+void VectorFontCache::GetVectorBlob( FontId vectorFontId,
+ FontId fontId,
+ GlyphIndex glyphIndex,
+ VectorBlob*& blob,
+ unsigned int& blobLength,
+ unsigned int& nominalWidth,
+ unsigned int& nominalHeight )
+{
+ if( mImpl )
+ {
+ if( vectorFontId > 0 &&
+ vectorFontId-1 < mImpl->mVectorFonts.size() )
+ {
+ VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ];
+ GlyphCache& cache = font->mGlyphCache;
+
+ bool foundGlyph( false );
+ unsigned int foundIndex( 0 );
+ for( unsigned int i=0; i<cache.size(); ++i )
+ {
+ VectorGlyph* glyph = cache[i];
+
+ if( glyph->glyphInfo.index == glyphIndex )
+ {
+ foundIndex = i;
+ foundGlyph = true;
+ break;
+ }
+ }
+
+ if( foundGlyph )
+ {
+ VectorGlyph* glyph = cache[foundIndex];
+
+ blob = &glyph->blobData[0];
+ blobLength = glyph->blobData.size();
+ nominalWidth = glyph->nominalWidth;
+ nominalHeight = glyph->nominalHeight;
+ }
+ else
+ {
+ VectorGlyph* newGlyph = VectorGlyph::New( font->mFace, fontId, glyphIndex, mImpl->mAccumulator );
+
+ if( newGlyph )
+ {
+ blob = &newGlyph->blobData[0];
+ blobLength = newGlyph->blobData.size();
+ nominalWidth = newGlyph->nominalWidth;
+ nominalHeight = newGlyph->nominalHeight;
+
+ cache.push_back( newGlyph );
+ }
+ }
+ }
+ }
+}
+
+bool VectorFontCache::FindFont( const string& url, FontId& vectorFontId ) const
+{
+ vectorFontId = 0u;
+
+ const vector<string>& idLookup = mImpl->mIdLookup;
+
+ for( unsigned int i=0; i<idLookup.size(); ++i, ++vectorFontId )
+ {
+ if( url == idLookup[i] )
+ {
+ ++vectorFontId;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+FontId VectorFontCache::CreateFont( const string& url )
+{
+ FontId id( 0 );
+
+ // Create & cache new font face
+ FT_Face face;
+ int error = FT_New_Face( mImpl->mFreeTypeLibrary,
+ url.c_str(),
+ 0,
+ &face );
+
+ if( FT_Err_Ok == error )
+ {
+ mImpl->mIdLookup.push_back( url );
+ id = mImpl->mIdLookup.size();
+
+ VectorFont* newFont = new VectorFont( face );
+ mImpl->mVectorFonts.push_back( newFont );
+
+ DALI_ASSERT_DEBUG( mImpl->mIdLookup.size() == mImpl->mVectorFonts.size() );
+ }
+
+ return id;
+}
+
+} // namespace Internal
+
+} // namespace TextAbstraction
+
+} // namespace Dali
+++ /dev/null
-# Add local source files here
-
-image_resampler_src_files = \
- $(static_libraries_image_resampler_src_dir)/resampler.cpp