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