Merge "Update image downloading functionality" into tizen
[platform/core/uifw/dali-adaptor.git] / adaptors / x11 / imf-manager-impl-x.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <imf-manager-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/events/key-event.h>
23 #include <dali/public-api/object/type-registry.h>
24 #include <dali/integration-api/debug.h>
25
26 // INTERNAL INCLUDES
27 #include <adaptor.h>
28 #include <window-render-surface.h>
29 #include <adaptor-impl.h>
30 #include <singleton-service-impl.h>
31 #include <virtual-keyboard-impl.h>
32
33 namespace Dali
34 {
35
36 namespace Internal
37 {
38
39 namespace Adaptor
40 {
41
42 namespace
43 {
44
45 #if defined(DEBUG_ENABLED)
46 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMF_MANAGER");
47 #endif
48
49 // Currently this code is internal to dali/dali/internal/event/text/utf8.h but should be made Public and used from there instead.
50 size_t Utf8SequenceLength(const unsigned char leadByte)
51 {
52   size_t length = 0;
53
54   if ((leadByte & 0x80) == 0 )          //ASCII character (lead bit zero)
55   {
56     length = 1;
57   }
58   else if (( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx
59   {
60     length = 2;
61   }
62   else if (( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx
63   {
64     length = 3;
65   }
66   else if (( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx
67   {
68     length = 4;
69   }
70
71   return length;
72 }
73
74 // Static function calls used by ecore 'c' style callback registration
75 void Commit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
76 {
77   if ( data )
78   {
79     ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
80     imfManager->CommitReceived( data, imfContext, event_info );
81   }
82 }
83
84 void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *event_info )
85 {
86   if ( data )
87   {
88     ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
89     imfManager->PreEditChanged( data, imfContext, event_info );
90   }
91 }
92
93 Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
94 {
95   if ( data )
96   {
97     ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
98     return imfManager->RetrieveSurrounding( data, imfContext, text, cursorPosition );
99   }
100   else
101   {
102     return false;
103   }
104 }
105
106 /**
107  * Called when an IMF delete surrounding event is received.
108  * Here we tell the application that it should delete a certain range.
109  */
110 void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
111 {
112   if ( data )
113   {
114     ImfManager* imfManager = reinterpret_cast< ImfManager* > ( data );
115     imfManager->DeleteSurrounding( data, imfContext, event_info );
116   }
117 }
118
119 BaseHandle Create()
120 {
121   return ImfManager::Get();
122 }
123
124 TypeRegistration IMF_MANAGER_TYPE( typeid(Dali::ImfManager), typeid(Dali::BaseHandle), Create );
125
126 } // unnamed namespace
127
128 bool ImfManager::IsAvailable()
129 {
130   bool available( false );
131
132   Dali::SingletonService service( SingletonService::Get() );
133   if ( service )
134   {
135     available = service.GetSingleton( typeid( Dali::ImfManager ) );
136   }
137
138   return available;
139 }
140
141 Dali::ImfManager ImfManager::Get()
142 {
143   Dali::ImfManager manager;
144
145   Dali::SingletonService service( SingletonService::Get() );
146   if ( service )
147   {
148     // Check whether the singleton is already created
149     Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ImfManager ) );
150     if( handle )
151     {
152       // If so, downcast the handle
153       manager = Dali::ImfManager( dynamic_cast< ImfManager* >( handle.GetObjectPtr() ) );
154     }
155     else if ( Adaptor::IsAvailable() )
156     {
157       // Create instance and register singleton only if the adaptor is available
158
159       Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) );
160       Any nativeWindow = adaptorImpl.GetNativeWindowHandle();
161
162       // The Ecore_X_Window needs to use the ImfManager.
163       // Only when the render surface is window, we can get the Ecore_X_Window.
164       Ecore_X_Window ecoreXwin( AnyCast<Ecore_X_Window>(nativeWindow) );
165       if (ecoreXwin)
166       {
167         // If we fail to get Ecore_X_Window, we can't use the ImfManager correctly.
168         // Thus you have to call "ecore_imf_context_client_window_set" somewhere.
169         // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent().
170
171         manager = Dali::ImfManager( new ImfManager( ecoreXwin ) );
172         service.Register( typeid( manager ), manager );
173       }
174       else
175       {
176         DALI_LOG_ERROR("Failed to get native window handle");
177       }
178     }
179   }
180
181   return manager;
182 }
183
184 ImfManager::ImfManager( Ecore_X_Window ecoreXwin )
185 : mIMFContext(),
186   mIMFCursorPosition( 0 ),
187   mSurroundingText(""),
188   mRestoreAfterFocusLost( false ),
189   mIdleCallbackConnected( false ),
190   mKeyEvents()
191 {
192   ecore_imf_init();
193   CreateContext( ecoreXwin );
194
195   ConnectCallbacks();
196   VirtualKeyboard::ConnectCallbacks( mIMFContext );
197 }
198
199 ImfManager::~ImfManager()
200 {
201   VirtualKeyboard::DisconnectCallbacks( mIMFContext );
202   DisconnectCallbacks();
203
204   DeleteContext();
205   ecore_imf_shutdown();
206 }
207
208 void ImfManager::CreateContext( Ecore_X_Window ecoreXwin )
209 {
210   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CreateContext\n" );
211
212   const char *contextId = ecore_imf_context_default_id_get();
213   if( contextId )
214   {
215     mIMFContext = ecore_imf_context_add( contextId );
216
217     if( mIMFContext )
218     {
219       if( ecoreXwin )
220       {
221         ecore_imf_context_client_window_set( mIMFContext, reinterpret_cast<void*>( ecoreXwin ) );
222       }
223     }
224     else
225     {
226       DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
227     }
228   }
229   else
230   {
231     DALI_LOG_WARNING("IMF Unable to get IMF Context\n");
232   }
233 }
234
235 void ImfManager::DeleteContext()
236 {
237   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteContext\n" );
238
239   if ( mIMFContext )
240   {
241     mIMFContext = NULL;
242   }
243 }
244
245 // Callbacks for predicitive text support.
246 void ImfManager::ConnectCallbacks()
247 {
248   if ( mIMFContext )
249   {
250     DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::ConnectCallbacks\n" );
251
252     ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED,    PreEdit,    this );
253     ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT,             Commit,     this );
254     ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this );
255
256     ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this);
257   }
258 }
259
260 void ImfManager::DisconnectCallbacks()
261 {
262   if ( mIMFContext )
263   {
264     DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DisconnectCallbacks\n" );
265
266     ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED,    PreEdit );
267     ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT,             Commit );
268     ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding );
269
270     // We do not need to unset the retrieve surrounding callback.
271   }
272 }
273
274 void ImfManager::Activate()
275 {
276   // Reset mIdleCallbackConnected
277   mIdleCallbackConnected = false;
278
279   if ( mIMFContext )
280   {
281     DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Activate\n" );
282
283     ecore_imf_context_focus_in( mIMFContext );
284
285     // emit keyboard activated signal
286     Dali::ImfManager handle( this );
287     mActivatedSignal.Emit( handle );
288   }
289 }
290
291 void ImfManager::Deactivate()
292 {
293   if( mIMFContext )
294   {
295     DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Deactivate\n" );
296
297     Reset();
298     ecore_imf_context_focus_out( mIMFContext );
299   }
300
301   // Reset mIdleCallbackConnected
302   mIdleCallbackConnected = false;
303 }
304
305 void ImfManager::Reset()
306 {
307   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::Reset\n" );
308
309   if ( mIMFContext )
310   {
311     ecore_imf_context_reset( mIMFContext );
312   }
313 }
314
315 Ecore_IMF_Context* ImfManager::GetContext()
316 {
317   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetContext\n" );
318
319   return mIMFContext;
320 }
321
322 bool ImfManager::RestoreAfterFocusLost() const
323 {
324   return mRestoreAfterFocusLost;
325 }
326
327 void ImfManager::SetRestoreAfterFocusLost( bool toggle )
328 {
329   mRestoreAfterFocusLost = toggle;
330 }
331
332 /**
333  * Called when an IMF Pre-Edit changed event is received.
334  * We are still predicting what the user is typing.  The latest string is what the IMF module thinks
335  * the user wants to type.
336  */
337 void ImfManager::PreEditChanged( void *, Ecore_IMF_Context *imfContext, void *event_info )
338 {
339   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::PreEditChanged\n" );
340
341   char *preEditString( NULL );
342   int cursorPosition( 0 );
343   Eina_List *attrs = NULL;
344   Eina_List *l = NULL;
345
346   Ecore_IMF_Preedit_Attr *attr;
347
348   // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string.
349   // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string.
350   ecore_imf_context_preedit_string_with_attributes_get( imfContext, &preEditString, &attrs, &cursorPosition );
351
352   if ( attrs )
353   {
354     // iterate through the list of attributes getting the type, start and end position.
355     for ( l = attrs, (attr =  (Ecore_IMF_Preedit_Attr*)eina_list_data_get(l) ); l; l = eina_list_next(l), ( attr = (Ecore_IMF_Preedit_Attr*)eina_list_data_get(l) ))
356     {
357 #ifdef DALI_PROFILE_UBUNTU
358       if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB3 ) // (Ecore_IMF)
359 #else // DALI_PROFILE_UBUNTU
360       if ( attr->preedit_type == ECORE_IMF_PREEDIT_TYPE_SUB4 ) // (Ecore_IMF)
361 #endif // DALI_PROFILE_UBUNTU
362       {
363         // 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.
364
365         size_t visualCharacterIndex = 0;
366         size_t byteIndex = 0;
367
368         // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ).
369         while ( preEditString[byteIndex] != '\0' )
370         {
371           // attr->end_index is provided as a byte position not character and we need to know the character position.
372           size_t currentSequenceLength = Utf8SequenceLength(preEditString[byteIndex]); // returns number of bytes used to represent character.
373           if ( byteIndex == attr->end_index )
374           {
375             cursorPosition = visualCharacterIndex;
376             break;
377             // end loop as found cursor position that matches byte position
378           }
379           else
380           {
381             byteIndex += currentSequenceLength; // jump to next character
382             visualCharacterIndex++;  // increment character count so we know our position for when we get a match
383           }
384
385           DALI_ASSERT_DEBUG( visualCharacterIndex < strlen( preEditString ));
386         }
387       }
388     }
389   }
390
391   if ( Dali::Adaptor::IsAvailable() )
392   {
393     std::string keyString ( preEditString );
394     int numberOfChars( 0 );
395
396     Dali::ImfManager handle( this );
397     Dali::ImfManager::ImfEventData imfEventData ( Dali::ImfManager::PREEDIT, keyString, cursorPosition, numberOfChars );
398     Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
399
400     if ( callbackData.update )
401     {
402       SetCursorPosition( callbackData.cursorPosition );
403       SetSurroundingText( callbackData.currentText );
404
405       NotifyCursorPosition();
406     }
407
408     if ( callbackData.preeditResetRequired )
409     {
410       Reset();
411     }
412   }
413   free( preEditString );
414 }
415
416 void ImfManager::CommitReceived( void *, Ecore_IMF_Context *imfContext, void *event_info )
417 {
418   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::CommitReceived\n" );
419
420   if ( Dali::Adaptor::IsAvailable() )
421   {
422     const std::string keyString( (char *)event_info );
423     const int cursorOffset( 0 );
424     const int numberOfChars( 0 );
425
426     Dali::ImfManager handle( this );
427     Dali::ImfManager::ImfEventData imfEventData ( Dali::ImfManager::COMMIT, keyString, cursorOffset, numberOfChars );
428     Dali::ImfManager::ImfCallbackData callbackData = mEventSignal.Emit( handle, imfEventData );
429
430     if ( callbackData.update )
431     {
432       SetCursorPosition( callbackData.cursorPosition );
433       SetSurroundingText( callbackData.currentText );
434
435       NotifyCursorPosition();
436     }
437   }
438 }
439
440 /**
441  * Called when an IMF retrieve surround event is received.
442  * Here the IMF module wishes to know the string we are working with and where within the string the cursor is
443  * We need to signal the application to tell us this information.
444  */
445 Eina_Bool ImfManager::RetrieveSurrounding( void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition )
446 {
447   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::RetrieveSurrounding\n" );
448
449   std::string keyString ( "" );
450   int cursorOffset( 0 );
451   int numberOfChars( 0 );
452
453   Dali::ImfManager::ImfEventData imfData ( Dali::ImfManager::GETSURROUNDING , keyString, cursorOffset, numberOfChars );
454   Dali::ImfManager handle( this );
455   mEventSignal.Emit( handle, imfData );
456
457   if ( text )
458   {
459     std::string surroundingText( GetSurroundingText() );
460
461     if ( !surroundingText.empty() )
462     {
463       *text = strdup( surroundingText.c_str() );
464     }
465     else
466     {
467       *text = strdup( "" );
468     }
469   }
470
471   if ( cursorPosition )
472   {
473     *cursorPosition = GetCursorPosition();
474   }
475
476
477   return EINA_TRUE;
478 }
479
480 /**
481  * Called when an IMF delete surrounding event is received.
482  * Here we tell the application that it should delete a certain range.
483  */
484 void ImfManager::DeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *event_info )
485 {
486   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::DeleteSurrounding\n" );
487
488   if ( Dali::Adaptor::IsAvailable() )
489   {
490     Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = (Ecore_IMF_Event_Delete_Surrounding*) event_info;
491
492     const std::string keyString( "" );
493     const int cursorOffset( deleteSurroundingEvent->offset );
494     const int numberOfChars( deleteSurroundingEvent->n_chars );
495
496     Dali::ImfManager::ImfEventData imfData ( Dali::ImfManager::DELETESURROUNDING , keyString, cursorOffset, numberOfChars );
497     Dali::ImfManager handle( this );
498     mEventSignal.Emit( handle, imfData );
499   }
500 }
501
502 void ImfManager::NotifyCursorPosition()
503 {
504   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::NotifyCursorPosition\n" );
505
506   if ( mIMFContext )
507   {
508     ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition );
509   }
510 }
511
512 int ImfManager::GetCursorPosition()
513 {
514   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetCursorPosition\n" );
515
516   return mIMFCursorPosition;
517 }
518
519 void ImfManager::SetCursorPosition( unsigned int cursorPosition )
520 {
521   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetCursorPosition\n" );
522
523   mIMFCursorPosition = ( int )cursorPosition;
524 }
525
526 void ImfManager::SetSurroundingText( std::string text )
527 {
528   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::SetSurroundingText\n" );
529
530   mSurroundingText = text;
531 }
532
533 std::string ImfManager::GetSurroundingText()
534 {
535   DALI_LOG_INFO( gLogFilter, Debug::General, "ImfManager::GetSurroundingText\n" );
536
537   return mSurroundingText;
538 }
539
540 } // Adaptor
541
542 } // Internal
543
544 } // Dali