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