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