Apply secure logs
[platform/framework/native/appfw.git] / src / app / FApp_AppManagerImpl.cpp
1 //
2 // Copyright (c) 2012 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  * @file        FApp_AppManagerImpl.cpp
19  * @brief       This is the implementation for the _AppManagerImpl class.
20  */
21
22 #include <memory>
23 #include <stdint.h>
24 #include <cstdio>
25 #include <unique_ptr.h>
26
27 #include <aul/aul.h>
28 #include <bundle.h>
29 #include <app_manager.h>
30 #include <Ecore.h>
31 #include <Ecore_X.h>
32 #include <X11/Xlib.h>
33
34 #include <FBaseInteger.h>
35 #include <FBaseObject.h>
36 #include <FBaseString.h>
37 #include <FBaseColArrayList.h>
38 #include <FBaseErrors.h>
39 #include <FAppAppControl.h>
40 #include <FAppAppManager.h>
41 #include <FAppSqlDataControl.h>
42 #include <FAppMapDataControl.h>
43 #include <FAppPkgPackageInfo.h>
44 #include <FAppIActiveAppEventListener.h>
45 #include <FBaseSysLog.h>
46 #include <FAppIAppControlListener.h>
47
48 #include <FBase_StringConverter.h>
49 #include <FBaseRt_LibraryImpl.h>
50 #include <FIo_DataControlResultSetImpl.h>
51
52 #include "FApp_AppControlRegistry.h"
53 #include "FApp_AppImpl.h"
54 #include "FApp_AppInfo.h"
55 #include "FApp_AppManagerEventArg.h"
56 #include "FApp_AppManagerImpl.h"
57 #include "FApp_AppManagerProxy.h"
58 #include "FApp_AppMessageImpl.h"
59 #include "FApp_AppControlImpl.h"
60 #include "FApp_ConditionManagerProxy.h"
61 #include "FApp_IAppManagerEventListener.h"
62 #include "FApp_IAppEventListener.h"
63 #include "FApp_MapDataControlImpl.h"
64 #include "FApp_SqlDataControlImpl.h"
65 #include "FAppPkg_PackageManagerImpl.h"
66 #include "FAppPkg_PackageInfoImpl.h"
67 #include "FApp_AppControlManager.h"
68 #include "FApp_Aul.h"
69 #include "FSys_SystemInfoImpl.h"
70
71 using namespace Tizen::App::Package;
72 using namespace Tizen::Base;
73 using namespace Tizen::Base::Collection;
74 using namespace Tizen::Base::Runtime;
75 using namespace Tizen::Base::Utility;
76 using namespace Tizen::Io;
77
78 namespace
79 {
80
81 //const long MAX_APPCONTROL_ARGUMENT = 4096;
82 const long MAX_APPCONTROL_ARGUMENT = 1024;
83 const long MAX_CONDITION_LENGTH = 400;
84
85 // ActiveWindow related function and variable from shared library.
86 // libecore_x.so.1
87 static Ecore_X_Atom(* p_ecore_x_atom_get)(const char* name) = null;
88 static int(* p_ecore_x_window_prop_window_get)(Ecore_X_Window win, Ecore_X_Atom atom, Ecore_X_Window* val, unsigned int len) = null;
89 static Eina_Bool(* p_ecore_x_netwm_pid_get)(Ecore_X_Window win, int* pid) = null;
90 static int(* p_ecore_x_netwm_name_get)(Ecore_X_Window win, char** name) = null;
91 static Ecore_X_Window* (* p_ecore_x_window_root_list)(int* num_ret) = null;
92 static int* p_ECORE_X_EVENT_WINDOW_PROPERTY = null;
93 // libecore.so.1
94 static Ecore_Event_Handler* (* p_ecore_event_handler_add)(int type, Ecore_Event_Handler_Cb func, const void* data) = null;
95 static void* (* p_ecore_event_handler_del)(Ecore_Event_Handler* event_handler) = null;
96 // libX11.so
97 static int (* p_XSelectInput)(Display* display, Window w, long event_mask) = null;
98 static Display* (* p_XOpenDisplay)(_Xconst char* display_name) = null;
99 static int (* p_XCloseDisplay)(Display* display) = null;
100
101 Ecore_Event_Handler* pWindowPropertyChanged = null;
102
103 struct _DisplayDeleter
104 {
105         void operator()(Display* pDisplay)
106         {
107                 if (p_XOpenDisplay)
108                 {
109                         p_XCloseDisplay(pDisplay);
110                 }
111         }
112 };
113
114 int
115 GetTotalSize(const Tizen::Base::Collection::ICollection& col)
116 {
117         int size = 0;
118         std::unique_ptr<IEnumerator> pEnum(col.GetEnumeratorN());
119
120         if (pEnum)
121         {
122                 while (pEnum->MoveNext() == E_SUCCESS)
123                 {
124                         String* pStr = static_cast<String*>(pEnum->GetCurrent());
125                         if (pStr == null)
126                         {
127                                 continue;
128                         }
129                         size += pStr->GetLength();
130                 }
131         }
132
133         return size;
134 }
135
136 Eina_Bool
137 OnPropertyChanged(void* pData, int type, void* pEvent)
138 {
139         using namespace Tizen::App;
140
141         if (p_ecore_x_atom_get == null)
142         {
143                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
144                 p_ecore_x_atom_get = reinterpret_cast<Ecore_X_Atom(*)(const char* name)>(lib.GetProcAddress(L"ecore_x_atom_get"));
145                 SysTryReturnResult(NID_APP, p_ecore_x_atom_get != null, EINA_FALSE,
146                                                    "A system error has been occurred. Failed to get ecore_x_atom_get.");
147         }
148         if (p_ecore_x_window_prop_window_get == null)
149         {
150                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
151                 p_ecore_x_window_prop_window_get = reinterpret_cast<int(*)(Ecore_X_Window win, Ecore_X_Atom atom, Ecore_X_Window* val, unsigned int len)>(lib.GetProcAddress(L"ecore_x_window_prop_window_get"));
152                 SysTryReturnResult(NID_APP, p_ecore_x_window_prop_window_get != null, EINA_FALSE,
153                                                    "A system error has been occurred. Failed to get ecore_x_window_prop_window_get.");
154         }
155         if (p_ecore_x_netwm_pid_get == null)
156         {
157                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
158                 p_ecore_x_netwm_pid_get = reinterpret_cast<Eina_Bool(*)(Ecore_X_Window win, int* pid)>(lib.GetProcAddress(L"ecore_x_netwm_pid_get"));
159                 SysTryReturnResult(NID_APP, p_ecore_x_netwm_pid_get != null, EINA_FALSE,
160                                                    "A system error has been occurred. Failed to get ecore_x_netwm_pid_get.");
161         }
162         if (p_ecore_x_netwm_name_get == null)
163         {
164                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
165                 p_ecore_x_netwm_name_get = reinterpret_cast<int(*)(Ecore_X_Window win, char** name)>(lib.GetProcAddress(L"ecore_x_netwm_name_get"));
166                 SysTryReturnResult(NID_APP, p_ecore_x_netwm_name_get != null, EINA_FALSE,
167                                                    "A system error has been occurred. Failed to get ecore_x_netwm_name_get.");
168         }
169
170         if (!pData)
171         {
172                 SysLog(NID_UI, "The data is not valid.");
173                 return EINA_FALSE;
174         }
175         if (!pEvent)
176         {
177                 SysLog(NID_UI, "The event is not valid.");
178                 return EINA_FALSE;
179         }
180
181         Ecore_X_Event_Window_Property* pE = (Ecore_X_Event_Window_Property*) pEvent;
182         Ecore_X_Atom atom = pE->atom;
183         Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW");
184
185         if (atom != activeAtom)
186         {
187                 return ECORE_CALLBACK_PASS_ON;
188         }
189
190         Ecore_X_Window win = pE->win;
191         Ecore_X_Window activeWin = 0;
192         p_ecore_x_window_prop_window_get(win, activeAtom, &activeWin, 1);
193
194         int pid = 0;
195         p_ecore_x_netwm_pid_get(activeWin, &pid);
196
197         char* pAppName = null;
198         p_ecore_x_netwm_name_get(activeWin, &pAppName);
199
200         Tizen::App::_AppManagerImpl* pAppManagerImpl = static_cast<Tizen::App::_AppManagerImpl*>(pData);
201         pAppManagerImpl->FireActiveAppEvent(activeWin, pid, pAppName);
202
203         if (pAppName)
204         {
205                 free(pAppName);
206         }
207
208         return ECORE_CALLBACK_PASS_ON;
209 }
210
211 } // anonymous name-space
212
213
214 namespace Tizen { namespace App
215 {
216
217 const wchar_t LEGACY_LAUNCH_REASON_NORMAL[] = L"LAUNCH_NORMAL";
218 const wchar_t LEGACY_LAUNCH_REASON_CONDITIONAL[] = L"LAUNCH_CONDITIONAL";
219 const wchar_t OSP_UI_SONAME[] = L"libosp-uifw.so.1";
220 const wchar_t OSP_ECORE_X_SONAME[] = L"libecore_x.so.1";
221 const wchar_t OSP_ECORE_SONAME[] = L"libecore.so.1";
222 const wchar_t OSP_X11_SONAME[] = L"libX11.so.6";
223 const int _MAX_PACKAGE_ID_LENGTH = 10;
224
225 _LibraryImpl* _AppManagerImpl::__pEcoreLibrary = null;
226 _LibraryImpl* _AppManagerImpl::__pEcoreXLibrary = null;
227
228 _AppManagerImpl::_AppManagerImpl(void)
229         : __pConditionManager(null)
230         , __eventListenerCount(0)
231         , __pUiLibrary(null)
232         , __pX11Library(null)
233 {
234         SysLog(NID_APP, "");
235 }
236
237 _AppManagerImpl::~_AppManagerImpl(void)
238 {
239         SysLog(NID_APP, "");
240
241         if (__activeAppEventListenerList.GetCount() > 0)
242         {
243                 if (p_ecore_event_handler_del == null)
244                 {
245                         _LibraryImpl& lib = GetEcoreLibraryImpl();
246                         p_ecore_event_handler_del = reinterpret_cast<void*(*)(Ecore_Event_Handler* event_handler)>(lib.GetProcAddress(L"ecore_event_handler_del"));
247                 }
248                 if (p_ecore_event_handler_del)
249                 {
250                         if (pWindowPropertyChanged)
251                         {
252                                 p_ecore_event_handler_del(pWindowPropertyChanged);
253                                 pWindowPropertyChanged = null;
254                         }
255                 }
256         }
257
258         delete __pConditionManager;
259         delete __pUiLibrary;
260         delete __pX11Library;
261         delete __pEcoreXLibrary;
262         __pEcoreXLibrary = null;
263         delete __pEcoreLibrary;
264         __pEcoreLibrary = null;
265 }
266
267
268 result
269 _AppManagerImpl::Construct(void)
270 {
271         __appManagerEvent.Construct();
272
273         _IAppManager* pMgr = _AppManagerProxy::GetService();
274         //todo : uncomment following _SysTryReturn or put assert.
275         //SysTryReturn(NID_APP, pMgr != null, GetLastResult(), GetLastResult(), "[%s]GetService failed. Please check 'ps -A | grep OspAppService'!", GetLastResult());
276         SysTryReturn(NID_APP, pMgr != null, E_SUCCESS, E_SUCCESS, "[E_SYSTEM] fatal error. Please check 'ps -A | grep osp-app-service'!", GetLastResult());
277         pMgr->InitEventListener(this);
278
279         return E_SUCCESS;
280 }
281
282 _AppManagerImpl*
283 _AppManagerImpl::GetInstance(void)
284 {
285         return AppManager::GetInstance()->__pAppManagerImpl;
286 }
287
288 _ConditionManagerProxy*
289 _AppManagerImpl::GetConditionManagerProxy(void)
290 {
291         if (__pConditionManager == null)
292         {
293                 __pConditionManager = new (std::nothrow) _ConditionManagerProxy;
294                 SysAssert(__pConditionManager != null);
295
296                 result r = __pConditionManager->Construct();
297                 SysAssertf(r == E_SUCCESS, "__pConditionManager->Construct() faliied [%s].", GetErrorMessage(r));
298         }
299
300         return __pConditionManager;
301 }
302
303 AppControl*
304 _AppManagerImpl::FindAppControlN(const AppId& aId, const String& oId)
305 {
306         _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance();
307
308         AppControl* pAc = null;
309
310         pAc = pRegs->GetTizenAppControlN(aId, oId);
311         if (pAc != null)
312         {
313                 SetLastResult(E_SUCCESS);
314                 return pAc;
315         }
316
317         pAc = pRegs->GetAppControlN(aId, oId);
318
319         SysTryReturn(NID_APP, pAc != null, null, E_OBJ_NOT_FOUND, "[%s] No matching AppControl instance found (%ls, %ls).",
320                                  GetErrorMessage(E_OBJ_NOT_FOUND), aId.GetPointer(), oId.GetPointer());
321         SetLastResult(E_SUCCESS);
322         return pAc;
323 }
324
325 IList*
326 _AppManagerImpl::FindAppControlsN(const String* pOperationId, const String* pCategory, const String* pDataType,
327                                                                   const String* pUriScheme)
328 {
329         SysTryReturn(NID_APP, !(pOperationId == null && pCategory == null && pUriScheme == null && pDataType == null), null,
330                                  E_INVALID_ARG, "[%s] At least one parameter should not be null.", GetErrorMessage(E_INVALID_ARG));
331
332         String mimeType;
333         const String* pMimeType = pDataType;
334
335         if (pDataType)
336         {
337                 if ((*pDataType)[0] == L'.')
338                 {
339                         SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer());
340
341                         String ext;
342                         pDataType->SubString(1, ext);
343
344                         result r = _AppControlManager::GetMimeFromExt(ext, mimeType);
345
346                         SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer());
347
348                         pMimeType = &mimeType;
349
350                         SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer());
351                 }
352         }
353
354         if (pUriScheme)
355         {
356                 SysTryReturn(NID_APP, !(pUriScheme->IsEmpty()), null, E_INVALID_FORMAT, "[%s] The specified URI scheme is invalid.",
357                                          GetErrorMessage(E_INVALID_FORMAT));
358         }
359
360         _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance();
361         ArrayList* pRetArg = pRegs->FindAppControlListN(pOperationId, pUriScheme, pMimeType, pCategory);
362
363         if ((pRetArg == null) || (pRetArg->GetCount() == 0))
364         {
365                 delete pRetArg;
366                 pRetArg = null;
367                 SetLastResult(E_OBJ_NOT_FOUND);
368                 return null;
369         }
370
371         SetLastResult(E_SUCCESS);
372         SysLog(NID_APP, "Found %d matching AppControls.", pRetArg->GetCount());
373
374         return pRetArg;
375 }
376
377
378 result
379 _AppManagerImpl::StartAppControl(const String& uri, const String* pOperationId, const String* pDataType,
380                                                                  IAppControlListener* pListener)
381 {
382         return StartAppControl(pOperationId, null, pDataType, &uri, null, pListener);
383 }
384
385
386 result
387 _AppManagerImpl::StartAppControl(const String* pOperationId, const String* pCategory, const String* pDataType,
388                                                                  const String* pUri, const IList* pDataList, IAppControlListener* pListener)
389 {
390         SysTryReturnResult(NID_APP, !(pOperationId == null && pUri == null && pCategory == null && pDataType == null), E_INVALID_ARG,
391                                                 "At least one of the specified argument must not be null.");
392         if (pDataList != null)
393         {
394                 int argSize = 0;
395                 argSize = GetTotalSize(*pDataList);
396
397                 SysLog(NID_APP, "Argument count = %d, size = %d", pDataList->GetCount(), argSize);
398
399                 SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED,
400                                                   "The size of pDataList exceeded the limit(%d).",
401                                                   MAX_APPCONTROL_ARGUMENT);
402         }
403
404         String operation = (pOperationId) ? *pOperationId : TIZEN_OPERATION_MAIN;
405
406         std::unique_ptr<bundle, BundleDeleter> pBundle(bundle_create());
407         SysTryReturnResult(NID_APP, pBundle.get(), E_OUT_OF_MEMORY, "Bundle creation failure.");
408
409         _AppMessageImpl::SetOperation(pBundle.get(), operation);
410
411         if (pUri)
412         {
413                 _AppMessageImpl::SetUri(pBundle.get(), *pUri);
414         }
415
416         if (pDataType)
417         {
418                 String mimeType = *pDataType;
419
420                 if ((*pDataType)[0] == L'.')
421                 {
422                         SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer());
423
424 #if 0
425                         String ext;
426                         pDataType->SubString(1, ext);
427
428                         result r = _AppControlManager::GetMimeFromExt(ext, mimeType);
429
430                         SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer());
431
432                         pMimeType = &mimeType;
433
434                         SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer());
435 #endif
436                 }
437
438                 _AppMessageImpl::SetMime(pBundle.get(), mimeType);
439         }
440
441         if (pCategory)
442         {
443                 _AppMessageImpl::SetCategory(pBundle.get(), *pCategory);
444         }
445
446         return _AppControlImpl::StartImplicit(pBundle.get(), pDataList, pListener);
447 }
448
449
450 SqlDataControl*
451 _AppManagerImpl::GetSqlDataControlN(const String& providerId)
452 {
453         SqlDataControl* pDc = null;
454         String type(L"Sql");
455         String* pAppId = null;
456         String* pAccess = null;
457         String appId;
458
459         // XXX: Need _NativeDataControlRegistry for SLP native app ?
460         // Try to searach SLP data control.
461 //      _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton
462 //      pDc = pReg->GetNativeSqlDataControlN(providerId);
463 //      if (pDc != null)
464 //      {
465 //              return pDc;
466 //      }
467
468         std::unique_ptr <IList, AllElementsDeleter> pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type));
469         SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist.");
470
471         pAppId = dynamic_cast< String* >(pList->GetAt(0));
472         SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
473         pAccess = dynamic_cast< String* >(pList->GetAt(1));
474         SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
475         pAccess->ToLower();
476
477         if (pAppId->StartsWith(L"org.tizen.", 0))
478         {
479                 std::unique_ptr<StringTokenizer> pStrTok(new (std::nothrow) StringTokenizer(*pAppId, L'.'));
480                 SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
481                 for (int i = 0; i < 3; ++i)
482                 {
483                         pStrTok->GetNextToken(appId);
484                 }
485
486                 appId[_MAX_PACKAGE_ID_LENGTH] = L'.';
487         }
488         else
489         {
490                 appId.Append(*pAppId);
491         }
492
493         pDc = _SqlDataControlImpl::CreateSqlDataControl(appId, providerId, *pAccess);
494         SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult()));
495
496         return pDc;
497 }
498
499 MapDataControl*
500 _AppManagerImpl::GetMapDataControlN(const String& providerId)
501 {
502         MapDataControl* pDc = null;
503         String type(L"Map");
504         String* pAppId = null;
505         String* pAccess = null;
506         String appId;
507
508         // XXX: Need _NativeDataControlRegistry for SLP native app ?
509         // Try to searach SLP data control.
510 //      _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton
511 //      pDc = pReg->GetNativeMapDataControlN(providerId);
512 //      if (pDc != null)
513 //      {
514 //              return pDc;
515 //      }
516
517         std::unique_ptr <IList, AllElementsDeleter> pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type));
518         SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist.");
519
520         pAppId = dynamic_cast< String* >(pList->GetAt(0));
521         SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
522         pAccess = dynamic_cast< String* >(pList->GetAt(1));
523         SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
524         pAccess->ToLower();
525
526         if (pAppId->StartsWith(L"org.tizen.", 0))
527         {
528                 std::unique_ptr<StringTokenizer> pStrTok( new (std::nothrow) StringTokenizer(*pAppId, L'.'));
529                 SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
530                 for (int i = 0; i < 3; ++i)
531                 {
532                         pStrTok->GetNextToken(appId);
533                 }
534
535                 appId[_MAX_PACKAGE_ID_LENGTH] = L'.';
536         }
537         else
538         {
539                 appId.Append(*pAppId);
540         }
541
542         pDc = _MapDataControlImpl::CreateMapDataControl(appId, providerId, *pAccess);
543         SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult()));
544
545         return pDc;
546 }
547
548 result
549 _AppManagerImpl::GetAppRootPath(const AppId& appId, String& appRootPath)
550 {
551         String pkgId = PackageManager::GetPackageIdByAppId(appId);
552         SysTryReturnResult(NID_APP, pkgId.IsEmpty() == false, E_APP_NOT_INSTALLED,
553                         "The application is not installed. (app: %ls)", appId.GetPointer());
554
555         _PackageManagerImpl* pPkgMgr = _PackageManagerImpl::GetInstance();
556         SysTryReturnResult(NID_APP, pPkgMgr != null, E_SYSTEM,
557                         "Failed to get _PackageManagerImpl instance.");
558
559         std::unique_ptr< PackageInfo >pPkgInfo(pPkgMgr->GetPackageInfoN(pkgId));
560         SysTryReturnResult(NID_APP, pPkgInfo != null, E_APP_NOT_INSTALLED,
561                         "The application is not installed. (app: %ls)", appId.GetPointer());
562
563         _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo.get());
564         SysTryReturnResult(NID_APP, pPkgInfoImpl != null, E_SYSTEM,
565                         "Failed to get _PackageInfoImpl instance.");
566
567         appRootPath = pPkgInfoImpl->GetAppRootPath();
568         appRootPath.Append(L"/");
569
570         return E_SUCCESS;
571 }
572
573 result
574 _AppManagerImpl::LaunchApplication(const String& appId, const IList* pArguments, AppManager::LaunchOption option)
575 {
576         SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_INVALID_ARG, "The appid is empty.");
577         SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_OBJ_NOT_FOUND,
578                                            "The target application(%ls) is not installed.", appId.GetPointer());
579 //      SysTryReturnResult(NID_APP,
580 //                                        appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED,
581 //                                        "The length of appid exceeded the limit(%d).",
582 //                                        WIDGET_APP_MAX_APPID_LENGTH);
583
584         std::unique_ptr<AppControl> pAc(_AppControlRegistry::GetInstance()->GetAppControlN(appId, TIZEN_OPERATION_MAIN));
585         SysTryReturnResult(NID_APP, pAc.get() != null, E_OBJ_NOT_FOUND, "The target application (%ls) is not found.", appId.GetPointer());
586
587         if (pArguments)
588         {
589                 int argSize = 0;
590                 argSize = GetTotalSize(*pArguments);
591
592                 SysLog(NID_APP, "Argument count = %d, size = %d", pArguments->GetCount(), argSize);
593
594                 SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED,
595                                                   "The size of pDataList exceeded the limit(%d).",
596                                                   MAX_APPCONTROL_ARGUMENT);
597         }
598
599         result r = pAc->Start(pArguments, null);
600
601         SysLog(NID_APP, "[%s] Launching %ls finished.", GetErrorMessage(r), appId.GetPointer());
602         return r;
603 }
604
605
606 result
607 _AppManagerImpl::LaunchApplication(const String& appId, AppManager::LaunchOption option)
608 {
609         SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_APP_NOT_INSTALLED, "The appid is empty.");
610
611         std::unique_ptr<char[]> pName(_StringConverter::CopyToCharArrayN(appId));
612
613         int ret = aul_open_app(pName.get());
614
615         if (ret > 0)
616         {
617                 SysLog(NID_APP, "Launching %ls successful.", appId.GetPointer());
618                 return E_SUCCESS;
619         }
620
621         // failure
622         SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_APP_NOT_INSTALLED,
623                                            "The target application(%ls) is not installed.", appId.GetPointer());
624
625         result r = E_SYSTEM;
626         switch (ret)
627         {
628         case AUL_R_EINVAL:
629                 r = E_APP_NOT_INSTALLED;
630                 break;
631         case AUL_R_OK:
632                 // r = E_SUCCESS;
633                 // never reach here
634                 break;
635         default:
636                 break;
637         }
638
639         SysLog(NID_APP, "[%s] Launching %ls failed.", GetErrorMessage(r), appId.GetPointer());
640         return r;
641 }
642
643
644 result
645 _AppManagerImpl::TerminateApplication(const AppId& appId)
646 {
647         _IAppManager* pMgr = _AppManagerProxy::GetService();
648         SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
649
650         return pMgr->TerminateApplication(appId);
651 }
652
653
654 static int
655 TerminateIterFnCb(const aul_app_info* pAppInfo, void* pData)
656 {
657         const char* pStr = static_cast<const char*>(pData);
658
659         if (pStr && strncmp(pStr, pAppInfo->pkg_name, _MAX_PACKAGE_ID_LENGTH) == 0)
660         {
661                 aul_terminate_pid(pAppInfo->pid);
662                 SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid);
663         }
664         return 0;
665 }
666
667 result
668 _AppManagerImpl::TerminateApplications(const PackageId& packageId)
669 {
670         std::unique_ptr<char[]> pPackage(_StringConverter::CopyToCharArrayN(packageId));
671         aul_app_get_running_app_info(TerminateIterFnCb, static_cast<void*>(pPackage.get()));
672
673         SysLog(NID_APP, "%ls terminated.", packageId.GetPointer());
674         return E_SUCCESS;
675 }
676
677 bool
678 _AppManagerImpl::IsRunning(const AppId& appId) const
679 {
680         std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
681
682         return aul_app_is_running(pAppId.get());
683 }
684
685 static int
686 AulAppInfoIterFnCb(const aul_app_info* pAppInfo, void* pData)
687 {
688         ArrayList* pList = static_cast<ArrayList*>(pData);
689         if (pList && pAppInfo && pAppInfo->appid)
690         {
691                 pList->Add(*new (std::nothrow) String(pAppInfo->appid));
692         }
693
694         return 0;
695 }
696
697 IList*
698 _AppManagerImpl::GetRunningAppListN(void) const
699 {
700         ArrayList* pRunningAppList = new (std::nothrow) ArrayList();
701         SysTryReturn(NID_APP, pRunningAppList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.",
702                                  GetErrorMessage(E_OUT_OF_MEMORY));
703         pRunningAppList->Construct();
704
705         int ret = aul_app_get_running_app_info(AulAppInfoIterFnCb, reinterpret_cast<void*>(pRunningAppList));
706         SysTryLog(NID_APP, ret == AUL_R_OK, "Getting running list failed.");
707
708         // according to the doxygen, GetRunningAppListN() does not return null pointer for no object
709         return pRunningAppList;
710 }
711
712
713 result
714 _AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& condition, const IList* pArguments,
715                                                                    AppManager::LaunchOption option)
716 {
717         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
718         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
719
720         Tizen::Base::Utility::StringTokenizer strTok(condition, L"=");
721         SysTryReturnResult(NID_APP, strTok.GetTokenCount() > 0, E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
722
723         String key;
724         result r = strTok.GetNextToken(key);
725         SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
726
727         bool ret = true;
728         if (key == L"Serial")
729         {
730                 r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/usb.accessory", ret);
731         }
732         else if (key == L"NFC")
733         {
734                 r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/network.nfc", ret);
735         }
736         SysTryReturnResult(NID_APP, ret != false, E_UNSUPPORTED_OPERATION, "Condition(%ls)", condition.GetPointer());
737
738         return pProxy->RegisterAppLaunch(appId, condition, pArguments, option);
739 }
740
741 result
742 _AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String* pCondition)
743 {
744         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
745         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
746
747         if (pCondition)
748         {
749                 SysTryReturnResult(NID_APP,
750                                                   !pCondition->IsEmpty() && pCondition->GetLength() < MAX_CONDITION_LENGTH, E_OBJ_NOT_FOUND,
751                                                   "No such a condition.");
752         }
753
754         return pProxy->UnregisterAppLaunch(appId, pCondition);
755 }
756
757 bool
758 _AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String* pCondition)
759 {
760         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
761         SysTryReturn(NID_APP, null != pProxy, false, E_INVALID_STATE, "[%s] ConditionManager instance must not be null.",
762                                  GetErrorMessage(E_INVALID_STATE));
763
764         ClearLastResult();
765         return pProxy->IsAppLaunchRegistered(appId, pCondition);
766 }
767
768 result
769 _AppManagerImpl::SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener)
770 {
771         return _AppImpl::GetInstance()->SetListener(appEvent, pListener);
772 }
773
774 result
775 _AppManagerImpl::OnServiceEventReceived(int clientId, const _AppManagerEventArg& arg)
776 {
777         SysLog(NID_APP, "app:%ls, appType:0x%x", arg.GetAppId().GetPointer(), arg.GetAppType());
778
779         _AppManagerEventArg* pArg = new (std::nothrow)_AppManagerEventArg(arg);
780         SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
781         __appManagerEvent.FireAsync(*pArg);
782         return E_SUCCESS;
783 }
784
785 result
786 _AppManagerImpl::OnTerminateApplicationRequested(int clientId)
787 {
788         SysLog(NID_APP, "");
789
790         return E_SUCCESS;
791 }
792
793 result
794 _AppManagerImpl::AddEventListener(_IAppManagerEventListener& listener)
795 {
796         _IAppManager* pMgr = _AppManagerProxy::GetService();
797         SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, "");
798
799         result r = __appManagerEvent.AddListener(listener);
800         SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r));
801
802         __eventListenerCount++;
803         SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount);
804
805         if( __eventListenerCount > 1)
806         {
807                 return E_SUCCESS;
808         }
809
810         return pMgr->AddEventListener(-1);
811 }
812
813 result
814 _AppManagerImpl::RemoveEventListener(_IAppManagerEventListener& listener)
815 {
816         _IAppManager* pMgr = _AppManagerProxy::GetService();
817         SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, "");
818
819         result r = __appManagerEvent.RemoveListener(listener);
820         SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r));
821
822         __eventListenerCount--;
823         SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount);
824
825         if (__eventListenerCount == 0)
826         {
827                 return pMgr->RemoveEventListener(-1);
828         }
829
830         return E_SUCCESS;
831 }
832
833
834 ///////////////////////////////////////////////////////////////////////////////
835 // LifecycleManager begins.
836 ///////////////////////////////////////////////////////////////////////////////
837
838 void
839 _AppLifecycleManager::Init(void)
840 {
841         aul_listen_app_launch_signal(LaunchCallback, this);
842         aul_listen_app_dead_signal(TerminateCallback, this);
843 }
844
845 void
846 _AppLifecycleManager::Fini(void)
847 {
848         aul_listen_app_launch_signal(NULL, NULL);
849         aul_listen_app_dead_signal(NULL, NULL);
850 }
851
852 result
853 _AppLifecycleManager::AddListener(_IAppEventListener& listener)
854 {
855         if (__pEventList == null)
856         {
857                 std::unique_ptr< LinkedListT<_IAppEventListener*> > pAppEventList(new LinkedListT<_IAppEventListener*>);
858                 SysTryReturnResult(NID_APP, pAppEventList, E_SYSTEM, "Memory allocation failed.");
859
860                 Init();
861
862                 __pEventList = pAppEventList.release();
863                 SysLog(NID_APP, "Registered app event listener.");
864         }
865
866         return __pEventList->Add(&listener);
867 }
868
869 result
870 _AppLifecycleManager::RemoveListener(_IAppEventListener& listener)
871 {
872         SysTryReturnResult(NID_APP,__pEventList != null, E_OBJ_NOT_FOUND, "_IEventListener list is empty.");
873
874         result r = __pEventList->Remove(&listener);
875
876         if (__pEventList->GetCount() == 0)
877         {
878                 Fini();
879
880                 delete __pEventList;
881                 __pEventList = null;
882         }
883
884         return r;
885 }
886
887 int
888 _AppLifecycleManager::LaunchCallback(int pid, void* pData)
889 {
890         _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
891         if (pImpl == null || pImpl->__pEventList == null)
892         {
893                 SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
894                 return -1;
895         }
896
897         char appId[255];
898         int ret = aul_app_get_appid_bypid(pid, appId, sizeof(appId));
899         if (ret != AUL_R_OK)
900         {
901                 SysLogException(NID_APP, E_SYSTEM, "Cannot acquire app for %d.", pid);
902                 return -1;
903         }
904
905         std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
906         if (pEnum.get())
907         {
908                 const String tmp = appId;
909                 pImpl->__map.Add(pid, tmp);
910
911                 while (pEnum->MoveNext() == E_SUCCESS)
912                 {
913                         _IAppEventListener* pListener = null;
914                         pEnum->GetCurrent(pListener);
915
916                         pListener->OnApplicationLaunched(tmp, pid);
917                 }
918         }
919
920         SysLog(NID_APP, "Finished invoking application event listener for %s, %d.", appId, pid);
921
922         return 0;
923 }
924
925 int
926 _AppLifecycleManager::TerminateCallback(int pid, void* pData)
927 {
928         _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
929         if (pImpl == null || pImpl->__pEventList == null)
930         {
931                 SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
932                 return -1;
933         }
934
935         // terminate callback cannot acquire appId from pid
936         String tmp;
937         result r = pImpl->__map.GetValue(pid, tmp);
938         if (r != E_SUCCESS)
939         {
940                 SysLog(NID_APP, "Cannot acquire app from pid %d.", pid);
941                 return -1;
942         }
943
944         pImpl->__map.Remove(pid);
945
946         std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
947         if (pEnum.get())
948         {
949                 while (pEnum->MoveNext() == E_SUCCESS)
950                 {
951                         _IAppEventListener* pListener = null;
952                         pEnum->GetCurrent(pListener);
953
954                         pListener->OnApplicationTerminated(tmp, pid);
955                 }
956         }
957
958         SysLog(NID_APP, "Finished invoking application event listener for %ls, %d.", tmp.GetPointer(), pid);
959
960         return 0;
961 }
962
963 ///////////////////////////////////////////////////////////////////////////////
964 // LifecycleManager ends.
965 ///////////////////////////////////////////////////////////////////////////////
966
967
968 result
969 _AppManagerImpl::AddAppEventListener(_IAppEventListener& listener)
970 {
971         return __lifeManager.AddListener(listener);
972 }
973
974 result
975 _AppManagerImpl::RemoveAppEventListener(_IAppEventListener& listener)
976 {
977         return __lifeManager.RemoveListener(listener);
978 }
979
980
981 _LibraryImpl&
982 _AppManagerImpl::GetUiLibraryImpl(void)
983 {
984         if (__pUiLibrary == null)
985         {
986                 __pUiLibrary = new (std::nothrow) _LibraryImpl;
987                 SysAssertf(__pUiLibrary != null, "_LibraryImpl allocation failure.");
988
989                 result r = __pUiLibrary->Construct(OSP_UI_SONAME);
990                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
991         }
992
993         return *__pUiLibrary;
994 }
995
996 _LibraryImpl&
997 _AppManagerImpl::GetEcoreXLibraryImpl(void)
998 {
999         if (__pEcoreXLibrary == null)
1000         {
1001                 __pEcoreXLibrary = new (std::nothrow) _LibraryImpl;
1002                 SysAssertf(__pEcoreXLibrary != null, "_LibraryImpl allocation failure.");
1003
1004                 result r = __pEcoreXLibrary->Construct(OSP_ECORE_X_SONAME);
1005                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
1006         }
1007         return *__pEcoreXLibrary;
1008 }
1009
1010 _LibraryImpl&
1011 _AppManagerImpl::GetEcoreLibraryImpl(void)
1012 {
1013         if (__pEcoreLibrary == null)
1014         {
1015                 __pEcoreLibrary = new (std::nothrow) _LibraryImpl;
1016                 SysAssertf(__pEcoreLibrary != null, "_LibraryImpl allocation failure.");
1017
1018                 result r = __pEcoreLibrary->Construct(OSP_ECORE_SONAME);
1019                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
1020         }
1021         return *__pEcoreLibrary;
1022 }
1023
1024 _LibraryImpl&
1025 _AppManagerImpl::GetX11LibraryImpl(void)
1026 {
1027         if (__pX11Library == null)
1028         {
1029                 __pX11Library = new (std::nothrow) _LibraryImpl;
1030                 SysAssertf(__pX11Library != null, "_LibraryImpl allocation failure.");
1031
1032                 result r = __pX11Library->Construct(OSP_X11_SONAME);
1033                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
1034         }
1035         return *__pX11Library;
1036 }
1037
1038 void
1039 _AppManagerImpl::FireActiveAppEvent(unsigned int xid, int pid, char* pAppName)
1040 {
1041         static int oldPid = 0;
1042         if (oldPid != pid)
1043         {
1044                 oldPid = pid;
1045                 std::unique_ptr<IEnumeratorT<Tizen::App::IActiveAppEventListener* > > pEnum(__activeAppEventListenerList.GetEnumeratorN());
1046                 if (pEnum.get())
1047                 {
1048                         while (pEnum->MoveNext() == E_SUCCESS)
1049                         {
1050                                 Tizen::App::IActiveAppEventListener* pListener = null;
1051                                 pEnum->GetCurrent(pListener);
1052                                 if (pListener)
1053                                 {
1054                                         char pkgname[255] = {0, };
1055                                         aul_app_get_pkgname_bypid(pid, pkgname, 255);
1056                                         // TODO: Translate it to package name --> AppId
1057                                         pListener->OnActiveAppChanged(AppId(pkgname));
1058                                 }
1059                         }
1060                 }
1061         }
1062 }
1063
1064 unsigned int
1065 _AppManagerImpl::GetActiveWindow(void)
1066 {
1067         if (p_ecore_x_window_root_list == null)
1068         {
1069                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1070                 p_ecore_x_window_root_list = reinterpret_cast<Ecore_X_Window*(*)(int* num_ret)>(lib.GetProcAddress(L"ecore_x_window_root_list"));
1071                 SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, 0,
1072                                                    "A system error has been occurred. Failed to get p_ecore_x_window_root_list.");
1073         }
1074         if (p_ecore_x_atom_get == null)
1075         {
1076                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1077                 p_ecore_x_atom_get = reinterpret_cast<Ecore_X_Atom(*)(const char* name)>(lib.GetProcAddress(L"ecore_x_atom_get"));
1078                 SysTryReturnResult(NID_APP, p_ecore_x_atom_get != null, 0,
1079                                                    "A system error has been occurred. Failed to get ecore_x_atom_get.");
1080         }
1081         if (p_ecore_x_window_prop_window_get == null)
1082         {
1083                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1084                 p_ecore_x_window_prop_window_get = reinterpret_cast<int(*)(Ecore_X_Window win, Ecore_X_Atom atom, Ecore_X_Window* val, unsigned int len)>(lib.GetProcAddress(L"ecore_x_window_prop_window_get"));
1085                 SysTryReturnResult(NID_APP, p_ecore_x_window_prop_window_get != null, EINA_FALSE,
1086                                                    "A system error has been occurred. Failed to get ecore_x_window_prop_window_get.");
1087         }
1088
1089         int num = 0;
1090         Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
1091
1092         Ecore_X_Window activeWin = 0;
1093         if (pRoots)
1094         {
1095                 Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW");
1096                 p_ecore_x_window_prop_window_get(pRoots[0], activeAtom, &activeWin, 1);
1097                 free(pRoots);
1098         }
1099
1100         return activeWin;
1101 }
1102
1103 int
1104 _AppManagerImpl::GetProcessId(unsigned int window)
1105 {
1106         if (p_ecore_x_netwm_pid_get == null)
1107         {
1108                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1109                 p_ecore_x_netwm_pid_get = reinterpret_cast<Eina_Bool(*)(Ecore_X_Window win, int* pid)>(lib.GetProcAddress(L"ecore_x_netwm_pid_get"));
1110                 SysTryReturnResult(NID_APP, p_ecore_x_netwm_pid_get != null, EINA_FALSE,
1111                                                    "A system error has been occurred. Failed to get ecore_x_netwm_pid_get.");
1112         }
1113
1114         int pid = 0;
1115         p_ecore_x_netwm_pid_get(window, &pid);
1116
1117         return pid;
1118 }
1119
1120 result
1121 _AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener)
1122 {
1123         if (p_ecore_x_window_root_list == null)
1124         {
1125                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1126                 p_ecore_x_window_root_list = reinterpret_cast<Ecore_X_Window*(*)(int* num_ret)>(lib.GetProcAddress(L"ecore_x_window_root_list"));
1127                 SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, E_SYSTEM,
1128                                                    "A system error has been occurred. Failed to get p_ecore_x_window_root_list.");
1129         }
1130         if (p_ECORE_X_EVENT_WINDOW_PROPERTY == null)
1131         {
1132                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1133                 p_ECORE_X_EVENT_WINDOW_PROPERTY = reinterpret_cast<int*>(lib.GetProcAddress(L"ECORE_X_EVENT_WINDOW_PROPERTY"));
1134                 SysTryReturnResult(NID_APP, p_ECORE_X_EVENT_WINDOW_PROPERTY != null, E_SYSTEM,
1135                                                    "A system error has been occurred. Failed to get p_ECORE_X_EVENT_WINDOW_PROPERTY.");
1136         }
1137         if (p_XOpenDisplay == null)
1138         {
1139                 _LibraryImpl& lib = GetX11LibraryImpl();
1140                 p_XOpenDisplay = reinterpret_cast<Display*(*)(_Xconst char* display_name)>(lib.GetProcAddress(L"XOpenDisplay"));
1141                 SysTryReturnResult(NID_APP, p_XOpenDisplay != null, E_SYSTEM,
1142                                                    "A system error has been occurred. Failed to get p_XOpenDisplay.");
1143         }
1144         if (p_XCloseDisplay == null)
1145         {
1146                 _LibraryImpl& lib = GetX11LibraryImpl();
1147                 p_XCloseDisplay = reinterpret_cast<int(*)(Display* display)>(lib.GetProcAddress(L"XCloseDisplay"));
1148                 SysTryReturnResult(NID_APP, p_XCloseDisplay != null, E_SYSTEM,
1149                                                    "A system error has been occurred. Failed to get p_XCloseDisplay.");
1150         }
1151         if (p_XSelectInput == null)
1152         {
1153                 _LibraryImpl& lib = GetX11LibraryImpl();
1154                 p_XSelectInput = reinterpret_cast<int(*)(Display* display, Window w, long event_mask)>(lib.GetProcAddress(L"XSelectInput"));
1155                 SysTryReturnResult(NID_APP, p_XSelectInput != null, E_SYSTEM,
1156                                                    "A system error has been occurred. Failed to get p_XSelectInput.");
1157         }
1158         if (p_ecore_event_handler_add == null)
1159         {
1160                 _LibraryImpl& lib = GetEcoreLibraryImpl();
1161                 p_ecore_event_handler_add = reinterpret_cast<Ecore_Event_Handler*(*)(int type, Ecore_Event_Handler_Cb func, const void* data)>(lib.GetProcAddress(L"ecore_event_handler_add"));
1162                 SysTryReturnResult(NID_APP, p_ecore_event_handler_add != null, E_SYSTEM,
1163                                                    "A system error has been occurred. Failed to get p_ecore_event_handler_add.");
1164         }
1165
1166         bool alreadyExist = __activeAppEventListenerList.Contains(&listener);
1167         SysTryReturnResult(NID_APP, !alreadyExist, E_OBJ_ALREADY_EXIST, "The event listener already exist.");
1168         result r = __activeAppEventListenerList.Add(&listener);
1169         SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r));
1170
1171         if (!pWindowPropertyChanged)
1172         {
1173                 std::unique_ptr<Display, _DisplayDeleter> pDisplay(p_XOpenDisplay(NULL));
1174                 SysTryReturnResult(NID_APP, pDisplay != null, E_SYSTEM, "A system error has been occurred. Failed to XOpenDisplay.");
1175
1176                 int num = 0;
1177                 Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
1178                 SysTryReturnResult(NID_APP, pRoots != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
1179
1180                 for (int i = 0; i < num; i++)
1181                 {
1182                         p_XSelectInput(pDisplay.get(), pRoots[i], PropertyChangeMask);
1183                 }
1184
1185                 pWindowPropertyChanged = p_ecore_event_handler_add(*p_ECORE_X_EVENT_WINDOW_PROPERTY, OnPropertyChanged, (void*) this);
1186                 free(pRoots);
1187                 SysTryReturnResult(NID_APP, pWindowPropertyChanged, E_SYSTEM, "A system error has been occurred.");
1188         }
1189
1190         return r;
1191 }
1192
1193 result
1194 _AppManagerImpl::RemoveActiveAppEventListener(IActiveAppEventListener& listener)
1195 {
1196         if (p_ecore_event_handler_del == null)
1197         {
1198                 _LibraryImpl& lib = GetEcoreLibraryImpl();
1199                 p_ecore_event_handler_del = reinterpret_cast<void*(*)(Ecore_Event_Handler* event_handler)>(lib.GetProcAddress(L"ecore_event_handler_del"));
1200                 SysTryReturnResult(NID_APP, p_ecore_event_handler_del != null, E_SYSTEM,
1201                                                    "A system error has been occurred. Failed to get p_ecore_event_handler_del.");
1202         }
1203
1204         result r = __activeAppEventListenerList.Remove(&listener);
1205         SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r));
1206
1207         if (__activeAppEventListenerList.GetCount() == 0)
1208         {
1209                 p_ecore_event_handler_del(pWindowPropertyChanged);
1210                 pWindowPropertyChanged = null;
1211         }
1212
1213         return r;
1214 }
1215
1216 result
1217 _AppManagerImpl::GetActiveApp(AppId& appId)
1218 {
1219         unsigned int windowId = GetActiveWindow();
1220         int processId = GetProcessId(windowId);
1221         char pkgname[255] = {0, };
1222         aul_app_get_pkgname_bypid(processId, pkgname, 255);
1223         // TODO: Translate it to package name --> AppId
1224         appId = pkgname;
1225         return E_SUCCESS;
1226 }
1227
1228 }} // Tizen::App