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