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