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