Merge "Update PowerManager Implementation" 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         std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
699
700         return aul_app_is_running(pAppId.get());
701 }
702
703 static int
704 AulAppInfoIterFnCb(const aul_app_info* pAppInfo, void* pData)
705 {
706         ArrayList* pList = static_cast<ArrayList*>(pData);
707         if (pList && pAppInfo && pAppInfo->appid)
708         {
709                 pList->Add(*new (std::nothrow) String(pAppInfo->appid));
710         }
711
712         return 0;
713 }
714
715 IList*
716 _AppManagerImpl::GetRunningAppListN(void) const
717 {
718         ArrayList* pRunningAppList = new (std::nothrow) ArrayList();
719         SysTryReturn(NID_APP, pRunningAppList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.",
720                                  GetErrorMessage(E_OUT_OF_MEMORY));
721         pRunningAppList->Construct();
722
723         int ret = aul_app_get_running_app_info(AulAppInfoIterFnCb, reinterpret_cast<void*>(pRunningAppList));
724         SysTryLog(NID_APP, ret == AUL_R_OK, "Getting running list failed.");
725
726         // according to the doxygen, GetRunningAppListN() does not return null pointer for no object
727         return pRunningAppList;
728 }
729
730
731 result
732 _AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& condition, const IList* pArguments,
733                                                                    AppManager::LaunchOption option)
734 {
735         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
736         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
737
738         return pProxy->RegisterAppLaunch(appId, condition, pArguments, option);
739 }
740
741 result
742 _AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String* pCondition)
743 {
744         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
745         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
746
747         if (pCondition)
748         {
749                 SysTryReturnResult(NID_APP,
750                                                   !pCondition->IsEmpty() && pCondition->GetLength() < MAX_CONDITION_LENGTH, E_OBJ_NOT_FOUND,
751                                                   "No such a condition.");
752         }
753
754         return pProxy->UnregisterAppLaunch(appId, pCondition);
755 }
756
757 bool
758 _AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String* pCondition)
759 {
760         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
761         SysTryReturn(NID_APP, null != pProxy, false, E_INVALID_STATE, "[%s] ConditionManager instance must not be null.",
762                                  GetErrorMessage(E_INVALID_STATE));
763
764         ClearLastResult();
765         return pProxy->IsAppLaunchRegistered(appId, pCondition);
766 }
767
768 result
769 _AppManagerImpl::SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener)
770 {
771         return _AppImpl::GetInstance()->SetListener(appEvent, pListener);
772 }
773
774 result
775 _AppManagerImpl::OnServiceEventReceived(int clientId, const _AppManagerEventArg& arg)
776 {
777         SysLog(NID_APP, "appId:%ls, appType:0x%x", arg.GetAppId().GetPointer(), arg.GetAppType());
778
779         _AppManagerEventArg* pArg = new (std::nothrow)_AppManagerEventArg(arg);
780         SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
781         __appManagerEvent.FireAsync(*pArg);
782         return E_SUCCESS;
783 }
784
785 result
786 _AppManagerImpl::OnTerminateApplicationRequested(int clientId)
787 {
788         SysLog(NID_APP, "");
789
790         return E_SUCCESS;
791 }
792
793 result
794 _AppManagerImpl::AddEventListener(_IAppManagerEventListener& listener)
795 {
796         _IAppManager* pMgr = _AppManagerProxy::GetService();
797         SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, "");
798
799         result r = __appManagerEvent.AddListener(listener);
800         SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r));
801
802         __eventListenerCount++;
803         SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount);
804
805         if( __eventListenerCount > 1)
806         {
807                 return E_SUCCESS;
808         }
809
810         return pMgr->AddEventListener(-1);
811 }
812
813 result
814 _AppManagerImpl::RemoveEventListener(_IAppManagerEventListener& listener)
815 {
816         _IAppManager* pMgr = _AppManagerProxy::GetService();
817         SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, "");
818
819         result r = __appManagerEvent.RemoveListener(listener);
820         SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r));
821
822         __eventListenerCount--;
823         SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount);
824
825         if (__eventListenerCount == 0)
826         {
827                 return pMgr->RemoveEventListener(-1);
828         }
829
830         return E_SUCCESS;
831 }
832
833
834 void
835 _AppManagerImpl::AppEventCallback(app_context_h app_context, app_context_event_e event, void* pData)
836 {
837         _AppManagerImpl* pImpl = static_cast<_AppManagerImpl*>(pData);
838         if (pImpl == null || pImpl->__pAppEventList == null)
839         {
840                 SysLogException(NID_APP, E_SYSTEM, "Wrong _AppManagerImpl state.");
841                 return;
842         }
843
844         std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pAppEventList->GetEnumeratorN());
845
846         if (pEnum.get())
847         {
848                 char* pAppId = NULL;
849                 app_context_get_app_id(app_context, &pAppId);
850                 if (pAppId == NULL)
851                 {
852                         SysLogException(NID_APP, E_SYSTEM, "Cannot acquire appId.");
853                         return;
854                 }
855
856                 const String appId = pAppId;
857
858                 free(pAppId);
859
860                 pid_t pid = -1;
861                 app_context_get_pid(app_context, &pid);
862                 const int val = event;
863
864                 // loop unfolding
865                 switch (val)
866                 {
867                 case APP_CONTEXT_EVENT_LAUNCHED:
868                         while (pEnum->MoveNext() == E_SUCCESS)
869                         {
870                                 _IAppEventListener* pListener = null;
871                                 pEnum->GetCurrent(pListener);
872
873                                 pListener->OnApplicationLaunched(appId, pid);
874                         }
875                         break;
876                 case APP_CONTEXT_EVENT_TERMINATED:
877                         while (pEnum->MoveNext() == E_SUCCESS)
878                         {
879                                 _IAppEventListener* pListener = null;
880                                 pEnum->GetCurrent(pListener);
881
882                                 pListener->OnApplicationTerminated(appId, pid);
883                         }
884                         break;
885                 default:
886                         SysLog(NID_APP, "Invalid state.");
887                         break;
888                 }
889         }
890
891         SysLog(NID_APP, "Finished invoking application event listener.");
892 }
893
894 result
895 _AppManagerImpl::AddAppEventListener(_IAppEventListener& listener)
896 {
897         if (__pAppEventList == null)
898         {
899                 std::unique_ptr< LinkedListT<_IAppEventListener*> > pAppEventList(new LinkedListT<_IAppEventListener*>);
900                 SysTryReturnResult(NID_APP, pAppEventList, E_SYSTEM, "Memory allocation failed.");
901
902                 const int ret = app_manager_set_app_context_event_cb(_AppManagerImpl::AppEventCallback, this);
903                 SysTryReturnResult(NID_APP, ret == APP_MANAGER_ERROR_NONE, E_SYSTEM, "Context registration failed.");
904
905                 __pAppEventList = pAppEventList.release();
906                 SysLog(NID_APP, "Registered app event listener.");
907         }
908
909         return __pAppEventList->Add(&listener);
910 }
911
912 result
913 _AppManagerImpl::RemoveAppEventListener(_IAppEventListener& listener)
914 {
915         result r = E_SUCCESS;
916
917         SysTryReturnResult(NID_APP,__pAppEventList != null, E_OBJ_NOT_FOUND, "_IAppEventListener list is empty.");
918
919         r = __pAppEventList->Remove(&listener);
920
921         if (__pAppEventList->GetCount() == 0)
922         {
923                 app_manager_unset_app_context_event_cb();
924
925                 delete __pAppEventList;
926                 __pAppEventList = null;
927         }
928
929         return E_SUCCESS;
930 }
931
932
933 _LibraryImpl&
934 _AppManagerImpl::GetUiLibraryImpl(void)
935 {
936         if (__pUiLibrary == null)
937         {
938                 __pUiLibrary = new (std::nothrow) _LibraryImpl;
939                 SysAssertf(__pUiLibrary != null, "_LibraryImpl allocation failure.");
940
941                 result r = __pUiLibrary->Construct(OSP_UI_SONAME);
942                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
943         }
944
945         return *__pUiLibrary;
946 }
947
948 _LibraryImpl&
949 _AppManagerImpl::GetEcoreXLibraryImpl(void)
950 {
951         if (__pEcoreXLibrary == null)
952         {
953                 __pEcoreXLibrary = new (std::nothrow) _LibraryImpl;
954                 SysAssertf(__pEcoreXLibrary != null, "_LibraryImpl allocation failure.");
955
956                 result r = __pEcoreXLibrary->Construct(OSP_ECORE_X_SONAME);
957                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
958         }
959         return *__pEcoreXLibrary;
960 }
961
962 _LibraryImpl&
963 _AppManagerImpl::GetEcoreLibraryImpl(void)
964 {
965         if (__pEcoreLibrary == null)
966         {
967                 __pEcoreLibrary = new (std::nothrow) _LibraryImpl;
968                 SysAssertf(__pEcoreLibrary != null, "_LibraryImpl allocation failure.");
969
970                 result r = __pEcoreLibrary->Construct(OSP_ECORE_SONAME);
971                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
972         }
973         return *__pEcoreLibrary;
974 }
975
976 _LibraryImpl&
977 _AppManagerImpl::GetX11LibraryImpl(void)
978 {
979         if (__pX11Library == null)
980         {
981                 __pX11Library = new (std::nothrow) _LibraryImpl;
982                 SysAssertf(__pX11Library != null, "_LibraryImpl allocation failure.");
983
984                 result r = __pX11Library->Construct(OSP_X11_SONAME);
985                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
986         }
987         return *__pX11Library;
988 }
989
990 void
991 _AppManagerImpl::FireActiveAppEvent(unsigned int xid, int pid, char* pAppName)
992 {
993         static int oldPid = 0;
994         if (oldPid != pid)
995         {
996                 oldPid = pid;
997                 std::unique_ptr<IEnumeratorT<Tizen::App::IActiveAppEventListener* > > pEnum(__activeAppEventListenerList.GetEnumeratorN());
998                 if (pEnum.get())
999                 {
1000                         while (pEnum->MoveNext() == E_SUCCESS)
1001                         {
1002                                 Tizen::App::IActiveAppEventListener* pListener = null;
1003                                 pEnum->GetCurrent(pListener);
1004                                 if (pListener)
1005                                 {
1006                                         char pkgname[255] = {0, };
1007                                         aul_app_get_pkgname_bypid(pid, pkgname, 255);
1008                                         // TODO: Translate it to package name --> AppId
1009                                         pListener->OnActiveAppChanged(AppId(pkgname));
1010                                 }
1011                         }
1012                 }
1013         }
1014 }
1015
1016 unsigned int
1017 _AppManagerImpl::GetActiveWindow(void)
1018 {
1019         if (p_ecore_x_window_root_list == null)
1020         {
1021                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1022                 p_ecore_x_window_root_list = reinterpret_cast<Ecore_X_Window*(*)(int* num_ret)>(lib.GetProcAddress(L"ecore_x_window_root_list"));
1023                 SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, 0,
1024                                                    "A system error has been occurred. Failed to get p_ecore_x_window_root_list.");
1025         }
1026         if (p_ecore_x_atom_get == null)
1027         {
1028                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1029                 p_ecore_x_atom_get = reinterpret_cast<Ecore_X_Atom(*)(const char* name)>(lib.GetProcAddress(L"ecore_x_atom_get"));
1030                 SysTryReturnResult(NID_APP, p_ecore_x_atom_get != null, 0,
1031                                                    "A system error has been occurred. Failed to get ecore_x_atom_get.");
1032         }
1033         if (p_ecore_x_window_prop_window_get == null)
1034         {
1035                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1036                 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"));
1037                 SysTryReturnResult(NID_APP, p_ecore_x_window_prop_window_get != null, EINA_FALSE,
1038                                                    "A system error has been occurred. Failed to get ecore_x_window_prop_window_get.");
1039         }
1040
1041         int num = 0;
1042         Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
1043
1044         Ecore_X_Window activeWin = 0;
1045         if (pRoots)
1046         {
1047                 Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW");
1048                 p_ecore_x_window_prop_window_get(pRoots[0], activeAtom, &activeWin, 1);
1049                 free(pRoots);
1050         }
1051
1052         return activeWin;
1053 }
1054
1055 int
1056 _AppManagerImpl::GetProcessId(unsigned int window)
1057 {
1058         if (p_ecore_x_netwm_pid_get == null)
1059         {
1060                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1061                 p_ecore_x_netwm_pid_get = reinterpret_cast<Eina_Bool(*)(Ecore_X_Window win, int* pid)>(lib.GetProcAddress(L"ecore_x_netwm_pid_get"));
1062                 SysTryReturnResult(NID_APP, p_ecore_x_netwm_pid_get != null, EINA_FALSE,
1063                                                    "A system error has been occurred. Failed to get ecore_x_netwm_pid_get.");
1064         }
1065
1066         int pid = 0;
1067         p_ecore_x_netwm_pid_get(window, &pid);
1068
1069         return pid;
1070 }
1071
1072 result
1073 _AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener)
1074 {
1075         if (p_ecore_x_window_root_list == null)
1076         {
1077                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1078                 p_ecore_x_window_root_list = reinterpret_cast<Ecore_X_Window*(*)(int* num_ret)>(lib.GetProcAddress(L"ecore_x_window_root_list"));
1079                 SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, E_SYSTEM,
1080                                                    "A system error has been occurred. Failed to get p_ecore_x_window_root_list.");
1081         }
1082         if (p_ECORE_X_EVENT_WINDOW_PROPERTY == null)
1083         {
1084                 _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
1085                 p_ECORE_X_EVENT_WINDOW_PROPERTY = reinterpret_cast<int*>(lib.GetProcAddress(L"ECORE_X_EVENT_WINDOW_PROPERTY"));
1086                 SysTryReturnResult(NID_APP, p_ECORE_X_EVENT_WINDOW_PROPERTY != null, E_SYSTEM,
1087                                                    "A system error has been occurred. Failed to get p_ECORE_X_EVENT_WINDOW_PROPERTY.");
1088         }
1089         if (p_XOpenDisplay == null)
1090         {
1091                 _LibraryImpl& lib = GetX11LibraryImpl();
1092                 p_XOpenDisplay = reinterpret_cast<Display*(*)(_Xconst char* display_name)>(lib.GetProcAddress(L"XOpenDisplay"));
1093                 SysTryReturnResult(NID_APP, p_XOpenDisplay != null, E_SYSTEM,
1094                                                    "A system error has been occurred. Failed to get p_XOpenDisplay.");
1095         }
1096         if (p_XCloseDisplay == null)
1097         {
1098                 _LibraryImpl& lib = GetX11LibraryImpl();
1099                 p_XCloseDisplay = reinterpret_cast<int(*)(Display* display)>(lib.GetProcAddress(L"XCloseDisplay"));
1100                 SysTryReturnResult(NID_APP, p_XCloseDisplay != null, E_SYSTEM,
1101                                                    "A system error has been occurred. Failed to get p_XCloseDisplay.");
1102         }
1103         if (p_XSelectInput == null)
1104         {
1105                 _LibraryImpl& lib = GetX11LibraryImpl();
1106                 p_XSelectInput = reinterpret_cast<int(*)(Display* display, Window w, long event_mask)>(lib.GetProcAddress(L"XSelectInput"));
1107                 SysTryReturnResult(NID_APP, p_XSelectInput != null, E_SYSTEM,
1108                                                    "A system error has been occurred. Failed to get p_XSelectInput.");
1109         }
1110         if (p_ecore_event_handler_add == null)
1111         {
1112                 _LibraryImpl& lib = GetEcoreLibraryImpl();
1113                 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"));
1114                 SysTryReturnResult(NID_APP, p_ecore_event_handler_add != null, E_SYSTEM,
1115                                                    "A system error has been occurred. Failed to get p_ecore_event_handler_add.");
1116         }
1117
1118         bool alreadyExist = __activeAppEventListenerList.Contains(&listener);
1119         SysTryReturnResult(NID_APP, !alreadyExist, E_OBJ_ALREADY_EXIST, "The event listener already exist.");
1120         result r = __activeAppEventListenerList.Add(&listener);
1121         SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r));
1122
1123         if (!pWindowPropertyChanged)
1124         {
1125                 std::unique_ptr<Display, _DisplayDeleter> pDisplay(p_XOpenDisplay(NULL));
1126                 SysTryReturnResult(NID_APP, pDisplay != null, E_SYSTEM, "A system error has been occurred. Failed to XOpenDisplay.");
1127
1128                 int num = 0;
1129                 Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
1130                 SysTryReturnResult(NID_APP, pRoots != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
1131
1132                 for (int i = 0; i < num; i++)
1133                 {
1134                         p_XSelectInput(pDisplay.get(), pRoots[i], PropertyChangeMask);
1135                 }
1136
1137                 pWindowPropertyChanged = p_ecore_event_handler_add(*p_ECORE_X_EVENT_WINDOW_PROPERTY, OnPropertyChanged, (void*) this);
1138                 free(pRoots);
1139                 SysTryReturnResult(NID_APP, pWindowPropertyChanged, E_SYSTEM, "A system error has been occurred.");
1140         }
1141
1142         return r;
1143 }
1144
1145 result
1146 _AppManagerImpl::RemoveActiveAppEventListener(IActiveAppEventListener& listener)
1147 {
1148         if (p_ecore_event_handler_del == null)
1149         {
1150                 _LibraryImpl& lib = GetEcoreLibraryImpl();
1151                 p_ecore_event_handler_del = reinterpret_cast<void*(*)(Ecore_Event_Handler* event_handler)>(lib.GetProcAddress(L"ecore_event_handler_del"));
1152                 SysTryReturnResult(NID_APP, p_ecore_event_handler_del != null, E_SYSTEM,
1153                                                    "A system error has been occurred. Failed to get p_ecore_event_handler_del.");
1154         }
1155
1156         result r = __activeAppEventListenerList.Remove(&listener);
1157         SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r));
1158
1159         if (__activeAppEventListenerList.GetCount() == 0)
1160         {
1161                 p_ecore_event_handler_del(pWindowPropertyChanged);
1162                 pWindowPropertyChanged = null;
1163         }
1164
1165         return r;
1166 }
1167
1168 result
1169 _AppManagerImpl::GetActiveApp(AppId& appId)
1170 {
1171         unsigned int windowId = GetActiveWindow();
1172         int processId = GetProcessId(windowId);
1173         char pkgname[255] = {0, };
1174         aul_app_get_pkgname_bypid(processId, pkgname, 255);
1175         // TODO: Translate it to package name --> AppId
1176         appId = pkgname;
1177         return E_SUCCESS;
1178 }
1179
1180 }} // Tizen::App