export _AppControlImpl::FindAndStart()
[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
30 #include <FBaseObject.h>
31 #include <FBaseString.h>
32 #include <FBaseColArrayList.h>
33 #include <FBaseErrors.h>
34 #include <FAppAppControl.h>
35 #include <FAppAppManager.h>
36 #include <FAppSqlDataControl.h>
37 #include <FAppMapDataControl.h>
38 #include <FAppPkgPackageInfo.h>
39 #include <FAppIActiveAppEventListener.h>
40 #include <FBaseSysLog.h>
41 #include <FAppIAppControlListener.h>
42
43 #include <FBase_StringConverter.h>
44 #include <FBaseRt_LibraryImpl.h>
45 #include <FSys_SystemInfoImpl.h>
46
47 #include "FApp_AppControlRegistry.h"
48 #include "FApp_AppImpl.h"
49 #include "FApp_AppInfo.h"
50 #include "FApp_AppManagerImpl.h"
51 #include "FApp_AppManagerProxy.h"
52 #include "FApp_AppMessageImpl.h"
53 #include "FApp_AppControlImpl.h"
54 #include "FApp_ConditionManagerProxy.h"
55 #include "FApp_IAppEventListener.h"
56 #include "FApp_MapDataControlImpl.h"
57 #include "FApp_SqlDataControlImpl.h"
58 #include "FAppPkg_PackageManagerImpl.h"
59 #include "FAppPkg_PackageInfoImpl.h"
60 #include "FApp_AppControlManager.h"
61 #include "FApp_TemplateUtil.h"
62 #include "FApp_Aul.h"
63 #include "FApp_AppLifecycleEvent.h"
64 #include "FApp_AppLifecycleEventArg.h"
65 #include "FApp_IAppLifecycleEventListener.h"
66 #include "FApp_ActiveWindowManager.h"
67
68 using namespace Tizen::App::Package;
69 using namespace Tizen::Base;
70 using namespace Tizen::Base::Collection;
71 using namespace Tizen::Base::Runtime;
72 using namespace Tizen::Base::Utility;
73 using namespace Tizen::Io;
74
75 namespace
76 {
77
78 //const long MAX_APPCONTROL_ARGUMENT = 4096;
79 const long MAX_APPCONTROL_ARGUMENT = 1024;
80 const long MAX_CONDITION_LENGTH = 400;
81
82 int
83 GetTotalSize(const Tizen::Base::Collection::ICollection& col)
84 {
85         int size = 0;
86         std::unique_ptr<IEnumerator> pEnum(col.GetEnumeratorN());
87
88         if (pEnum)
89         {
90                 while (pEnum->MoveNext() == E_SUCCESS)
91                 {
92                         String* pStr = static_cast<String*>(pEnum->GetCurrent());
93                         if (pStr == null)
94                         {
95                                 continue;
96                         }
97                         size += pStr->GetLength();
98                 }
99         }
100
101         return size;
102 }
103
104 } // anonymous name-space
105
106
107 namespace Tizen { namespace App
108 {
109
110 const wchar_t LEGACY_LAUNCH_REASON_NORMAL[] = L"LAUNCH_NORMAL";
111 const wchar_t LEGACY_LAUNCH_REASON_CONDITIONAL[] = L"LAUNCH_CONDITIONAL";
112 const wchar_t OSP_UI_SONAME[] = L"libosp-uifw.so.1";
113 const int _MAX_PACKAGE_ID_LENGTH = 10;
114
115
116 _AppManagerImpl::_AppManagerImpl(void)
117         : __pConditionManager(null)
118         , __pActiveWindowManager(new (std::nothrow) _ActiveWindowManager)
119         , __pUiLibrary(null)
120 {
121         SysLog(NID_APP, "");
122 }
123
124 _AppManagerImpl::~_AppManagerImpl(void)
125 {
126         SysLog(NID_APP, "");
127
128         delete __pConditionManager;
129         delete __pUiLibrary;
130 }
131
132
133 result
134 _AppManagerImpl::Construct(void)
135 {
136         __appLifecycleEvent.Construct();
137         __appListForAppLifecycle.Construct();
138         result r = __mutex.Create();
139         SysTryLog(NID_APP, r == E_SUCCESS, "Creating mutex failed.");
140
141         _IAppManager* pMgr = _AppManagerProxy::GetService();
142         //todo : uncomment following _SysTryReturn or put assert.
143         //SysTryReturn(NID_APP, pMgr != null, GetLastResult(), GetLastResult(), "[%s]GetService failed. Please check 'ps -A | grep OspAppService'!", GetLastResult());
144         SysTryReturn(NID_APP, pMgr != null, E_SUCCESS, E_SUCCESS, "[E_SYSTEM] fatal error. Please check 'ps -A | grep osp-app-service'!", GetLastResult());
145         pMgr->InitEventListener(this);
146
147         return E_SUCCESS;
148 }
149
150 _AppManagerImpl*
151 _AppManagerImpl::GetInstance(void)
152 {
153         return AppManager::GetInstance()->__pAppManagerImpl;
154 }
155
156 _ConditionManagerProxy*
157 _AppManagerImpl::GetConditionManagerProxy(void)
158 {
159         if (__pConditionManager == null)
160         {
161                 const int MAX_TRY_COUNT = 5;
162                 const int TRY_SLEEP_TIME = 250;
163
164                 __pConditionManager = new (std::nothrow) _ConditionManagerProxy;
165                 SysAssert(__pConditionManager != null);
166
167                 int count = 0;
168                 while (true)
169                 {
170                         result r = __pConditionManager->Construct();
171                         if (r == E_SUCCESS)
172                         {
173                                 SysLog(NID_APP, "Succeeded in connecting condition manager.");
174                                 break;
175                         }
176
177                         if (count >= MAX_TRY_COUNT)
178                         {
179                                 SysLog(NID_APP, "Failed to connecting condition manager.");
180                                 break;
181                         }
182
183                         count++;
184                         Thread::Sleep(TRY_SLEEP_TIME);
185                 }
186         }
187
188         return __pConditionManager;
189 }
190
191 AppControl*
192 _AppManagerImpl::FindAppControlN(const AppId& aId, const String& oId)
193 {
194         _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance();
195
196         AppControl* pAc = null;
197
198         pAc = pRegs->GetTizenAppControlN(aId, oId);
199         SysTryReturn(NID_APP, pAc != null, null, E_OBJ_NOT_FOUND, "[%s] No matching AppControl instance found (%ls, %ls).",
200                                  GetErrorMessage(E_OBJ_NOT_FOUND), aId.GetPointer(), oId.GetPointer());
201         SetLastResult(E_SUCCESS);
202         return pAc;
203 }
204
205 IList*
206 _AppManagerImpl::FindAppControlsN(const String* pOperationId, const String* pCategory, const String* pDataType,
207                                                                   const String* pUriScheme)
208 {
209         SysTryReturn(NID_APP, !(pOperationId == null && pCategory == null && pUriScheme == null && pDataType == null), null,
210                                  E_INVALID_ARG, "[%s] At least one parameter should not be null.", GetErrorMessage(E_INVALID_ARG));
211
212         String mimeType;
213         const String* pMimeType = pDataType;
214
215         if (pDataType)
216         {
217                 if ((*pDataType)[0] == L'.')
218                 {
219                         SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer());
220
221                         String ext;
222                         pDataType->SubString(1, ext);
223
224                         result r = _AppControlManager::GetMimeFromExt(ext, mimeType);
225
226                         SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer());
227
228                         pMimeType = &mimeType;
229
230                         SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer());
231                 }
232         }
233
234         if (pUriScheme)
235         {
236                 SysTryReturn(NID_APP, !(pUriScheme->IsEmpty()), null, E_INVALID_FORMAT, "[%s] The specified URI scheme is invalid.",
237                                          GetErrorMessage(E_INVALID_FORMAT));
238         }
239
240         _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance();
241         ArrayList* pRetArg = pRegs->FindAppControlListN(pOperationId, pUriScheme, pMimeType, pCategory);
242
243         if ((pRetArg == null) || (pRetArg->GetCount() == 0))
244         {
245                 delete pRetArg;
246                 pRetArg = null;
247                 SetLastResult(E_OBJ_NOT_FOUND);
248                 return null;
249         }
250
251         SetLastResult(E_SUCCESS);
252         SysLog(NID_APP, "Found %d matching AppControls.", pRetArg->GetCount());
253
254         return pRetArg;
255 }
256
257
258 result
259 _AppManagerImpl::StartAppControl(const String& uri, const String* pOperationId, const String* pDataType,
260                                                                  IAppControlListener* pListener)
261 {
262         return StartAppControl(pOperationId, null, pDataType, &uri, null, pListener);
263 }
264
265
266 result
267 _AppManagerImpl::StartAppControl(const String* pOperationId, const String* pCategory, const String* pDataType,
268                                                                  const String* pUri, const IList* pDataList, IAppControlListener* pListener)
269 {
270         SysTryReturnResult(NID_APP, !(pOperationId == null && pUri == null && pCategory == null && pDataType == null), E_INVALID_ARG,
271                                                 "At least one of the specified argument must not be null.");
272         if (pDataList != null)
273         {
274                 int argSize = 0;
275                 argSize = GetTotalSize(*pDataList);
276
277                 SysLog(NID_APP, "Argument count = %d, size = %d", pDataList->GetCount(), argSize);
278
279                 SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED,
280                                                   "The size of pDataList exceeded the limit(%d).",
281                                                   MAX_APPCONTROL_ARGUMENT);
282         }
283
284         String operation = (pOperationId) ? *pOperationId : TIZEN_OPERATION_MAIN;
285
286         std::unique_ptr<bundle, BundleDeleter> pBundle(bundle_create());
287         SysTryReturnResult(NID_APP, pBundle.get(), E_OUT_OF_MEMORY, "Bundle creation failure.");
288
289         _AppMessageImpl::SetOperation(pBundle.get(), operation);
290
291         if (pUri)
292         {
293                 _AppMessageImpl::SetUri(pBundle.get(), *pUri);
294         }
295
296         if (pDataType)
297         {
298                 String mimeType = *pDataType;
299
300                 if ((*pDataType)[0] == L'.')
301                 {
302                         SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer());
303
304 #if 0
305                         String ext;
306                         pDataType->SubString(1, ext);
307
308                         result r = _AppControlManager::GetMimeFromExt(ext, mimeType);
309
310                         SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer());
311
312                         pMimeType = &mimeType;
313
314                         SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer());
315 #endif
316                 }
317
318                 _AppMessageImpl::SetMime(pBundle.get(), mimeType);
319         }
320
321         if (pCategory)
322         {
323                 _AppMessageImpl::SetCategory(pBundle.get(), *pCategory);
324         }
325
326         return _AppControlImpl::StartImplicit(pBundle.get(), pDataList, pListener);
327 }
328
329
330 SqlDataControl*
331 _AppManagerImpl::GetSqlDataControlN(const String& providerId)
332 {
333         SqlDataControl* pDc = null;
334         String type(L"Sql");
335         String* pAppId = null;
336         String* pAccess = null;
337         String appId;
338
339         // XXX: Need _NativeDataControlRegistry for SLP native app ?
340         // Try to searach SLP data control.
341 //      _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton
342 //      pDc = pReg->GetNativeSqlDataControlN(providerId);
343 //      if (pDc != null)
344 //      {
345 //              return pDc;
346 //      }
347
348         std::unique_ptr <IList, AllElementsDeleter> pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type));
349         SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist.");
350
351         pAppId = dynamic_cast< String* >(pList->GetAt(0));
352         SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
353         pAccess = dynamic_cast< String* >(pList->GetAt(1));
354         SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
355         pAccess->ToLower();
356
357         if (pAppId->StartsWith(L"org.tizen.", 0))
358         {
359                 std::unique_ptr<StringTokenizer> pStrTok(new (std::nothrow) StringTokenizer(*pAppId, L'.'));
360                 SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
361                 for (int i = 0; i < 3; ++i)
362                 {
363                         pStrTok->GetNextToken(appId);
364                 }
365
366                 appId[_MAX_PACKAGE_ID_LENGTH] = L'.';
367         }
368         else
369         {
370                 appId.Append(*pAppId);
371         }
372
373         pDc = _SqlDataControlImpl::CreateSqlDataControl(appId, providerId, *pAccess);
374         SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult()));
375
376         return pDc;
377 }
378
379 MapDataControl*
380 _AppManagerImpl::GetMapDataControlN(const String& providerId)
381 {
382         MapDataControl* pDc = null;
383         String type(L"Map");
384         String* pAppId = null;
385         String* pAccess = null;
386         String appId;
387
388         // XXX: Need _NativeDataControlRegistry for SLP native app ?
389         // Try to searach SLP data control.
390 //      _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton
391 //      pDc = pReg->GetNativeMapDataControlN(providerId);
392 //      if (pDc != null)
393 //      {
394 //              return pDc;
395 //      }
396
397         std::unique_ptr <IList, AllElementsDeleter> pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type));
398         SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist.");
399
400         pAppId = dynamic_cast< String* >(pList->GetAt(0));
401         SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
402         pAccess = dynamic_cast< String* >(pList->GetAt(1));
403         SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error.");
404         pAccess->ToLower();
405
406         if (pAppId->StartsWith(L"org.tizen.", 0))
407         {
408                 std::unique_ptr<StringTokenizer> pStrTok( new (std::nothrow) StringTokenizer(*pAppId, L'.'));
409                 SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
410                 for (int i = 0; i < 3; ++i)
411                 {
412                         pStrTok->GetNextToken(appId);
413                 }
414
415                 appId[_MAX_PACKAGE_ID_LENGTH] = L'.';
416         }
417         else
418         {
419                 appId.Append(*pAppId);
420         }
421
422         pDc = _MapDataControlImpl::CreateMapDataControl(appId, providerId, *pAccess);
423         SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult()));
424
425         return pDc;
426 }
427
428 result
429 _AppManagerImpl::GetAppRootPath(const AppId& appId, String& appRootPath)
430 {
431         String pkgId = PackageManager::GetPackageIdByAppId(appId);
432         SysTryReturnResult(NID_APP, pkgId.IsEmpty() == false, E_APP_NOT_INSTALLED,
433                         "The application is not installed. (app: %ls)", appId.GetPointer());
434
435         _PackageManagerImpl* pPkgMgr = _PackageManagerImpl::GetInstance();
436         SysTryReturnResult(NID_APP, pPkgMgr != null, E_SYSTEM,
437                         "Failed to get _PackageManagerImpl instance.");
438
439         std::unique_ptr< PackageInfo >pPkgInfo(pPkgMgr->GetPackageInfoN(pkgId));
440         SysTryReturnResult(NID_APP, pPkgInfo != null, E_APP_NOT_INSTALLED,
441                         "The application is not installed. (app: %ls)", appId.GetPointer());
442
443         _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo.get());
444         SysTryReturnResult(NID_APP, pPkgInfoImpl != null, E_SYSTEM,
445                         "Failed to get _PackageInfoImpl instance.");
446
447         appRootPath = pPkgInfoImpl->GetAppRootPath();
448         appRootPath.Append(L"/");
449
450         return E_SUCCESS;
451 }
452
453 result
454 _AppManagerImpl::LaunchApplication(const String& appId, const IList* pArguments, AppManager::LaunchOption option)
455 {
456         SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_INVALID_ARG, "The appid is empty.");
457         SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_OBJ_NOT_FOUND,
458                                            "The target application(%ls) is not installed.", appId.GetPointer());
459 //      SysTryReturnResult(NID_APP,
460 //                                        appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED,
461 //                                        "The length of appid exceeded the limit(%d).",
462 //                                        WIDGET_APP_MAX_APPID_LENGTH);
463
464         std::unique_ptr<AppControl> pAc(FindAppControlN(appId, TIZEN_OPERATION_MAIN));
465         SysTryReturnResult(NID_APP, pAc.get() != null, E_OBJ_NOT_FOUND, "The target application (%ls) is not found.", appId.GetPointer());
466
467         if (pArguments)
468         {
469                 int argSize = 0;
470                 argSize = GetTotalSize(*pArguments);
471
472                 SysLog(NID_APP, "Argument count = %d, size = %d", pArguments->GetCount(), argSize);
473
474                 SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED,
475                                                   "The size of pDataList exceeded the limit(%d).",
476                                                   MAX_APPCONTROL_ARGUMENT);
477         }
478
479         result r = pAc->Start(pArguments, null);
480
481         SysLog(NID_APP, "[%s] Launching %ls finished.", GetErrorMessage(r), appId.GetPointer());
482         return r;
483 }
484
485
486 result
487 _AppManagerImpl::LaunchApplication(const String& appId, AppManager::LaunchOption option)
488 {
489         SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_APP_NOT_INSTALLED, "The appid is empty.");
490
491         std::unique_ptr<char[]> pName(_StringConverter::CopyToCharArrayN(appId));
492
493         int ret = aul_open_app(pName.get());
494
495         if (ret > 0)
496         {
497                 SysLog(NID_APP, "Launching %ls successful.", appId.GetPointer());
498                 return E_SUCCESS;
499         }
500
501         // failure
502         SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_APP_NOT_INSTALLED,
503                                            "The target application(%ls) is not installed.", appId.GetPointer());
504
505         result r = E_SYSTEM;
506         switch (ret)
507         {
508         case AUL_R_EINVAL:
509                 r = E_APP_NOT_INSTALLED;
510                 break;
511         case AUL_R_OK:
512                 // r = E_SUCCESS;
513                 // never reach here
514                 break;
515         default:
516                 break;
517         }
518
519         SysLog(NID_APP, "[%s] Launching %ls failed.", GetErrorMessage(r), appId.GetPointer());
520         return r;
521 }
522
523
524 result
525 _AppManagerImpl::TerminateApplication(const AppId& appId)
526 {
527         _IAppManager* pMgr = _AppManagerProxy::GetService();
528         SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
529
530         return pMgr->TerminateApplication(appId);
531 }
532
533
534 static int
535 TerminateIterFnCb(const aul_app_info* pAppInfo, void* pData)
536 {
537         const char* pStr = static_cast<const char*>(pData);
538
539         if (pStr && strncmp(pStr, pAppInfo->pkg_name, _MAX_PACKAGE_ID_LENGTH) == 0)
540         {
541                 aul_terminate_pid(pAppInfo->pid);
542                 SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid);
543         }
544         return 0;
545 }
546
547 result
548 _AppManagerImpl::TerminateApplications(const PackageId& packageId)
549 {
550         std::unique_ptr<char[]> pPackage(_StringConverter::CopyToCharArrayN(packageId));
551         aul_app_get_running_app_info(TerminateIterFnCb, static_cast<void*>(pPackage.get()));
552
553         SysLog(NID_APP, "%ls terminated.", packageId.GetPointer());
554         return E_SUCCESS;
555 }
556
557 bool
558 _AppManagerImpl::IsRunning(const AppId& appId) const
559 {
560         std::unique_ptr<char[]> pAppId(_StringConverter::CopyToCharArrayN(appId));
561
562         return aul_app_is_running(pAppId.get());
563 }
564
565 static int
566 AulAppInfoIterFnCb(const aul_app_info* pAppInfo, void* pData)
567 {
568         ArrayList* pList = static_cast<ArrayList*>(pData);
569         if (pList && pAppInfo && pAppInfo->appid)
570         {
571                 pList->Add(*new (std::nothrow) String(pAppInfo->appid));
572         }
573
574         return 0;
575 }
576
577 IList*
578 _AppManagerImpl::GetRunningAppListN(void) const
579 {
580         ArrayList* pRunningAppList = new (std::nothrow) ArrayList();
581         SysTryReturn(NID_APP, pRunningAppList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.",
582                                  GetErrorMessage(E_OUT_OF_MEMORY));
583         pRunningAppList->Construct();
584
585         int ret = aul_app_get_running_app_info(AulAppInfoIterFnCb, reinterpret_cast<void*>(pRunningAppList));
586         SysTryLog(NID_APP, ret == AUL_R_OK, "Getting running list failed.");
587
588         // according to the doxygen, GetRunningAppListN() does not return null pointer for no object
589         return pRunningAppList;
590 }
591
592
593 result
594 _AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& condition, const IList* pArguments,
595                                                                    AppManager::LaunchOption option)
596 {
597         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
598         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
599
600         Tizen::Base::Utility::StringTokenizer strTok(condition, L"=");
601         SysTryReturnResult(NID_APP, strTok.GetTokenCount() > 0, E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
602
603         String key;
604         result r = strTok.GetNextToken(key);
605         SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "Condition string is invalid.(%ls)", condition.GetPointer());
606
607         bool ret = true;
608         if (key == L"Serial")
609         {
610                 r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/usb.accessory", ret);
611         }
612         else if (key == L"NFC")
613         {
614                 r = Tizen::System::_SystemInfoImpl::GetSysInfo(L"http://tizen.org/feature/network.nfc", ret);
615         }
616         SysTryReturnResult(NID_APP, ret != false, E_UNSUPPORTED_OPERATION, "Condition(%ls)", condition.GetPointer());
617
618         return pProxy->RegisterAppLaunch(appId, condition, pArguments, option);
619 }
620
621 result
622 _AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String* pCondition)
623 {
624         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
625         SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null.");
626
627         if (pCondition)
628         {
629                 SysTryReturnResult(NID_APP,
630                                                   !pCondition->IsEmpty() && pCondition->GetLength() < MAX_CONDITION_LENGTH, E_OBJ_NOT_FOUND,
631                                                   "No such a condition.");
632         }
633
634         return pProxy->UnregisterAppLaunch(appId, pCondition);
635 }
636
637 bool
638 _AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String* pCondition)
639 {
640         _ConditionManagerProxy* pProxy = GetConditionManagerProxy();
641         SysTryReturn(NID_APP, null != pProxy, false, E_INVALID_STATE, "[%s] ConditionManager instance must not be null.",
642                                  GetErrorMessage(E_INVALID_STATE));
643
644         ClearLastResult();
645         return pProxy->IsAppLaunchRegistered(appId, pCondition);
646 }
647
648 result
649 _AppManagerImpl::SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener)
650 {
651         return _AppImpl::GetInstance()->SetListener(appEvent, pListener);
652 }
653
654
655 result
656 _AppManagerImpl::OnTerminateApplicationRequested(int clientId)
657 {
658         SysLog(NID_APP, "");
659
660         return E_SUCCESS;
661 }
662
663
664 ///////////////////////////////////////////////////////////////////////////////
665 // LifecycleManager begins.
666 ///////////////////////////////////////////////////////////////////////////////
667
668 void
669 _AppLifecycleManager::Init(void)
670 {
671         aul_listen_app_launch_signal(LaunchCallback, this);
672         aul_listen_app_dead_signal(TerminateCallback, this);
673 }
674
675 void
676 _AppLifecycleManager::Fini(void)
677 {
678         aul_listen_app_launch_signal(NULL, NULL);
679         aul_listen_app_dead_signal(NULL, NULL);
680 }
681
682 result
683 _AppLifecycleManager::AddListener(_IAppEventListener& listener)
684 {
685         if (__pEventList == null)
686         {
687                 std::unique_ptr< LinkedListT<_IAppEventListener*> > pAppEventList(new LinkedListT<_IAppEventListener*>);
688                 SysTryReturnResult(NID_APP, pAppEventList, E_SYSTEM, "Memory allocation failed.");
689
690                 Init();
691
692                 __pEventList = pAppEventList.release();
693                 SysLog(NID_APP, "Registered app event listener.");
694         }
695
696         return __pEventList->Add(&listener);
697 }
698
699 result
700 _AppLifecycleManager::RemoveListener(_IAppEventListener& listener)
701 {
702         SysTryReturnResult(NID_APP,__pEventList != null, E_OBJ_NOT_FOUND, "_IEventListener list is empty.");
703
704         result r = __pEventList->Remove(&listener);
705
706         if (__pEventList->GetCount() == 0)
707         {
708                 Fini();
709
710                 delete __pEventList;
711                 __pEventList = null;
712         }
713
714         return r;
715 }
716
717 int
718 _AppLifecycleManager::LaunchCallback(int pid, void* pData)
719 {
720         _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
721         if (pImpl == null || pImpl->__pEventList == null)
722         {
723                 SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
724                 return -1;
725         }
726
727         char appId[255];
728         int ret = aul_app_get_appid_bypid(pid, appId, sizeof(appId));
729         if (ret != AUL_R_OK)
730         {
731                 SysLogException(NID_APP, E_SYSTEM, "Cannot acquire app for %d.", pid);
732                 return -1;
733         }
734
735         std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
736         if (pEnum.get())
737         {
738                 const String tmp = appId;
739                 pImpl->__map.Add(pid, tmp);
740
741                 while (pEnum->MoveNext() == E_SUCCESS)
742                 {
743                         _IAppEventListener* pListener = null;
744                         pEnum->GetCurrent(pListener);
745
746                         pListener->OnApplicationLaunched(tmp, pid);
747                 }
748         }
749
750         SysLog(NID_APP, "Finished invoking application event listener for %s, %d.", appId, pid);
751
752         return 0;
753 }
754
755 int
756 _AppLifecycleManager::TerminateCallback(int pid, void* pData)
757 {
758         _AppLifecycleManager* pImpl = static_cast<_AppLifecycleManager*>(pData);
759         if (pImpl == null || pImpl->__pEventList == null)
760         {
761                 SysLogException(NID_APP, E_SYSTEM, "Wrong _AppLifecycleImpl state.");
762                 return -1;
763         }
764
765         // terminate callback cannot acquire appId from pid
766         String tmp;
767         result r = pImpl->__map.GetValue(pid, tmp);
768         if (r != E_SUCCESS)
769         {
770                 SysLog(NID_APP, "Cannot acquire app from pid %d.", pid);
771                 return -1;
772         }
773
774         pImpl->__map.Remove(pid);
775
776         std::unique_ptr< IEnumeratorT<_IAppEventListener*> > pEnum(pImpl->__pEventList->GetEnumeratorN());
777         if (pEnum.get())
778         {
779                 while (pEnum->MoveNext() == E_SUCCESS)
780                 {
781                         _IAppEventListener* pListener = null;
782                         pEnum->GetCurrent(pListener);
783
784                         pListener->OnApplicationTerminated(tmp, pid);
785                 }
786         }
787
788         SysLog(NID_APP, "Finished invoking application event listener for %ls, %d.", tmp.GetPointer(), pid);
789
790         return 0;
791 }
792
793 ///////////////////////////////////////////////////////////////////////////////
794 // LifecycleManager ends.
795 ///////////////////////////////////////////////////////////////////////////////
796
797
798 result
799 _AppManagerImpl::AddAppEventListener(_IAppEventListener& listener)
800 {
801         return __lifeManager.AddListener(listener);
802 }
803
804 result
805 _AppManagerImpl::RemoveAppEventListener(_IAppEventListener& listener)
806 {
807         return __lifeManager.RemoveListener(listener);
808 }
809
810
811 _LibraryImpl&
812 _AppManagerImpl::GetUiLibraryImpl(void)
813 {
814         if (__pUiLibrary == null)
815         {
816                 __pUiLibrary = new (std::nothrow) _LibraryImpl;
817                 SysAssertf(__pUiLibrary != null, "_LibraryImpl allocation failure.");
818
819                 result r = __pUiLibrary->Construct(OSP_UI_SONAME);
820                 SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r));
821         }
822
823         return *__pUiLibrary;
824 }
825
826
827 result
828 _AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener)
829 {
830         return __pActiveWindowManager->AddActiveAppEventListener(listener);
831 }
832
833
834 result
835 _AppManagerImpl::RemoveActiveAppEventListener(IActiveAppEventListener& listener)
836 {
837         return __pActiveWindowManager->RemoveActiveAppEventListener(listener);
838 }
839
840
841 result
842 _AppManagerImpl::GetActiveApp(AppId& appId)
843 {
844         return __pActiveWindowManager->GetActiveApp(appId);
845 }
846
847
848 bool 
849 _AppManagerImpl::IsUserPreferredAppForAppControlResolution(const AppId& appId) const
850 {
851         _IAppManager* pMgr = _AppManagerProxy::GetService();
852         SysTryReturn(NID_APP, pMgr, false, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
853
854         return pMgr->IsUserPreferredAppForAppControlResolution(appId);
855 }
856
857 result 
858 _AppManagerImpl::ClearUserPreferenceForAppControlResolution(const AppId& appId)
859 {
860         _IAppManager* pMgr = _AppManagerProxy::GetService();
861         SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "Failed to _AppManagerProxy::GetService().");
862
863         return pMgr->ClearUserPreferenceForAppControlResolution(appId);
864 }
865
866 result
867 _AppManagerImpl::AddAppLifecycleEventListener(_IAppLifecycleEventListener& listener)
868 {
869         return __appLifecycleEvent.AddListener(listener, false);
870 }
871
872 result
873 _AppManagerImpl::RemoveAppLifecycleEventListener(_IAppLifecycleEventListener& listener)
874 {
875         return __appLifecycleEvent.RemoveListener(listener);
876 }
877
878 result
879 _AppManagerImpl::RegisterAppForAppLifecycleEvent(const AppId& appId)
880 {
881         SysLog(NID_APP, "Enter");
882
883         result res = __mutex.Acquire();
884         SysTryLog(NID_APP, res == E_SUCCESS, "Acquiring mutex failed.");
885
886         bool isContained = false;
887         result r = __appListForAppLifecycle.ContainsKey(appId, isContained);
888
889         int currentRefCnt = 0;
890         if(isContained)
891         {
892                 r = __appListForAppLifecycle.GetValue(appId, currentRefCnt);
893                 r = __appListForAppLifecycle.SetValue(appId, ++currentRefCnt);
894         }
895         else
896         {
897                 r = __appListForAppLifecycle.Add(appId, currentRefCnt);
898                 
899                 _IAppManager* pMgr = _AppManagerProxy::GetService();
900                 SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "_AppManagerProxy::GetService() is failed.");
901
902                 r = pMgr->RegisterAppForAppLifecycleEvent(appId, -1);
903                 SysLog(NID_APP, "The appId(%ls) is registered.", appId.GetPointer());
904         }
905         res = __mutex.Release();
906         SysTryLog(NID_APP, res == E_SUCCESS, "Releasing mutex failed.");
907         
908         SysLog(NID_APP, "Exit");
909
910         return r;
911 }
912
913 result
914 _AppManagerImpl::UnregisterAppForAppLifecycleEvent(const AppId& appId)
915 {
916         SysLog(NID_APP, "Enter");
917
918         result res = __mutex.Acquire();
919         SysTryLog(NID_APP, res == E_SUCCESS, "Acquiring mutex failed.");
920         
921         bool isContained = false;
922         result r = __appListForAppLifecycle.ContainsKey(appId, isContained);
923
924         if(isContained)
925         {
926                 int currentRefCnt = 0;
927                 r = __appListForAppLifecycle.GetValue(appId, currentRefCnt);
928
929                 currentRefCnt--;
930
931                 if (currentRefCnt < 0)
932                 {
933                         r = __appListForAppLifecycle.Remove(appId);
934
935                         _IAppManager* pMgr = _AppManagerProxy::GetService();
936                         SysTryReturnResult(NID_APP, pMgr, E_SYSTEM, "_AppManagerProxy::GetService() is failed.");
937
938                         r = pMgr->UnregisterAppForAppLifecycleEvent(appId, -1);
939                         
940                         SysLog(NID_APP, "The appId(%ls) is unregistered.", appId.GetPointer());
941                 }
942                 else
943                 {
944                         r = __appListForAppLifecycle.SetValue(appId, currentRefCnt);
945                 }
946         }
947         else
948         {
949                 SysLog(NID_APP, "The appId(%ls) is not registered.", appId.GetPointer());
950         }
951         
952         res = __mutex.Release();
953         SysTryLog(NID_APP, res == E_SUCCESS, "Releasing mutex failed.");
954         
955         SysLog(NID_APP, "Exit");
956
957         return r;
958
959 }
960
961 result
962 _AppManagerImpl::OnAppLifecycleEventReceived(int clientId,const AppId& appId, _AppLifecycleEventType appLifecycleEventType)
963 {
964         SysLog(NID_APP, "Enter appId(%ls), appLifecycleEventType(%d)", appId.GetPointer(), appLifecycleEventType);
965         
966         _AppLifecycleEventArg* pArg = new (std::nothrow)_AppLifecycleEventArg(appId, appLifecycleEventType);
967         SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
968         
969         __appLifecycleEvent.FireAsync(*pArg);
970         return E_SUCCESS;
971 }
972
973 }} // Tizen::App