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