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