Clean-up Multiple process for application control
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_manifest_file.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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  * @file    task_manifest_file.cpp
18  * @author  Pawel Sikorski (p.sikorski@samgsung.com)
19  * @version
20  * @brief
21  */
22
23 //SYSTEM INCLUDES
24 #include <unistd.h>
25 #include <string>
26 #include <dpl/assert.h>
27 #include <dirent.h>
28 #include <fstream>
29 #include <ail.h>
30
31 //WRT INCLUDES
32 #include <widget_install/task_manifest_file.h>
33 #include <widget_install/job_widget_install.h>
34 #include <widget_install/widget_install_errors.h>
35 #include <widget_install/widget_install_context.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
37 #include <dpl/log/log.h>
38 #include <dpl/file_input.h>
39 #include <dpl/errno_string.h>
40 #include <dpl/file_output.h>
41 #include <dpl/copy.h>
42 #include <dpl/exception.h>
43 #include <dpl/foreach.h>
44 #include <dpl/sstream.h>
45 #include <dpl/string.h>
46 #include <dpl/optional.h>
47 #include <dpl/utils/wrt_utility.h>
48 #include <map>
49 #include <libxml_utils.h>
50 #include <pkgmgr/pkgmgr_parser.h>
51 #include <dpl/localization/LanguageTagsProvider.h>
52
53 #define DEFAULT_ICON_NAME   "icon.png"
54
55 using namespace WrtDB;
56
57 namespace {
58 typedef std::map<DPL::String, DPL::String> LanguageTagMap;
59
60 const char* const ST_TRUE = "true";
61 const char* const ST_NODISPLAY = "nodisplay";
62
63 LanguageTagMap getLanguageTagMap()
64 {
65     LanguageTagMap map;
66
67 #define ADD(tag, l_tag) map.insert(std::make_pair(L###tag, L###l_tag));
68 #include "languages.def"
69 #undef ADD
70
71     return map;
72 }
73
74 DPL::OptionalString getLangTag(const DPL::String& tag)
75 {
76     static LanguageTagMap TagsMap =
77         getLanguageTagMap();
78
79     DPL::String langTag = tag;
80
81     LogDebug("Trying to map language tag: " << langTag);
82     size_t pos = langTag.find_first_of(L'_');
83     if (pos != DPL::String::npos) {
84         langTag.erase(pos);
85     }
86     DPL::OptionalString ret;
87
88     LanguageTagMap::iterator it = TagsMap.find(langTag);
89     if (it != TagsMap.end()) {
90         ret = it->second;
91     }
92     LogDebug("Mapping IANA Language tag to language tag: " <<
93              langTag << " -> " << ret);
94
95     return ret;
96 }
97 }
98
99 namespace Jobs {
100 namespace WidgetInstall {
101 const char * TaskManifestFile::encoding = "UTF-8";
102
103 TaskManifestFile::TaskManifestFile(InstallerContext &inCont) :
104     DPL::TaskDecl<TaskManifestFile>(this),
105     m_context(inCont),
106     writer(NULL)
107 {
108     if (m_context.isUpdateMode) {
109         // for widget update.
110         AddStep(&TaskManifestFile::stepBackupIconFiles);
111         AddStep(&TaskManifestFile::stepCopyIconFiles);
112         AddStep(&TaskManifestFile::stepGenerateManifest);
113         AddStep(&TaskManifestFile::stepParseUpgradedManifest);
114         AddStep(&TaskManifestFile::stepUpdateFinalize);
115
116         AddAbortStep(&TaskManifestFile::stepAbortIconFiles);
117     } else {
118         AddStep(&TaskManifestFile::stepCopyIconFiles);
119         AddStep(&TaskManifestFile::stepCreateExecFile);
120         AddStep(&TaskManifestFile::stepGenerateManifest);
121         AddStep(&TaskManifestFile::stepParseManifest);
122         AddStep(&TaskManifestFile::stepFinalize);
123
124         AddAbortStep(&TaskManifestFile::stepAbortParseManifest);
125     }
126 }
127
128 TaskManifestFile::~TaskManifestFile()
129 {}
130
131 void TaskManifestFile::stepCreateExecFile()
132 {
133     std::string exec = m_context.locations->getExecFile();
134     std::string clientExeStr = GlobalConfig::GetWrtClientExec();
135
136 #ifdef MULTIPROCESS_SERVICE_SUPPORT
137     //default widget
138     std::stringstream postfix;
139     postfix << AppControlPrefix::PROCESS_PREFIX << 0;
140     std::string controlExec = exec;
141     controlExec.append(postfix.str());
142
143     errno = 0;
144     if (symlink(clientExeStr.c_str(), controlExec.c_str()) != 0)
145     {
146         int error = errno;
147         if (error)
148             LogPedantic("Failed to make a symbolic name for a file "
149                     << "[" <<  DPL::GetErrnoString(error) << "]");
150         ThrowMsg(Exceptions::FileOperationFailed,
151                 "Symbolic link creating is not done.");
152     }
153
154     // app-control widgets
155     unsigned int indexMax = 0;
156     FOREACH(it, m_context.widgetConfig.configInfo.appControlList) {
157         if (it->m_index > indexMax) {
158             indexMax = it->m_index;
159         }
160     }
161
162     for (std::size_t i = 1; i <= indexMax; ++i) {
163         std::stringstream postfix;
164         postfix << AppControlPrefix::PROCESS_PREFIX << i;
165         std::string controlExec = exec;
166         controlExec.append(postfix.str());
167         errno = 0;
168         if (symlink(clientExeStr.c_str(), controlExec.c_str()) != 0) {
169             int error = errno;
170             if (error) {
171                 LogPedantic("Failed to make a symbolic name for a file "
172                     << "[" <<  DPL::GetErrnoString(error) << "]");
173             }
174             ThrowMsg(Exceptions::FileOperationFailed,
175                      "Symbolic link creating is not done.");
176         }
177     }
178 #else
179     //default widget
180     LogInfo("link -s " << clientExeStr << " " << exec);
181     errno = 0;
182     if (symlink(clientExeStr.c_str(), exec.c_str()) != 0)
183     {
184         int error = errno;
185         if (error)
186             LogPedantic("Failed to make a symbolic name for a file "
187                     << "[" <<  DPL::GetErrnoString(error) << "]");
188         ThrowMsg(Exceptions::FileOperationFailed,
189                 "Symbolic link creating is not done.");
190     }
191 #endif
192     m_context.job->UpdateProgress(
193             InstallerContext::INSTALL_CREATE_EXECFILE,
194             "Widget execfile creation Finished");
195 }
196
197 void TaskManifestFile::stepCopyIconFiles()
198 {
199     LogDebug("CopyIconFiles");
200
201     //This function copies icon to desktop icon path. For each locale avaliable
202     //which there is at least one icon in widget for, icon file is copied.
203     //Coping prioritize last positions when coping. If there is several icons
204     //with given locale, the one, that will be copied, will be icon
205     //which is declared by <icon> tag later than the others in config.xml of
206     // widget
207
208     std::vector<Locale> generatedLocales;
209
210     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
211         m_context.widgetConfig.localizationData.icons;
212
213     //reversed: last <icon> has highest priority to be copied if it has given
214     // locale (TODO: why was that working that way?)
215     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
216          icon = icons.rbegin();
217          icon != icons.rend();
218          ++icon)
219     {
220         FOREACH(locale, icon->availableLocales)
221         {
222             DPL::String src = icon->src;
223             LogDebug("Icon for locale: " << *locale << "is : " << src);
224
225             if (std::find(generatedLocales.begin(), generatedLocales.end(),
226                           *locale) != generatedLocales.end())
227             {
228                 LogDebug("Skipping - has that locale");
229                 continue;
230             } else {
231                 generatedLocales.push_back(*locale);
232             }
233
234             std::ostringstream sourceFile;
235             std::ostringstream targetFile;
236
237             sourceFile << m_context.locations->getSourceDir() << "/";
238
239             if (!locale->empty()) {
240                 sourceFile << "locales/" << *locale << "/";
241             }
242
243             sourceFile << src;
244
245             targetFile << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
246             targetFile << getIconTargetFilename(*locale);
247
248             if (m_context.widgetConfig.packagingType ==
249                 WrtDB::PKG_TYPE_HOSTED_WEB_APP)
250             {
251                 m_context.locations->setIconTargetFilenameForLocale(
252                     targetFile.str());
253             }
254
255             LogDebug("Copying icon: " << sourceFile.str() <<
256                      " -> " << targetFile.str());
257
258             icon_list.push_back(targetFile.str());
259
260             Try
261             {
262                 DPL::FileInput input(sourceFile.str());
263                 DPL::FileOutput output(targetFile.str());
264                 DPL::Copy(&input, &output);
265             }
266
267             Catch(DPL::FileInput::Exception::Base)
268             {
269                 // Error while opening or closing source file
270                 //ReThrowMsg(InstallerException::CopyIconFailed,
271                 // sourceFile.str());
272                 LogError(
273                     "Copying widget's icon failed. Widget's icon will not be" \
274                     "available from Main Screen");
275             }
276
277             Catch(DPL::FileOutput::Exception::Base)
278             {
279                 // Error while opening or closing target file
280                 //ReThrowMsg(InstallerException::CopyIconFailed,
281                 // targetFile.str());
282                 LogError(
283                     "Copying widget's icon failed. Widget's icon will not be" \
284                     "available from Main Screen");
285             }
286
287             Catch(DPL::CopyFailed)
288             {
289                 // Error while copying
290                 //ReThrowMsg(InstallerException::CopyIconFailed,
291                 // targetFile.str());
292                 LogError(
293                     "Copying widget's icon failed. Widget's icon will not be" \
294                     "available from Main Screen");
295             }
296         }
297     }
298
299     m_context.job->UpdateProgress(
300         InstallerContext::INSTALL_COPY_ICONFILE,
301         "Widget iconfile copy Finished");
302 }
303
304 void TaskManifestFile::stepBackupIconFiles()
305 {
306     LogDebug("Backup Icon Files");
307
308     backup_dir << m_context.locations->getPackageInstallationDir();
309     backup_dir << "/" << "backup" << "/";
310
311     backupIconFiles();
312
313     m_context.job->UpdateProgress(
314         InstallerContext::INSTALL_BACKUP_ICONFILE,
315         "New Widget icon file backup Finished");
316 }
317
318 void TaskManifestFile::stepAbortIconFiles()
319 {
320     LogDebug("Abrot Icon Files");
321     FOREACH(it, icon_list)
322     {
323         LogDebug("Remove Update Icon : " << (*it));
324         unlink((*it).c_str());
325     }
326
327     std::ostringstream b_icon_dir;
328     b_icon_dir << backup_dir.str() << "icons";
329
330     std::list<std::string> fileList;
331     getFileList(b_icon_dir.str().c_str(), fileList);
332
333     FOREACH(back_icon, fileList)
334     {
335         std::ostringstream res_file;
336         res_file << GlobalConfig::GetUserWidgetDesktopIconPath();
337         res_file << "/" << (*back_icon);
338
339         std::ostringstream backup_file;
340         backup_file << b_icon_dir.str() << "/" << (*back_icon);
341
342         Try
343         {
344             DPL::FileInput input(backup_file.str());
345             DPL::FileOutput output(res_file.str());
346             DPL::Copy(&input, &output);
347         }
348         Catch(DPL::FileInput::Exception::Base)
349         {
350             LogError("Restoration icon File Failed." << backup_file.str()
351                                                      << " to " << res_file.str());
352         }
353
354         Catch(DPL::FileOutput::Exception::Base)
355         {
356             LogError("Restoration icon File Failed." << backup_file.str()
357                                                      << " to " << res_file.str());
358         }
359         Catch(DPL::CopyFailed)
360         {
361             LogError("Restoration icon File Failed." << backup_file.str()
362                                                      << " to " << res_file.str());
363         }
364     }
365 }
366
367 void TaskManifestFile::stepUpdateFinalize()
368 {
369     commitManifest();
370     LogDebug("Finished Update Desktopfile");
371 }
372
373 DPL::String TaskManifestFile::getIconTargetFilename(
374     const DPL::String& languageTag) const
375 {
376     DPL::OStringStream filename;
377     TizenAppId appid = m_context.widgetConfig.tzAppid;
378
379     filename << DPL::ToUTF8String(appid).c_str();
380
381     if (!languageTag.empty()) {
382         DPL::OptionalString tag = getLangTag(languageTag); // translate en ->
383                                                            // en_US etc
384         if (tag.IsNull()) {
385             tag = languageTag;
386         }
387         DPL::String locale =
388             LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
389
390         if (locale.empty()) {
391             filename << L"." << languageTag;
392         } else {
393             filename << L"." << locale;
394         }
395     }
396
397     filename << L".png";
398     return filename.str();
399 }
400
401 void TaskManifestFile::stepFinalize()
402 {
403     commitManifest();
404     LogInfo("Finished ManifestFile step");
405 }
406
407 void TaskManifestFile::saveLocalizedKey(std::ofstream &file,
408                                         const DPL::String& key,
409                                         const DPL::String& languageTag)
410 {
411     DPL::String locale =
412         LanguageTagsProvider::BCP47LanguageTagToLocale(languageTag);
413
414     file << key;
415     if (!locale.empty()) {
416         file << "[" << locale << "]";
417     }
418     file << "=";
419 }
420
421 void TaskManifestFile::backupIconFiles()
422 {
423     LogInfo("Backup Icon Files");
424
425     std::ostringstream b_icon_dir;
426     b_icon_dir << backup_dir.str() << "icons";
427
428     LogDebug("Create icon backup folder : " << b_icon_dir.str());
429     WrtUtilMakeDir(b_icon_dir.str());
430
431     std::list<std::string> fileList;
432     getFileList(GlobalConfig::GetUserWidgetDesktopIconPath(), fileList);
433     std::string appid = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
434
435     FOREACH(it, fileList)
436     {
437         if (0 == (strncmp((*it).c_str(), appid.c_str(),
438                           strlen(appid.c_str()))))
439         {
440             std::ostringstream icon_file, backup_icon;
441             icon_file << GlobalConfig::GetUserWidgetDesktopIconPath();
442             icon_file << "/" << (*it);
443
444             backup_icon << b_icon_dir.str() << "/" << (*it);
445
446             LogDebug("Backup icon file " << icon_file.str() << " to " <<
447                      backup_icon.str());
448             Try
449             {
450                 DPL::FileInput input(icon_file.str());
451                 DPL::FileOutput output(backup_icon.str());
452                 DPL::Copy(&input, &output);
453             }
454             Catch(DPL::FileInput::Exception::Base)
455             {
456                 LogError("Backup Desktop File Failed.");
457                 ReThrowMsg(Exceptions::BackupFailed, icon_file.str());
458             }
459
460             Catch(DPL::FileOutput::Exception::Base)
461             {
462                 LogError("Backup Desktop File Failed.");
463                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
464             }
465             Catch(DPL::CopyFailed)
466             {
467                 LogError("Backup Desktop File Failed.");
468                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
469             }
470             unlink((*it).c_str());
471         }
472     }
473 }
474
475 void TaskManifestFile::getFileList(const char* path,
476                                    std::list<std::string> &list)
477 {
478     DIR* dir = opendir(path);
479     if (!dir) {
480         LogError("icon directory doesn't exist");
481         ThrowMsg(Exceptions::FileOperationFailed, path);
482     }
483
484     struct dirent entry;
485     struct dirent *result;
486     int return_code;
487     errno = 0;
488     for (return_code = readdir_r(dir, &entry, &result);
489             result != NULL && return_code == 0;
490             return_code = readdir_r(dir, &entry, &result))
491     {
492         if (strcmp(entry.d_name, ".") == 0 ||
493             strcmp(entry.d_name, "..") == 0)
494         {
495             continue;
496         }
497         std::string file_name = entry.d_name;
498         list.push_back(file_name);
499     }
500
501     if (return_code != 0 || errno != 0) {
502         LogError("readdir_r() failed with " << DPL::GetErrnoString());
503     }
504
505     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
506         LogError("Failed to close dir: " << path << " with error: "
507                                          << DPL::GetErrnoString());
508     }
509 }
510
511 void TaskManifestFile::stepGenerateManifest()
512 {
513     TizenPkgId pkgid = m_context.widgetConfig.tzPkgid;
514     manifest_name = pkgid + L".xml";
515     manifest_file += L"/tmp/" + manifest_name;
516
517     //libxml - init and check
518     LibxmlSingleton::Instance().init();
519
520     writeManifest(manifest_file);
521
522     m_context.job->UpdateProgress(
523         InstallerContext::INSTALL_CREATE_MANIFEST,
524         "Widget Manifest Creation Finished");
525 }
526
527 void TaskManifestFile::stepParseManifest()
528 {
529     int code = pkgmgr_parser_parse_manifest_for_installation(
530             DPL::ToUTF8String(manifest_file).c_str(), NULL);
531
532     if (code != 0) {
533         LogError("Manifest parser error: " << code);
534         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
535     }
536
537     m_context.job->UpdateProgress(
538         InstallerContext::INSTALL_CREATE_MANIFEST,
539         "Widget Manifest Parsing Finished");
540     LogDebug("Manifest parsed");
541 }
542
543 void TaskManifestFile::stepParseUpgradedManifest()
544 {
545     int code = pkgmgr_parser_parse_manifest_for_upgrade(
546             DPL::ToUTF8String(manifest_file).c_str(), NULL);
547
548     if (code != 0) {
549         LogError("Manifest parser error: " << code);
550         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
551     }
552
553     m_context.job->UpdateProgress(
554         InstallerContext::INSTALL_CREATE_MANIFEST,
555         "Widget Manifest Parsing Finished");
556     LogDebug("Manifest parsed");
557 }
558
559 void TaskManifestFile::commitManifest()
560 {
561     LogDebug("Commiting manifest file : " << manifest_file);
562
563     std::ostringstream destFile;
564     if (m_context.job->getInstallerStruct().m_installMode
565             == InstallMode::INSTALL_MODE_PRELOAD)
566     {
567         destFile << "/usr/share/packages" << "/"; //TODO constant with path
568     } else {
569         destFile << "/opt/share/packages" << "/"; //TODO constant with path
570     }
571     destFile << DPL::ToUTF8String(manifest_name);
572     LogInfo("cp " << manifest_file << " " << destFile.str());
573
574     DPL::FileInput input(DPL::ToUTF8String(manifest_file));
575     DPL::FileOutput output(destFile.str());
576     DPL::Copy(&input, &output);
577     LogDebug("Manifest writen to: " << destFile.str());
578
579     //removing temp file
580     unlink((DPL::ToUTF8String(manifest_file)).c_str());
581     manifest_file = DPL::FromUTF8String(destFile.str().c_str());
582 }
583
584 void TaskManifestFile::writeManifest(const DPL::String & path)
585 {
586     LogDebug("Generating manifest file : " << path);
587     Manifest manifest;
588     UiApplication uiApp;
589
590 #ifdef MULTIPROCESS_SERVICE_SUPPORT
591     //default widget content
592     std::stringstream postfix;
593     // index 0 is reserved
594     postfix << AppControlPrefix::PROCESS_PREFIX << 0;
595     setWidgetExecPath(uiApp, postfix.str());
596     setWidgetName(manifest, uiApp);
597     setWidgetIds(manifest, uiApp);
598     setWidgetIcons(uiApp);
599     setWidgetDescription(manifest);
600     setWidgetManifest(manifest);
601     setWidgetOtherInfo(uiApp);
602     setAppCategory(uiApp);
603     setLiveBoxInfo(manifest);
604     setAccount(manifest);
605     setPrivilege(manifest);
606     manifest.addUiApplication(uiApp);
607
608     //app-control content
609     ConfigParserData::AppControlInfoList appControlList =
610         m_context.widgetConfig.configInfo.appControlList;
611     FOREACH(it, appControlList) {
612         UiApplication uiApp;
613
614         uiApp.setTaskmanage(true);
615         uiApp.setNodisplay(true);
616 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
617         uiApp.setTaskmanage(ConfigParserData::AppControlInfo::Disposition::INLINE != it->m_disposition);
618         uiApp.setMultiple(ConfigParserData::AppControlInfo::Disposition::INLINE == it->m_disposition);
619 #endif
620         std::stringstream postfix;
621         postfix << AppControlPrefix::PROCESS_PREFIX << it->m_index;
622         setWidgetExecPath(uiApp, postfix.str());
623         setWidgetName(manifest, uiApp);
624         setWidgetIds(manifest, uiApp);
625         setWidgetIcons(uiApp);
626         setAppControlInfo(uiApp, *it);
627         setAppCategory(uiApp);
628         manifest.addUiApplication(uiApp);
629     }
630 #else
631     //default widget content
632     setWidgetExecPath(uiApp);
633     setWidgetName(manifest, uiApp);
634     setWidgetIds(manifest, uiApp);
635     setWidgetIcons(uiApp);
636     setWidgetManifest(manifest);
637     setWidgetOtherInfo(uiApp);
638     setAppControlsInfo(uiApp);
639     setAppCategory(uiApp);
640     setLiveBoxInfo(manifest);
641     setAccount(manifest);
642     setPrivilege(manifest);
643
644     manifest.addUiApplication(uiApp);
645 #endif
646
647     manifest.generate(path);
648     LogDebug("Manifest file serialized");
649 }
650
651 void TaskManifestFile::setWidgetExecPath(UiApplication & uiApp,
652                                          const std::string &postfix)
653 {
654     std::string exec = m_context.locations->getExecFile();
655     if (!postfix.empty()) {
656         exec.append(postfix);
657     }
658     LogDebug("exec = " << exec);
659     uiApp.setExec(DPL::FromASCIIString(exec));
660 }
661
662 void TaskManifestFile::setWidgetName(Manifest & manifest,
663                                      UiApplication & uiApp)
664 {
665     bool defaultNameSaved = false;
666
667     DPL::OptionalString defaultLocale =
668         m_context.widgetConfig.configInfo.defaultlocale;
669     std::pair<DPL::String,
670               WrtDB::ConfigParserData::LocalizedData> defaultLocalizedData;
671     //labels
672     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
673     {
674         Locale i = localizedData->first;
675         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
676         if (tag.IsNull()) {
677             tag = i;
678         }
679         DPL::OptionalString name = localizedData->second.name;
680         generateWidgetName(manifest, uiApp, tag, name, defaultNameSaved);
681
682         //store default locale localized data
683         if (!!defaultLocale && defaultLocale == i) {
684             defaultLocalizedData = *localizedData;
685         }
686     }
687
688     if (!!defaultLocale && !defaultNameSaved) {
689         DPL::OptionalString name = defaultLocalizedData.second.name;
690         generateWidgetName(manifest,
691                            uiApp,
692                            DPL::OptionalString::Null,
693                            name,
694                            defaultNameSaved);
695     }
696 }
697
698 void TaskManifestFile::setWidgetIds(Manifest & manifest,
699                                     UiApplication & uiApp,
700                                     const std::string &postfix)
701 {
702     //appid
703     TizenAppId appid = m_context.widgetConfig.tzAppid;
704     if (!postfix.empty()) {
705         appid = DPL::FromUTF8String(DPL::ToUTF8String(appid).append(postfix));
706     }
707     uiApp.setAppid(appid);
708
709     //extraid
710     if (!!m_context.widgetConfig.guid) {
711         uiApp.setExtraid(*m_context.widgetConfig.guid);
712     } else {
713         if (!appid.empty()) {
714             uiApp.setExtraid(DPL::String(L"http://") + appid);
715         }
716     }
717
718     //type
719     uiApp.setType(DPL::FromASCIIString("webapp"));
720     manifest.setType(L"wgt");
721 }
722
723 void TaskManifestFile::generateWidgetName(Manifest & manifest,
724                                           UiApplication &uiApp,
725                                           const DPL::OptionalString& tag,
726                                           DPL::OptionalString name,
727                                           bool & defaultNameSaved)
728 {
729     if (!!name) {
730         if (!!tag) {
731             DPL::String locale =
732                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
733
734             if (!locale.empty()) {
735                 uiApp.addLabel(LabelType(*name, *tag));
736             } else {
737                 uiApp.addLabel(LabelType(*name));
738                 manifest.addLabel(LabelType(*name));
739             }
740         } else {
741             defaultNameSaved = true;
742             uiApp.addLabel(LabelType(*name));
743             manifest.addLabel(LabelType(*name));
744         }
745     }
746 }
747
748 void TaskManifestFile::setWidgetIcons(UiApplication & uiApp)
749 {
750     //TODO this file will need to be updated when user locale preferences
751     //changes.
752     bool defaultIconSaved = false;
753
754     DPL::OptionalString defaultLocale =
755         m_context.widgetConfig.configInfo.defaultlocale;
756
757     std::vector<Locale> generatedLocales;
758     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
759         m_context.widgetConfig.localizationData.icons;
760
761     //reversed: last <icon> has highest priority to be writen to manifest if it
762     // has given locale (TODO: why was that working that way?)
763     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
764          icon = icons.rbegin();
765          icon != icons.rend();
766          ++icon)
767     {
768         FOREACH(locale, icon->availableLocales)
769         {
770             if (std::find(generatedLocales.begin(), generatedLocales.end(),
771                           *locale) != generatedLocales.end())
772             {
773                 LogDebug("Skipping - has that locale - already in manifest");
774                 continue;
775             } else {
776                 generatedLocales.push_back(*locale);
777             }
778
779             DPL::OptionalString tag = getLangTag(*locale); // translate en ->
780                                                            // en_US etc
781             if (tag.IsNull()) {
782                 tag = *locale;
783             }
784
785             generateWidgetIcon(uiApp, tag, *locale, defaultIconSaved);
786         }
787     }
788     if (!!defaultLocale && !defaultIconSaved) {
789         generateWidgetIcon(uiApp, DPL::OptionalString::Null,
790                            DPL::String(),
791                            defaultIconSaved);
792     }
793 }
794
795 void TaskManifestFile::generateWidgetIcon(UiApplication & uiApp,
796                                           const DPL::OptionalString& tag,
797                                           const DPL::String& language,
798                                           bool & defaultIconSaved)
799 {
800     DPL::String locale;
801     if (!!tag) {
802         locale = LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
803     } else {
804         defaultIconSaved = true;
805     }
806
807     DPL::String iconText;
808     iconText += getIconTargetFilename(language);
809
810     if (!locale.empty()) {
811         uiApp.addIcon(IconType(iconText, locale));
812     } else {
813         uiApp.addIcon(IconType(iconText));
814     }
815     std::ostringstream iconPath;
816     iconPath << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
817     iconPath << getIconTargetFilename(locale);
818      m_context.job->SendProgressIconPath(iconPath.str());
819 }
820
821 void TaskManifestFile::setWidgetDescription(Manifest & manifest)
822 {
823     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
824     {
825         Locale i = localizedData->first;
826         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
827         if (tag.IsNull()) {
828             tag = i;
829         }
830         DPL::OptionalString description = localizedData->second.description;
831         generateWidgetDescription(manifest, tag, description);
832     }
833 }
834
835 void TaskManifestFile::generateWidgetDescription(Manifest & manifest,
836                                                  const DPL::OptionalString& tag,
837                                                   DPL::OptionalString description)
838 {
839     if (!!description) {
840         if (!!tag) {
841             DPL::String locale =
842                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
843             if (!locale.empty()) {
844                 manifest.addDescription(DescriptionType(*description, locale));
845             } else {
846                 manifest.addDescription(DescriptionType(*description));
847             }
848         } else {
849             manifest.addDescription(DescriptionType(*description));
850         }
851     }
852 }
853
854 void TaskManifestFile::setWidgetManifest(Manifest & manifest)
855 {
856     manifest.setPackage(m_context.widgetConfig.tzPkgid);
857
858     if (!!m_context.widgetConfig.version) {
859         manifest.setVersion(*m_context.widgetConfig.version);
860     }
861     DPL::String email = (!!m_context.widgetConfig.configInfo.authorEmail ?
862                          *m_context.widgetConfig.configInfo.authorEmail : L"");
863     DPL::String href = (!!m_context.widgetConfig.configInfo.authorHref ?
864                         *m_context.widgetConfig.configInfo.authorHref : L"");
865     DPL::String name = (!!m_context.widgetConfig.configInfo.authorName ?
866                         *m_context.widgetConfig.configInfo.authorName : L"");
867     manifest.addAuthor(Author(email, href, L"", name));
868 }
869
870 void TaskManifestFile::setWidgetOtherInfo(UiApplication & uiApp)
871 {
872     FOREACH(it, m_context.widgetConfig.configInfo.settingsList)
873     {
874         if (!strcmp(DPL::ToUTF8String(it->m_name).c_str(), ST_NODISPLAY)) {
875             if (!strcmp(DPL::ToUTF8String(it->m_value).c_str(), ST_TRUE)) {
876                 uiApp.setNodisplay(true);
877                 uiApp.setTaskmanage(false);
878             } else {
879                 uiApp.setNodisplay(false);
880                 uiApp.setTaskmanage(true);
881             }
882         }
883     }
884     //TODO
885     //There is no "X-TIZEN-PackageType=wgt"
886     //There is no X-TIZEN-PackageID in manifest "X-TIZEN-PackageID=" <<
887     // DPL::ToUTF8String(*widgetID).c_str()
888     //There is no Comment in pkgmgr "Comment=Widget application"
889     //that were in desktop file
890 }
891
892 void TaskManifestFile::setAppControlsInfo(UiApplication & uiApp)
893 {
894     WrtDB::ConfigParserData::AppControlInfoList appControlList =
895         m_context.widgetConfig.configInfo.appControlList;
896
897     if (appControlList.empty()) {
898         LogInfo("Widget doesn't contain app control");
899         return;
900     }
901
902      // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
903     FOREACH(it, appControlList) {
904         setAppControlInfo(uiApp, *it);
905     }
906 }
907
908 void TaskManifestFile::setAppControlInfo(UiApplication & uiApp,
909                                          const WrtDB::ConfigParserData::AppControlInfo & service)
910 {
911     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
912     AppControl appControl;
913     if (!service.m_operation.empty()) {
914         appControl.addOperation(service.m_operation); //TODO: encapsulation?
915     }
916     if (!service.m_uriList.empty()) {
917         FOREACH(uri, service.m_uriList) {
918             appControl.addUri(*uri);
919         }
920     }
921     if (!service.m_mimeList.empty()) {
922         FOREACH(mime, service.m_mimeList) {
923             appControl.addMime(*mime);
924         }
925     }
926     uiApp.addAppControl(appControl);
927 }
928
929 void TaskManifestFile::setAppCategory(UiApplication &uiApp)
930 {
931     WrtDB::ConfigParserData::CategoryList categoryList =
932         m_context.widgetConfig.configInfo.categoryList;
933
934     if (categoryList.empty()) {
935         LogInfo("Widget doesn't contain application category");
936         return;
937     }
938     FOREACH(it, categoryList) {
939         if (!(*it).empty()) {
940             uiApp.addAppCategory(*it);
941         }
942     }
943 }
944
945 void TaskManifestFile::stepAbortParseManifest()
946 {
947     LogError("[Parse Manifest] Abroting....");
948
949     int code = pkgmgr_parser_parse_manifest_for_uninstallation(
950             DPL::ToUTF8String(manifest_file).c_str(), NULL);
951
952     if (0 != code) {
953         LogWarning("Manifest parser error: " << code);
954         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
955     }
956     int ret = unlink(DPL::ToUTF8String(manifest_file).c_str());
957     if (0 != ret) {
958         LogWarning("No manifest file found: " << manifest_file);
959     }
960 }
961
962 void TaskManifestFile::setLiveBoxInfo(Manifest& manifest)
963 {
964     FOREACH(it, m_context.widgetConfig.configInfo.m_livebox) {
965         LogInfo("setLiveBoxInfo");
966         LiveBoxInfo liveBox;
967         DPL::Optional<WrtDB::ConfigParserData::LiveboxInfo> ConfigInfo = *it;
968         DPL::String appid = m_context.widgetConfig.tzAppid;
969
970         if (ConfigInfo->m_liveboxId != L"") {
971             size_t found = ConfigInfo->m_liveboxId.find_last_of(L".");
972             if (found != std::string::npos) {
973                 if (0 == ConfigInfo->m_liveboxId.compare(0, found, appid)) {
974                     liveBox.setLiveboxId(ConfigInfo->m_liveboxId);
975                 } else {
976                     DPL::String liveboxId =
977                         appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
978                     liveBox.setLiveboxId(liveboxId);
979                 }
980             } else {
981                 DPL::String liveboxId =
982                     appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
983                 liveBox.setLiveboxId(liveboxId);
984             }
985         }
986
987         if (ConfigInfo->m_primary != L"") {
988             liveBox.setPrimary(ConfigInfo->m_primary);
989         }
990
991         if (ConfigInfo->m_updatePeriod != L"") {
992             liveBox.setUpdatePeriod(ConfigInfo->m_updatePeriod);
993         }
994
995         if (ConfigInfo->m_label != L"") {
996             liveBox.setLabel(ConfigInfo->m_label);
997         }
998
999         DPL::String defaultLocale
1000             = DPL::FromUTF8String(
1001                     m_context.locations->getPackageInstallationDir())
1002                 + DPL::String(L"/res/wgt/");
1003
1004         if (ConfigInfo->m_icon != L"") {
1005             liveBox.setIcon(defaultLocale + ConfigInfo->m_icon);
1006         }
1007
1008         if (ConfigInfo->m_boxInfo.m_boxSrc.empty() ||
1009             ConfigInfo->m_boxInfo.m_boxSize.empty())
1010         {
1011             LogInfo("Widget doesn't contain box");
1012             return;
1013         } else {
1014             BoxInfoType box;
1015             if (!ConfigInfo->m_boxInfo.m_boxSrc.empty()) {
1016                 if ((0 == ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 4, L"http"))
1017                     || (0 ==
1018                         ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 5, L"https")))
1019                 {
1020                     box.boxSrc = ConfigInfo->m_boxInfo.m_boxSrc;
1021                 } else {
1022                     box.boxSrc = defaultLocale + ConfigInfo->m_boxInfo.m_boxSrc;
1023                 }
1024             }
1025
1026             if (ConfigInfo->m_boxInfo.m_boxMouseEvent == L"true") {
1027                 box.boxMouseEvent = ConfigInfo->m_boxInfo.m_boxMouseEvent;
1028             } else {
1029                 box.boxMouseEvent = L"false";
1030             }
1031
1032             if (ConfigInfo->m_boxInfo.m_boxTouchEffect == L"true") {
1033                 box.boxTouchEffect = ConfigInfo->m_boxInfo.m_boxTouchEffect;
1034             } else {
1035                 box.boxTouchEffect= L"false";
1036             }
1037
1038             std::list<std::pair<DPL::String, DPL::String> > BoxSizeList
1039                 = ConfigInfo->m_boxInfo.m_boxSize;
1040             FOREACH(im, BoxSizeList) {
1041                 std::pair<DPL::String, DPL::String> boxSize = *im;
1042                 if (!boxSize.second.empty()) {
1043                     boxSize.second = defaultLocale + boxSize.second;
1044                 }
1045                 box.boxSize.push_back(boxSize);
1046             }
1047
1048             if (!ConfigInfo->m_boxInfo.m_pdSrc.empty()
1049                 && !ConfigInfo->m_boxInfo.m_pdWidth.empty()
1050                 && !ConfigInfo->m_boxInfo.m_pdHeight.empty())
1051             {
1052                 if ((0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 4, L"http"))
1053                     || (0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 5, L"https")))
1054                 {
1055                     box.pdSrc = ConfigInfo->m_boxInfo.m_pdSrc;
1056                 } else {
1057                     box.pdSrc = defaultLocale + ConfigInfo->m_boxInfo.m_pdSrc;
1058                 }
1059                 box.pdWidth = ConfigInfo->m_boxInfo.m_pdWidth;
1060                 box.pdHeight = ConfigInfo->m_boxInfo.m_pdHeight;
1061             }
1062             liveBox.setBox(box);
1063         }
1064         manifest.addLivebox(liveBox);
1065     }
1066 }
1067
1068 void TaskManifestFile::setAccount(Manifest& manifest)
1069 {
1070     WrtDB::ConfigParserData::AccountProvider account =
1071         m_context.widgetConfig.configInfo.accountProvider;
1072
1073     AccountProviderType provider;
1074
1075     if (account.m_iconSet.empty()) {
1076         LogInfo("Widget doesn't contain Account");
1077         return;
1078     }
1079     if (account.m_multiAccountSupport) {
1080         provider.multiAccount = L"ture";
1081     } else {
1082         provider.multiAccount = L"false";
1083     }
1084     provider.appid = m_context.widgetConfig.tzAppid;
1085
1086     FOREACH(it, account.m_iconSet) {
1087         std::pair<DPL::String, DPL::String> icon;
1088
1089         if (it->first == ConfigParserData::IconSectionType::DefaultIcon) {
1090             icon.first = L"account";
1091         } else if (it->first == ConfigParserData::IconSectionType::SmallIcon) {
1092             icon.first = L"account-small";
1093         }
1094         icon.second = it->second;
1095
1096         provider.icon.push_back(icon);
1097     }
1098
1099     FOREACH(it, account.m_displayNameSet) {
1100         provider.name.push_back(LabelType(it->second, it->first));
1101     }
1102
1103     FOREACH(it, account.m_capabilityList) {
1104         provider.capability.push_back(*it);
1105     }
1106
1107     Account accountInfo;
1108     accountInfo.addAccountProvider(provider);
1109     manifest.addAccount(accountInfo);
1110 }
1111
1112 void TaskManifestFile::setPrivilege(Manifest& manifest)
1113 {
1114     WrtDB::ConfigParserData::PrivilegeList privileges =
1115         m_context.widgetConfig.configInfo.privilegeList;
1116
1117     PrivilegeType privilege;
1118
1119     FOREACH(it, privileges)
1120     {
1121         privilege.addPrivilegeName(it->name);
1122     }
1123
1124     manifest.addPrivileges(privilege);
1125 }
1126
1127 } //namespace WidgetInstall
1128 } //namespace Jobs