Ignore callback for null AppId case and optimize the loop body.
[platform/framework/native/appfw.git] / src / app / FApp_AppManagerImpl.cpp
index b13b58d..f696327 100755 (executable)
@@ -1,5 +1,4 @@
 //
-// Open Service Platform
 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
 //
 // Licensed under the Apache License, Version 2.0 (the License);
@@ -27,6 +26,7 @@
 
 #include <aul/aul.h>
 #include <bundle.h>
+#include <app_manager.h>
 #include <Ecore.h>
 #include <Ecore_X.h>
 #include <X11/Xlib.h>
 #include "FApp_AppControlImpl.h"
 #include "FApp_ConditionManagerProxy.h"
 #include "FApp_IAppManagerEventListener.h"
+#include "FApp_IAppEventListener.h"
 #include "FApp_MapDataControlImpl.h"
 #include "FApp_SqlDataControlImpl.h"
 #include "FAppPkg_PackageManagerImpl.h"
 #include "FAppPkg_PackageInfoImpl.h"
 #include "FApp_AppControlManager.h"
 #include "FApp_Aul.h"
+#include "FSys_SystemInfoImpl.h"
 
 using namespace Tizen::App::Package;
 using namespace Tizen::Base;
@@ -73,8 +75,6 @@ using namespace Tizen::Base::Runtime;
 using namespace Tizen::Base::Utility;
 using namespace Tizen::Io;
 
-//extern const char* _DATACONTROL_RESULTSET_DIR;
-
 namespace
 {
 
@@ -96,9 +96,20 @@ static void* (* p_ecore_event_handler_del)(Ecore_Event_Handler* event_handler) =
 // libX11.so
 static int (* p_XSelectInput)(Display* display, Window w, long event_mask) = null;
 static Display* (* p_XOpenDisplay)(_Xconst char* display_name) = null;
+static int (* p_XCloseDisplay)(Display* display) = null;
 
 Ecore_Event_Handler* pWindowPropertyChanged = null;
 
+struct _DisplayDeleter
+{
+       void operator()(Display* pDisplay)
+       {
+               if (p_XOpenDisplay)
+               {
+                       p_XCloseDisplay(pDisplay);
+               }
+       }
+};
 
 int
 GetTotalSize(const Tizen::Base::Collection::ICollection& col)
@@ -279,11 +290,31 @@ _AppManagerImpl::GetConditionManagerProxy(void)
 {
        if (__pConditionManager == null)
        {
+               const int MAX_TRY_COUNT = 5;
+               const int TRY_SLEEP_TIME = 250;
+
                __pConditionManager = new (std::nothrow) _ConditionManagerProxy;
                SysAssert(__pConditionManager != null);
 
-               result r = __pConditionManager->Construct();
-               SysAssertf(r == E_SUCCESS, "__pConditionManager->Construct() faliied [%s].", GetErrorMessage(r));
+               int count = 0;
+               while (true)
+               {
+                       result r = __pConditionManager->Construct();
+                       if (r == E_SUCCESS)
+                       {
+                               SysLog(NID_APP, "Succeeded in connecting condition manager.");
+                               break;
+                       }
+
+                       if (count >= MAX_TRY_COUNT)
+                       {
+                               SysLog(NID_APP, "Failed to connecting condition manager.");
+                               break;
+                       }
+
+                       count++;
+                       Thread::Sleep(TRY_SLEEP_TIME);
+               }
        }
 
        return __pConditionManager;
@@ -296,14 +327,7 @@ _AppManagerImpl::FindAppControlN(const AppId& aId, const String& oId)
 
        AppControl* pAc = null;
 
-       pAc = pRegs->GetNativeAppControlN(aId, oId);
-       if (pAc != null)
-       {
-               SetLastResult(E_SUCCESS);
-               return pAc;
-       }
-
-       pAc = pRegs->GetAliasAppControlN(aId, oId);
+       pAc = pRegs->GetTizenAppControlN(aId, oId);
        if (pAc != null)
        {
                SetLastResult(E_SUCCESS);
@@ -353,16 +377,8 @@ _AppManagerImpl::FindAppControlsN(const String* pOperationId, const String* pCat
                                         GetErrorMessage(E_INVALID_FORMAT));
        }
 
-       ArrayList* pRetArg = null;
-       pRetArg = new (std::nothrow) ArrayList();
-       SysTryReturn(NID_APP, pRetArg != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.",
-                                GetErrorMessage(E_OUT_OF_MEMORY));
-
-       pRetArg->Construct();
-
        _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance();
-
-       pRetArg = pRegs->FindAppControlListN(pOperationId, pUriScheme, pMimeType, pCategory);
+       ArrayList* pRetArg = pRegs->FindAppControlListN(pOperationId, pUriScheme, pMimeType, pCategory);
 
        if ((pRetArg == null) || (pRetArg->GetCount() == 0))
        {
@@ -554,7 +570,7 @@ _AppManagerImpl::GetAppRootPath(const AppId& appId, String& appRootPath)
 {
        String pkgId = PackageManager::GetPackageIdByAppId(appId);
        SysTryReturnResult(NID_APP, pkgId.IsEmpty() == false, E_APP_NOT_INSTALLED,
-                       "The application is not installed. (appId: %ls)", appId.GetPointer());
+                       "The application is not installed. (app: %ls)", appId.GetPointer());
 
        _PackageManagerImpl* pPkgMgr = _PackageManagerImpl::GetInstance();
        SysTryReturnResult(NID_APP, pPkgMgr != null, E_SYSTEM,
@@ -562,7 +578,7 @@ _AppManagerImpl::GetAppRootPath(const AppId& appId, String& appRootPath)
 
        std::unique_ptr< PackageInfo >pPkgInfo(pPkgMgr->GetPackageInfoN(pkgId));
        SysTryReturnResult(NID_APP, pPkgInfo != null, E_APP_NOT_INSTALLED,
-                       "The application is not installed. (appId: %ls)", appId.GetPointer());
+                       "The application is not installed. (app: %ls)", appId.GetPointer());
 
        _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo.get());
        SysTryReturnResult(NID_APP, pPkgInfoImpl != null, E_SYSTEM,
@@ -585,8 +601,8 @@ _AppManagerImpl::LaunchApplication(const String& appId, const IList* pArguments,
 //                                       "The length of appid exceeded the limit(%d).",
 //                                       WIDGET_APP_MAX_APPID_LENGTH);
 
-       AppControl* pAc = _AppControlRegistry::GetInstance()->GetAppControlN(appId, TIZEN_OPERATION_MAIN);
-       SysTryReturnResult(NID_APP, pAc != null, E_OBJ_NOT_FOUND, "The target application (%ls) is not found.", appId.GetPointer());
+       std::unique_ptr<AppControl> pAc(_AppControlRegistry::GetInstance()->GetAppControlN(appId, TIZEN_OPERATION_MAIN));
+       SysTryReturnResult(NID_APP, pAc.get() != null, E_OBJ_NOT_FOUND, "The target application (%ls) is not found.", appId.GetPointer());
 
        if (pArguments)
        {
@@ -646,18 +662,12 @@ _AppManagerImpl::LaunchApplication(const String& appId, AppManager::LaunchOption
 
 
 result
-_AppManagerImpl::TerminateApplication(const AppId& appId, const String* pExecutableName)
+_AppManagerImpl::TerminateApplication(const AppId& appId)
 {
-       result r = E_SUCCESS;
-
        _IAppManager* pMgr = _AppManagerProxy::GetService();
-       if (pMgr)
-       {
-               const String& name = (pExecutableName) ? *pExecutableName : _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId);
-               r = pMgr->TerminateApplication(appId, name);
-       }
+       SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
 
-       return r;
+       return pMgr->TerminateApplication(appId);
 }
 
 
@@ -666,7 +676,7 @@ TerminateIterFnCb(const aul_app_info* pAppInfo, void* pData)
 {
        const char* pStr = static_cast<const char*>(pData);
 
-       if (pStr && strncmp(pStr, pAppInfo->pkg_name, 10) == 0)
+       if (pStr && strncmp(pStr, pAppInfo->pkg_name, _MAX_PACKAGE_ID_LENGTH) == 0)
        {
                aul_terminate_pid(pAppInfo->pid);
                SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid);
@@ -677,8 +687,6 @@ TerminateIterFnCb(const aul_app_info* pAppInfo, void* pData)
 result
 _AppManagerImpl::TerminateApplications(const PackageId& packageId)
 {
-       result r = E_SUCCESS;
-
        std::unique_ptr<char[]> pPackage(_StringConverter::CopyToCharArrayN(packageId));
        aul_app_get_running_app_info(TerminateIterFnCb, static_cast<void*>(pPackage.get()));
 
@@ -687,18 +695,11 @@ _AppManagerImpl::TerminateApplications(const PackageId& packageId)
 }
 
 bool
-_AppManagerImpl::IsRunning(const AppId& appId, const String* pExecutableName) const
+_AppManagerImpl::IsRunning(const AppId& appId) const
 {
-       bool b = false;
+       std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
 
-       _IAppManager* pMgr = _AppManagerProxy::GetService();
-       if (pMgr)
-       {
-               const String& name = (pExecutableName) ? *pExecutableName : _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId);
-               b = pMgr->IsRunning(appId, name);
-       }
-
-       return b;
+       return aul_app_is_running(pAppId.get());
 }
 
 static int
@@ -730,17 +731,35 @@ _AppManagerImpl::GetRunningAppListN(void) const
 
 
 result
-_AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& executableName, const String& condition, const IList* pArguments,
+_AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& condition, const IList* pArguments,
                                                                   AppManager::LaunchOption option)
 {
        _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
        SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
 
-       return pProxy->RegisterAppLaunch(appId, executableName, condition, pArguments, option);
+       Tizen::Base::Utility::StringTokenizer strTok(condition, L"=");
+       SysTryReturnResult(NID_APP, strTok.GetTokenCount() > 0, E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
+
+       String key;
+       result r = strTok.GetNextToken(key);
+       SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
+
+       bool ret = true;
+       if (key == L"Serial")
+       {
+               r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/usb.accessory", ret);
+       }
+       else if (key == L"NFC")
+       {
+               r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/network.nfc", ret);
+       }
+       SysTryReturnResult(NID_APP, ret != false, E_UNSUPPORTED_OPERATION, "Condition(%ls)", condition.GetPointer());
+
+       return pProxy->RegisterAppLaunch(appId, condition, pArguments, option);
 }
 
 result
-_AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String& executableName, const String* pCondition)
+_AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String* pCondition)
 {
        _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
        SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
@@ -752,18 +771,18 @@ _AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String& executabl
                                                  "No such a condition.");
        }
 
-       return pProxy->UnregisterAppLaunch(appId, executableName, pCondition);
+       return pProxy->UnregisterAppLaunch(appId, pCondition);
 }
 
 bool
-_AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String &executableName, const String* pCondition)
+_AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String* pCondition)
 {
        _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
        SysTryReturn(NID_APP, null != pProxy, false, E_INVALID_STATE, "[%s] ConditionManager instance must not be null.",
                                 GetErrorMessage(E_INVALID_STATE));
 
        ClearLastResult();
-       return pProxy->IsAppLaunchRegistered(appId, executableName, pCondition);
+       return pProxy->IsAppLaunchRegistered(appId, pCondition);
 }
 
 result
@@ -775,11 +794,10 @@ _AppManagerImpl::SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEve
 result
 _AppManagerImpl::OnServiceEventReceived(int clientId, const _AppManagerEventArg& arg)
 {
-       SysLog(NID_APP, "appId:%ls, appType:0x%x", arg.GetAppId().GetPointer(), arg.GetAppType());
+       SysLog(NID_APP, "app:%ls, appType:0x%x", arg.GetAppId().GetPointer(), arg.GetAppType());
 
        _AppManagerEventArg* pArg = new (std::nothrow)_AppManagerEventArg(arg);
-       SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.",
-                                          GetErrorMessage(E_OUT_OF_MEMORY));
+       SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
        __appManagerEvent.FireAsync(*pArg);
        return E_SUCCESS;
 }
@@ -832,26 +850,154 @@ _AppManagerImpl::RemoveEventListener(_IAppManagerEventListener& listener)
        return E_SUCCESS;
 }
 
-// input ("qik37po9ck.BasicApp") => output {"qik37po9ck", "BasicApp"}
+
+///////////////////////////////////////////////////////////////////////////////
+// LifecycleManager begins.
+///////////////////////////////////////////////////////////////////////////////
+
+void
+_AppLifecycleManager::Init(void)
+{
+       aul_listen_app_launch_signal(LaunchCallback, this);
+       aul_listen_app_dead_signal(TerminateCallback, this);
+}
+
+void
+_AppLifecycleManager::Fini(void)
+{
+       aul_listen_app_launch_signal(NULL, NULL);
+       aul_listen_app_dead_signal(NULL, NULL);
+}
+
+result
+_AppLifecycleManager::AddListener(_IAppEventListener& listener)
+{
+       if (__pEventList == null)
+       {
+               std::unique_ptr< LinkedListT<_IAppEventListener*> > pAppEventList(new LinkedListT<_IAppEventListener*>);
+               SysTryReturnResult(NID_APP, pAppEventList, E_SYSTEM, "Memory allocation failed.");
+
+               Init();
+
+               __pEventList = pAppEventList.release();
+               SysLog(NID_APP, "Registered app event listener.");
+       }
+
+       return __pEventList->Add(&listener);
+}
+
 result
-_AppManagerImpl::ExtractValues(AppId inAppId, AppId& outAppId, String& outExecutableName)
+_AppLifecycleManager::RemoveListener(_IAppEventListener& listener)
 {
-       const int APP_ID_LEN = 10;
+       SysTryReturnResult(NID_APP,__pEventList != null, E_OBJ_NOT_FOUND, "_IEventListener list is empty.");
 
-       if (inAppId.GetLength() > APP_ID_LEN)
+       result r = __pEventList->Remove(&listener);
+
+       if (__pEventList->GetCount() == 0)
        {
-               result r = inAppId.SubString(APP_ID_LEN + 1, inAppId.GetLength() - (APP_ID_LEN + 1), outExecutableName);
-               SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "invalid AppId(%ls)", inAppId.GetPointer());
+               Fini();
 
-               r = inAppId.SubString(0, APP_ID_LEN, outAppId);
-               SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "invalid AppId(%ls)", inAppId.GetPointer());
+               delete __pEventList;
+               __pEventList = null;
+       }
 
-               SysLog(NID_APP, "appId(%ls), executableName(%ls)", outAppId.GetPointer(), outExecutableName.GetPointer());
-               return E_SUCCESS;
+       return r;
+}
+
+int
+_AppLifecycleManager::LaunchCallback(int pid, void* pData)
+{
+       _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
+       if (pImpl == null || pImpl->__pEventList == null)
+       {
+               SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
+               return -1;
        }
-       return E_SYSTEM;
+
+       char appId[255];
+       int ret = aul_app_get_appid_bypid(pid, appId, sizeof(appId));
+       if (ret != AUL_R_OK)
+       {
+               SysLogException(NID_APP, E_SYSTEM, "Cannot acquire app for %d.", pid);
+               return -1;
+       }
+
+       std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
+       if (pEnum.get())
+       {
+               const String tmp = appId;
+               pImpl->__map.Add(pid, tmp);
+
+               while (pEnum->MoveNext() == E_SUCCESS)
+               {
+                       _IAppEventListener* pListener = null;
+                       pEnum->GetCurrent(pListener);
+
+                       pListener->OnApplicationLaunched(tmp, pid);
+               }
+       }
+
+       SysLog(NID_APP, "Finished invoking application event listener for %s, %d.", appId, pid);
+
+       return 0;
+}
+
+int
+_AppLifecycleManager::TerminateCallback(int pid, void* pData)
+{
+       _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
+       if (pImpl == null || pImpl->__pEventList == null)
+       {
+               SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
+               return -1;
+       }
+
+       // terminate callback cannot acquire appId from pid
+       String tmp;
+       result r = pImpl->__map.GetValue(pid, tmp);
+       if (r != E_SUCCESS)
+       {
+               SysLog(NID_APP, "Cannot acquire app from pid %d.", pid);
+               return -1;
+       }
+
+       pImpl->__map.Remove(pid);
+
+       std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
+       if (pEnum.get())
+       {
+               while (pEnum->MoveNext() == E_SUCCESS)
+               {
+                       _IAppEventListener* pListener = null;
+                       pEnum->GetCurrent(pListener);
+
+                       pListener->OnApplicationTerminated(tmp, pid);
+               }
+       }
+
+       SysLog(NID_APP, "Finished invoking application event listener for %ls, %d.", tmp.GetPointer(), pid);
+
+       return 0;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// LifecycleManager ends.
+///////////////////////////////////////////////////////////////////////////////
+
+
+result
+_AppManagerImpl::AddAppEventListener(_IAppEventListener& listener)
+{
+       return __lifeManager.AddListener(listener);
 }
 
+result
+_AppManagerImpl::RemoveAppEventListener(_IAppEventListener& listener)
+{
+       return __lifeManager.RemoveListener(listener);
+}
+
+
 _LibraryImpl&
 _AppManagerImpl::GetUiLibraryImpl(void)
 {
@@ -916,6 +1062,14 @@ _AppManagerImpl::FireActiveAppEvent(unsigned int xid, int pid, char* pAppName)
        if (oldPid != pid)
        {
                oldPid = pid;
+               char pkgname[255] = {0, };
+               if ((AUL_R_OK != aul_app_get_pkgname_bypid(pid, pkgname, 255)) || pkgname[0] == 0)
+               {
+                       SysSecureLog(NID_APP, "Failed to get the package name from pid=%x pAppName=%s", pid, pAppName ? pAppName : "null");
+                       return;
+               }
+               AppId appId(_Aul::GetRealAppId(String(pkgname)));
+
                std::unique_ptr<IEnumeratorT<Tizen::App::IActiveAppEventListener* > > pEnum(__activeAppEventListenerList.GetEnumeratorN());
                if (pEnum.get())
                {
@@ -925,10 +1079,7 @@ _AppManagerImpl::FireActiveAppEvent(unsigned int xid, int pid, char* pAppName)
                                pEnum->GetCurrent(pListener);
                                if (pListener)
                                {
-                                       char pkgname[255] = {0, };
-                                       aul_app_get_pkgname_bypid(pid, pkgname, 255);
-                                       // TODO: Translate it to package name --> AppId
-                                       pListener->OnActiveAppChanged(AppId(pkgname));
+                                       pListener->OnActiveAppChanged(appId);
                                }
                        }
                }
@@ -960,14 +1111,16 @@ _AppManagerImpl::GetActiveWindow(void)
                                                   "A system error has been occurred. Failed to get ecore_x_window_prop_window_get.");
        }
 
-       Ecore_X_Window* pRoots = null;
        int num = 0;
-
-       pRoots = p_ecore_x_window_root_list(&num);
-       Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW");
+       Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
 
        Ecore_X_Window activeWin = 0;
-       p_ecore_x_window_prop_window_get(pRoots[0], activeAtom, &activeWin, 1);
+       if (pRoots)
+       {
+               Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW");
+               p_ecore_x_window_prop_window_get(pRoots[0], activeAtom, &activeWin, 1);
+               free(pRoots);
+       }
 
        return activeWin;
 }
@@ -996,35 +1149,42 @@ _AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener)
        {
                _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
                p_ecore_x_window_root_list = reinterpret_cast<Ecore_X_Window*(*)(int* num_ret)>(lib.GetProcAddress(L"ecore_x_window_root_list"));
-               SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, EINA_FALSE,
+               SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, E_SYSTEM,
                                                   "A system error has been occurred. Failed to get p_ecore_x_window_root_list.");
        }
        if (p_ECORE_X_EVENT_WINDOW_PROPERTY == null)
        {
                _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl();
                p_ECORE_X_EVENT_WINDOW_PROPERTY = reinterpret_cast<int*>(lib.GetProcAddress(L"ECORE_X_EVENT_WINDOW_PROPERTY"));
-               SysTryReturnResult(NID_APP, p_ECORE_X_EVENT_WINDOW_PROPERTY != null, EINA_FALSE,
+               SysTryReturnResult(NID_APP, p_ECORE_X_EVENT_WINDOW_PROPERTY != null, E_SYSTEM,
                                                   "A system error has been occurred. Failed to get p_ECORE_X_EVENT_WINDOW_PROPERTY.");
        }
        if (p_XOpenDisplay == null)
        {
                _LibraryImpl& lib = GetX11LibraryImpl();
                p_XOpenDisplay = reinterpret_cast<Display*(*)(_Xconst char* display_name)>(lib.GetProcAddress(L"XOpenDisplay"));
-               SysTryReturnResult(NID_APP, p_XOpenDisplay != null, EINA_FALSE,
+               SysTryReturnResult(NID_APP, p_XOpenDisplay != null, E_SYSTEM,
                                                   "A system error has been occurred. Failed to get p_XOpenDisplay.");
        }
+       if (p_XCloseDisplay == null)
+       {
+               _LibraryImpl& lib = GetX11LibraryImpl();
+               p_XCloseDisplay = reinterpret_cast<int(*)(Display* display)>(lib.GetProcAddress(L"XCloseDisplay"));
+               SysTryReturnResult(NID_APP, p_XCloseDisplay != null, E_SYSTEM,
+                                                  "A system error has been occurred. Failed to get p_XCloseDisplay.");
+       }
        if (p_XSelectInput == null)
        {
                _LibraryImpl& lib = GetX11LibraryImpl();
                p_XSelectInput = reinterpret_cast<int(*)(Display* display, Window w, long event_mask)>(lib.GetProcAddress(L"XSelectInput"));
-               SysTryReturnResult(NID_APP, p_XSelectInput != null, EINA_FALSE,
+               SysTryReturnResult(NID_APP, p_XSelectInput != null, E_SYSTEM,
                                                   "A system error has been occurred. Failed to get p_XSelectInput.");
        }
        if (p_ecore_event_handler_add == null)
        {
                _LibraryImpl& lib = GetEcoreLibraryImpl();
                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"));
-               SysTryReturnResult(NID_APP, p_ecore_event_handler_add != null, EINA_FALSE,
+               SysTryReturnResult(NID_APP, p_ecore_event_handler_add != null, E_SYSTEM,
                                                   "A system error has been occurred. Failed to get p_ecore_event_handler_add.");
        }
 
@@ -1033,19 +1193,22 @@ _AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener)
        result r = __activeAppEventListenerList.Add(&listener);
        SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r));
 
-       Ecore_X_Window* pRoots = null;
-       int num = 0;
-       pRoots = p_ecore_x_window_root_list(&num);
-
-       for (int i = 0; i < num; i++)
-       {
-               Display* pDisplay = p_XOpenDisplay(NULL);
-               p_XSelectInput(pDisplay, pRoots[i], PropertyChangeMask);
-       }
-
        if (!pWindowPropertyChanged)
        {
+               std::unique_ptr<Display, _DisplayDeleter> pDisplay(p_XOpenDisplay(NULL));
+               SysTryReturnResult(NID_APP, pDisplay != null, E_SYSTEM, "A system error has been occurred. Failed to XOpenDisplay.");
+
+               int num = 0;
+               Ecore_X_Window* pRoots = p_ecore_x_window_root_list(&num);
+               SysTryReturnResult(NID_APP, pRoots != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
+
+               for (int i = 0; i < num; i++)
+               {
+                       p_XSelectInput(pDisplay.get(), pRoots[i], PropertyChangeMask);
+               }
+
                pWindowPropertyChanged = p_ecore_event_handler_add(*p_ECORE_X_EVENT_WINDOW_PROPERTY, OnPropertyChanged, (void*) this);
+               free(pRoots);
                SysTryReturnResult(NID_APP, pWindowPropertyChanged, E_SYSTEM, "A system error has been occurred.");
        }
 
@@ -1078,13 +1241,33 @@ _AppManagerImpl::RemoveActiveAppEventListener(IActiveAppEventListener& listener)
 result
 _AppManagerImpl::GetActiveApp(AppId& appId)
 {
-       unsigned int windowId = GetActiveWindow();
-       int processId = GetProcessId(windowId);
+       const unsigned int windowId = GetActiveWindow();
+       const int processId = GetProcessId(windowId);
        char pkgname[255] = {0, };
        aul_app_get_pkgname_bypid(processId, pkgname, 255);
-       // TODO: Translate it to package name --> AppId
-       appId = pkgname;
+       
+       appId = _Aul::GetRealAppId(String(pkgname));
+
+       SysLog(NID_APP, "ActiveApp is %ls.", appId.GetPointer());
        return E_SUCCESS;
 }
 
+bool 
+_AppManagerImpl::IsUserPreferredAppForAppControlResolution(const AppId& appId) const
+{
+       _IAppManager* pMgr = _AppManagerProxy::GetService();
+       SysTryReturn(NID_APP, pMgr, false, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
+
+       return pMgr->IsUserPreferredAppForAppControlResolution(appId);
+}
+
+result 
+_AppManagerImpl::ClearUserPreferenceForAppControlResolution(const AppId& appId)
+{
+       _IAppManager* pMgr = _AppManagerProxy::GetService();
+       SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
+
+       return pMgr->ClearUserPreferenceForAppControlResolution(appId);
+}
+
 }} // Tizen::App