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