Add description element to manifest.xml
[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::stepGenerateManifest);
115         AddStep(&TaskManifestFile::stepParseUpgradedManifest);
116         AddStep(&TaskManifestFile::stepUpdateFinalize);
117
118         AddAbortStep(&TaskManifestFile::stepAbortIconFiles);
119     } else {
120         AddStep(&TaskManifestFile::stepCopyIconFiles);
121         AddStep(&TaskManifestFile::stepCreateExecFile);
122         AddStep(&TaskManifestFile::stepGenerateManifest);
123         AddStep(&TaskManifestFile::stepParseManifest);
124         AddStep(&TaskManifestFile::stepFinalize);
125
126         AddAbortStep(&TaskManifestFile::stepAbortParseManifest);
127     }
128 }
129
130 TaskManifestFile::~TaskManifestFile()
131 {}
132
133 void TaskManifestFile::stepCreateExecFile()
134 {
135     std::string exec = m_context.locations->getExecFile();
136     std::string clientExeStr = GlobalConfig::GetWrtClientExec();
137
138 #ifdef MULTIPROCESS_SERVICE_SUPPORT
139     //default widget
140     std::stringstream postfix;
141     postfix << AppControlPrefix::PROCESS_PREFIX << 0;
142     std::string controlExec = exec;
143     controlExec.append(postfix.str());
144
145     errno = 0;
146     if (symlink(clientExeStr.c_str(), controlExec.c_str()) != 0)
147     {
148         int error = errno;
149         if (error)
150             LogPedantic("Failed to make a symbolic name for a file "
151                     << "[" <<  DPL::GetErrnoString(error) << "]");
152         ThrowMsg(Exceptions::FileOperationFailed,
153                 "Symbolic link creating is not done.");
154     }
155
156     // app-control widgets
157     unsigned int indexMax = 0;
158     FOREACH(it, m_context.widgetConfig.configInfo.appControlList) {
159         if (it->m_index > indexMax) {
160             indexMax = it->m_index;
161         }
162     }
163
164     for (std::size_t i = 1; i <= indexMax; ++i) {
165         std::stringstream postfix;
166         postfix << AppControlPrefix::PROCESS_PREFIX << i;
167         std::string controlExec = exec;
168         controlExec.append(postfix.str());
169         errno = 0;
170         if (symlink(clientExeStr.c_str(), controlExec.c_str()) != 0) {
171             int error = errno;
172             if (error) {
173                 LogPedantic("Failed to make a symbolic name for a file "
174                     << "[" <<  DPL::GetErrnoString(error) << "]");
175             }
176             ThrowMsg(Exceptions::FileOperationFailed,
177                      "Symbolic link creating is not done.");
178         }
179     }
180 #else
181     //default widget
182     LogInfo("link -s " << clientExeStr << " " << exec);
183     errno = 0;
184     if (symlink(clientExeStr.c_str(), exec.c_str()) != 0)
185     {
186         int error = errno;
187         if (error)
188             LogPedantic("Failed to make a symbolic name for a file "
189                     << "[" <<  DPL::GetErrnoString(error) << "]");
190         ThrowMsg(Exceptions::FileOperationFailed,
191                 "Symbolic link creating is not done.");
192     }
193 #endif
194     m_context.job->UpdateProgress(
195             InstallerContext::INSTALL_CREATE_EXECFILE,
196             "Widget execfile creation Finished");
197 }
198
199 void TaskManifestFile::stepCopyIconFiles()
200 {
201     LogDebug("CopyIconFiles");
202
203     //This function copies icon to desktop icon path. For each locale avaliable
204     //which there is at least one icon in widget for, icon file is copied.
205     //Coping prioritize last positions when coping. If there is several icons
206     //with given locale, the one, that will be copied, will be icon
207     //which is declared by <icon> tag later than the others in config.xml of
208     // widget
209
210     std::vector<Locale> generatedLocales;
211
212     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
213         m_context.widgetConfig.localizationData.icons;
214
215     //reversed: last <icon> has highest priority to be copied if it has given
216     // locale (TODO: why was that working that way?)
217     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
218          icon = icons.rbegin();
219          icon != icons.rend();
220          ++icon)
221     {
222         FOREACH(locale, icon->availableLocales)
223         {
224             DPL::String src = icon->src;
225             LogDebug("Icon for locale: " << *locale << "is : " << src);
226
227             if (std::find(generatedLocales.begin(), generatedLocales.end(),
228                           *locale) != generatedLocales.end())
229             {
230                 LogDebug("Skipping - has that locale");
231                 continue;
232             } else {
233                 generatedLocales.push_back(*locale);
234             }
235
236             std::ostringstream sourceFile;
237             std::ostringstream targetFile;
238
239             sourceFile << m_context.locations->getSourceDir() << "/";
240
241             if (!locale->empty()) {
242                 sourceFile << "locales/" << *locale << "/";
243             }
244
245             sourceFile << src;
246
247             targetFile << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
248             targetFile << getIconTargetFilename(*locale);
249
250             if (m_context.widgetConfig.packagingType ==
251                 WrtDB::PKG_TYPE_HOSTED_WEB_APP)
252             {
253                 m_context.locations->setIconTargetFilenameForLocale(
254                     targetFile.str());
255             }
256
257             LogDebug("Copying icon: " << sourceFile.str() <<
258                      " -> " << targetFile.str());
259
260             icon_list.push_back(targetFile.str());
261
262             Try
263             {
264                 DPL::FileInput input(sourceFile.str());
265                 DPL::FileOutput output(targetFile.str());
266                 DPL::Copy(&input, &output);
267             }
268
269             Catch(DPL::FileInput::Exception::Base)
270             {
271                 // Error while opening or closing source file
272                 //ReThrowMsg(InstallerException::CopyIconFailed,
273                 // sourceFile.str());
274                 LogError(
275                     "Copying widget's icon failed. Widget's icon will not be" \
276                     "available from Main Screen");
277             }
278
279             Catch(DPL::FileOutput::Exception::Base)
280             {
281                 // Error while opening or closing target file
282                 //ReThrowMsg(InstallerException::CopyIconFailed,
283                 // targetFile.str());
284                 LogError(
285                     "Copying widget's icon failed. Widget's icon will not be" \
286                     "available from Main Screen");
287             }
288
289             Catch(DPL::CopyFailed)
290             {
291                 // Error while copying
292                 //ReThrowMsg(InstallerException::CopyIconFailed,
293                 // targetFile.str());
294                 LogError(
295                     "Copying widget's icon failed. Widget's icon will not be" \
296                     "available from Main Screen");
297             }
298         }
299     }
300
301     m_context.job->UpdateProgress(
302         InstallerContext::INSTALL_COPY_ICONFILE,
303         "Widget iconfile copy Finished");
304 }
305
306 void TaskManifestFile::stepBackupIconFiles()
307 {
308     LogDebug("Backup Icon Files");
309
310     backup_dir << m_context.locations->getPackageInstallationDir();
311     backup_dir << "/" << "backup" << "/";
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     int code = pkgmgr_parser_parse_manifest_for_upgrade(
548             DPL::ToUTF8String(manifest_file).c_str(), NULL);
549
550     if (code != 0) {
551         LogError("Manifest parser error: " << code);
552         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
553     }
554
555     m_context.job->UpdateProgress(
556         InstallerContext::INSTALL_CREATE_MANIFEST,
557         "Widget Manifest Parsing Finished");
558     LogDebug("Manifest parsed");
559 }
560
561 void TaskManifestFile::commitManifest()
562 {
563     LogDebug("Commiting manifest file : " << manifest_file);
564
565     std::ostringstream destFile;
566     if (m_context.job->getInstallerStruct().m_installMode
567             == InstallMode::INSTALL_MODE_PRELOAD)
568     {
569         destFile << "/usr/share/packages" << "/"; //TODO constant with path
570     } else {
571         destFile << "/opt/share/packages" << "/"; //TODO constant with path
572     }
573     destFile << DPL::ToUTF8String(manifest_name);
574     LogInfo("cp " << manifest_file << " " << destFile.str());
575
576     DPL::FileInput input(DPL::ToUTF8String(manifest_file));
577     DPL::FileOutput output(destFile.str());
578     DPL::Copy(&input, &output);
579     LogDebug("Manifest writen to: " << destFile.str());
580
581     //removing temp file
582     unlink((DPL::ToUTF8String(manifest_file)).c_str());
583     manifest_file = DPL::FromUTF8String(destFile.str().c_str());
584 }
585
586 void TaskManifestFile::writeManifest(const DPL::String & path)
587 {
588     LogDebug("Generating manifest file : " << path);
589     Manifest manifest;
590     UiApplication uiApp;
591
592 #ifdef MULTIPROCESS_SERVICE_SUPPORT
593     //default widget content
594     std::stringstream postfix;
595     // index 0 is reserved
596     postfix << AppControlPrefix::PROCESS_PREFIX << 0;
597     setWidgetExecPath(uiApp, postfix.str());
598     setWidgetName(manifest, uiApp);
599     setWidgetIds(manifest, uiApp);
600     setWidgetIcons(uiApp);
601     setWidgetDescription(manifest);
602     setWidgetManifest(manifest);
603     setWidgetOtherInfo(uiApp);
604     setAppCategory(uiApp);
605     setLiveBoxInfo(manifest);
606     setAccount(manifest);
607     setPrivilege(manifest);
608     manifest.addUiApplication(uiApp);
609
610     //app-control content
611     ConfigParserData::AppControlInfoList appControlList =
612         m_context.widgetConfig.configInfo.appControlList;
613     FOREACH(it, appControlList) {
614         UiApplication uiApp;
615
616         uiApp.setTaskmanage(true);
617         uiApp.setNodisplay(true);
618 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
619         uiApp.setTaskmanage(ConfigParserData::AppControlInfo::Disposition::INLINE != it->m_disposition);
620         uiApp.setMultiple(ConfigParserData::AppControlInfo::Disposition::INLINE == it->m_disposition);
621 #endif
622         std::stringstream postfix;
623         postfix << AppControlPrefix::PROCESS_PREFIX << it->m_index;
624         setWidgetExecPath(uiApp, postfix.str());
625         setWidgetName(manifest, uiApp);
626         setWidgetIds(manifest, uiApp);
627         setWidgetIcons(uiApp);
628         setAppControlInfo(uiApp, *it);
629         setAppCategory(uiApp);
630         manifest.addUiApplication(uiApp);
631     }
632 #else
633     //default widget content
634     setWidgetExecPath(uiApp);
635     setWidgetName(manifest, uiApp);
636     setWidgetIds(manifest, uiApp);
637     setWidgetIcons(uiApp);
638     setWidgetDescription(manifest);
639     setWidgetManifest(manifest);
640     setWidgetOtherInfo(uiApp);
641     setAppControlsInfo(uiApp);
642     setAppCategory(uiApp);
643     setLiveBoxInfo(manifest);
644     setAccount(manifest);
645     setPrivilege(manifest);
646
647     manifest.addUiApplication(uiApp);
648 #endif
649
650     manifest.generate(path);
651     LogDebug("Manifest file serialized");
652 }
653
654 void TaskManifestFile::setWidgetExecPath(UiApplication & uiApp,
655                                          const std::string &postfix)
656 {
657     std::string exec = m_context.locations->getExecFile();
658     if (!postfix.empty()) {
659         exec.append(postfix);
660     }
661     LogDebug("exec = " << exec);
662     uiApp.setExec(DPL::FromASCIIString(exec));
663 }
664
665 void TaskManifestFile::setWidgetName(Manifest & manifest,
666                                      UiApplication & uiApp)
667 {
668     bool defaultNameSaved = false;
669
670     DPL::OptionalString defaultLocale =
671         m_context.widgetConfig.configInfo.defaultlocale;
672     std::pair<DPL::String,
673               WrtDB::ConfigParserData::LocalizedData> defaultLocalizedData;
674     //labels
675     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
676     {
677         Locale i = localizedData->first;
678         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
679         if (tag.IsNull()) {
680             tag = i;
681         }
682         DPL::OptionalString name = localizedData->second.name;
683         generateWidgetName(manifest, uiApp, tag, name, defaultNameSaved);
684
685         //store default locale localized data
686         if (!!defaultLocale && defaultLocale == i) {
687             defaultLocalizedData = *localizedData;
688         }
689     }
690
691     if (!!defaultLocale && !defaultNameSaved) {
692         DPL::OptionalString name = defaultLocalizedData.second.name;
693         generateWidgetName(manifest,
694                            uiApp,
695                            DPL::OptionalString::Null,
696                            name,
697                            defaultNameSaved);
698     }
699 }
700
701 void TaskManifestFile::setWidgetIds(Manifest & manifest,
702                                     UiApplication & uiApp,
703                                     const std::string &postfix)
704 {
705     //appid
706     TizenAppId appid = m_context.widgetConfig.tzAppid;
707     if (!postfix.empty()) {
708         appid = DPL::FromUTF8String(DPL::ToUTF8String(appid).append(postfix));
709     }
710     uiApp.setAppid(appid);
711
712     //extraid
713     if (!!m_context.widgetConfig.guid) {
714         uiApp.setExtraid(*m_context.widgetConfig.guid);
715     } else {
716         if (!appid.empty()) {
717             uiApp.setExtraid(DPL::String(L"http://") + appid);
718         }
719     }
720
721     //type
722     uiApp.setType(DPL::FromASCIIString("webapp"));
723     manifest.setType(L"wgt");
724 }
725
726 void TaskManifestFile::generateWidgetName(Manifest & manifest,
727                                           UiApplication &uiApp,
728                                           const DPL::OptionalString& tag,
729                                           DPL::OptionalString name,
730                                           bool & defaultNameSaved)
731 {
732     if (!!name) {
733         if (!!tag) {
734             DPL::String locale =
735                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
736
737             if (!locale.empty()) {
738                 uiApp.addLabel(LabelType(*name, *tag));
739             } else {
740                 uiApp.addLabel(LabelType(*name));
741                 manifest.addLabel(LabelType(*name));
742             }
743         } else {
744             defaultNameSaved = true;
745             uiApp.addLabel(LabelType(*name));
746             manifest.addLabel(LabelType(*name));
747         }
748     }
749 }
750
751 void TaskManifestFile::setWidgetIcons(UiApplication & uiApp)
752 {
753     //TODO this file will need to be updated when user locale preferences
754     //changes.
755     bool defaultIconSaved = false;
756
757     DPL::OptionalString defaultLocale =
758         m_context.widgetConfig.configInfo.defaultlocale;
759
760     std::vector<Locale> generatedLocales;
761     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
762         m_context.widgetConfig.localizationData.icons;
763
764     //reversed: last <icon> has highest priority to be writen to manifest if it
765     // has given locale (TODO: why was that working that way?)
766     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
767          icon = icons.rbegin();
768          icon != icons.rend();
769          ++icon)
770     {
771         FOREACH(locale, icon->availableLocales)
772         {
773             if (std::find(generatedLocales.begin(), generatedLocales.end(),
774                           *locale) != generatedLocales.end())
775             {
776                 LogDebug("Skipping - has that locale - already in manifest");
777                 continue;
778             } else {
779                 generatedLocales.push_back(*locale);
780             }
781
782             DPL::OptionalString tag = getLangTag(*locale); // translate en ->
783                                                            // en_US etc
784             if (tag.IsNull()) {
785                 tag = *locale;
786             }
787
788             generateWidgetIcon(uiApp, tag, *locale, defaultIconSaved);
789         }
790     }
791     if (!!defaultLocale && !defaultIconSaved) {
792         generateWidgetIcon(uiApp, DPL::OptionalString::Null,
793                            DPL::String(),
794                            defaultIconSaved);
795     }
796 }
797
798 void TaskManifestFile::generateWidgetIcon(UiApplication & uiApp,
799                                           const DPL::OptionalString& tag,
800                                           const DPL::String& language,
801                                           bool & defaultIconSaved)
802 {
803     DPL::String locale;
804     if (!!tag) {
805         locale = LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
806     } else {
807         defaultIconSaved = true;
808     }
809
810     DPL::String iconText;
811     iconText += getIconTargetFilename(language);
812
813     if (!locale.empty()) {
814         uiApp.addIcon(IconType(iconText, locale));
815     } else {
816         uiApp.addIcon(IconType(iconText));
817     }
818     std::ostringstream iconPath;
819     iconPath << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
820     iconPath << getIconTargetFilename(locale);
821      m_context.job->SendProgressIconPath(iconPath.str());
822 }
823
824 void TaskManifestFile::setWidgetDescription(Manifest & manifest)
825 {
826     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
827     {
828         Locale i = localizedData->first;
829         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
830         if (tag.IsNull()) {
831             tag = i;
832         }
833         DPL::OptionalString description = localizedData->second.description;
834         generateWidgetDescription(manifest, tag, description);
835     }
836 }
837
838 void TaskManifestFile::generateWidgetDescription(Manifest & manifest,
839                                                  const DPL::OptionalString& tag,
840                                                   DPL::OptionalString description)
841 {
842     if (!!description) {
843         if (!!tag) {
844             DPL::String locale =
845                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
846             if (!locale.empty()) {
847                 manifest.addDescription(DescriptionType(*description, locale));
848             } else {
849                 manifest.addDescription(DescriptionType(*description));
850             }
851         } else {
852             manifest.addDescription(DescriptionType(*description));
853         }
854     }
855 }
856
857 void TaskManifestFile::setWidgetManifest(Manifest & manifest)
858 {
859     manifest.setPackage(m_context.widgetConfig.tzPkgid);
860
861     if (!!m_context.widgetConfig.version) {
862         manifest.setVersion(*m_context.widgetConfig.version);
863     }
864     DPL::String email = (!!m_context.widgetConfig.configInfo.authorEmail ?
865                          *m_context.widgetConfig.configInfo.authorEmail : L"");
866     DPL::String href = (!!m_context.widgetConfig.configInfo.authorHref ?
867                         *m_context.widgetConfig.configInfo.authorHref : L"");
868     DPL::String name = (!!m_context.widgetConfig.configInfo.authorName ?
869                         *m_context.widgetConfig.configInfo.authorName : L"");
870     manifest.addAuthor(Author(email, href, L"", name));
871 }
872
873 void TaskManifestFile::setWidgetOtherInfo(UiApplication & uiApp)
874 {
875     FOREACH(it, m_context.widgetConfig.configInfo.settingsList)
876     {
877         if (!strcmp(DPL::ToUTF8String(it->m_name).c_str(), ST_NODISPLAY)) {
878             if (!strcmp(DPL::ToUTF8String(it->m_value).c_str(), ST_TRUE)) {
879                 uiApp.setNodisplay(true);
880                 uiApp.setTaskmanage(false);
881             } else {
882                 uiApp.setNodisplay(false);
883                 uiApp.setTaskmanage(true);
884             }
885         }
886     }
887     //TODO
888     //There is no "X-TIZEN-PackageType=wgt"
889     //There is no X-TIZEN-PackageID in manifest "X-TIZEN-PackageID=" <<
890     // DPL::ToUTF8String(*widgetID).c_str()
891     //There is no Comment in pkgmgr "Comment=Widget application"
892     //that were in desktop file
893 }
894
895 void TaskManifestFile::setAppControlsInfo(UiApplication & uiApp)
896 {
897     WrtDB::ConfigParserData::AppControlInfoList appControlList =
898         m_context.widgetConfig.configInfo.appControlList;
899
900     if (appControlList.empty()) {
901         LogInfo("Widget doesn't contain app control");
902         return;
903     }
904
905      // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
906     FOREACH(it, appControlList) {
907         setAppControlInfo(uiApp, *it);
908     }
909 }
910
911 void TaskManifestFile::setAppControlInfo(UiApplication & uiApp,
912                                          const WrtDB::ConfigParserData::AppControlInfo & service)
913 {
914     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
915     AppControl appControl;
916     if (!service.m_operation.empty()) {
917         appControl.addOperation(service.m_operation); //TODO: encapsulation?
918     }
919     if (!service.m_uriList.empty()) {
920         FOREACH(uri, service.m_uriList) {
921             appControl.addUri(*uri);
922         }
923     }
924     if (!service.m_mimeList.empty()) {
925         FOREACH(mime, service.m_mimeList) {
926             appControl.addMime(*mime);
927         }
928     }
929     uiApp.addAppControl(appControl);
930 }
931
932 void TaskManifestFile::setAppCategory(UiApplication &uiApp)
933 {
934     WrtDB::ConfigParserData::CategoryList categoryList =
935         m_context.widgetConfig.configInfo.categoryList;
936
937     if (categoryList.empty()) {
938         LogInfo("Widget doesn't contain application category");
939         return;
940     }
941     FOREACH(it, categoryList) {
942         if (!(*it).empty()) {
943             uiApp.addAppCategory(*it);
944         }
945     }
946 }
947
948 void TaskManifestFile::stepAbortParseManifest()
949 {
950     LogError("[Parse Manifest] Abroting....");
951
952     int code = pkgmgr_parser_parse_manifest_for_uninstallation(
953             DPL::ToUTF8String(manifest_file).c_str(), NULL);
954
955     if (0 != code) {
956         LogWarning("Manifest parser error: " << code);
957         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
958     }
959     int ret = unlink(DPL::ToUTF8String(manifest_file).c_str());
960     if (0 != ret) {
961         LogWarning("No manifest file found: " << manifest_file);
962     }
963 }
964
965 void TaskManifestFile::setLiveBoxInfo(Manifest& manifest)
966 {
967     FOREACH(it, m_context.widgetConfig.configInfo.m_livebox) {
968         LogInfo("setLiveBoxInfo");
969         LiveBoxInfo liveBox;
970         DPL::Optional<WrtDB::ConfigParserData::LiveboxInfo> ConfigInfo = *it;
971         DPL::String appid = m_context.widgetConfig.tzAppid;
972
973         if (ConfigInfo->m_liveboxId != L"") {
974             size_t found = ConfigInfo->m_liveboxId.find_last_of(L".");
975             if (found != std::string::npos) {
976                 if (0 == ConfigInfo->m_liveboxId.compare(0, found, appid)) {
977                     liveBox.setLiveboxId(ConfigInfo->m_liveboxId);
978                 } else {
979                     DPL::String liveboxId =
980                         appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
981                     liveBox.setLiveboxId(liveboxId);
982                 }
983             } else {
984                 DPL::String liveboxId =
985                     appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
986                 liveBox.setLiveboxId(liveboxId);
987             }
988         }
989
990         if (ConfigInfo->m_primary != L"") {
991             liveBox.setPrimary(ConfigInfo->m_primary);
992         }
993
994         if (ConfigInfo->m_updatePeriod != L"") {
995             liveBox.setUpdatePeriod(ConfigInfo->m_updatePeriod);
996         }
997
998         if (ConfigInfo->m_label != L"") {
999             liveBox.setLabel(ConfigInfo->m_label);
1000         }
1001
1002         DPL::String defaultLocale
1003             = DPL::FromUTF8String(
1004                     m_context.locations->getPackageInstallationDir())
1005                 + DPL::String(L"/res/wgt/");
1006
1007         if (ConfigInfo->m_icon != L"") {
1008             liveBox.setIcon(defaultLocale + ConfigInfo->m_icon);
1009         }
1010
1011         if (ConfigInfo->m_boxInfo.m_boxSrc.empty() ||
1012             ConfigInfo->m_boxInfo.m_boxSize.empty())
1013         {
1014             LogInfo("Widget doesn't contain box");
1015             return;
1016         } else {
1017             BoxInfoType box;
1018             if (!ConfigInfo->m_boxInfo.m_boxSrc.empty()) {
1019                 if ((0 == ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 4, L"http"))
1020                     || (0 ==
1021                         ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 5, L"https")))
1022                 {
1023                     box.boxSrc = ConfigInfo->m_boxInfo.m_boxSrc;
1024                 } else {
1025                     box.boxSrc = defaultLocale + ConfigInfo->m_boxInfo.m_boxSrc;
1026                 }
1027             }
1028
1029             if (ConfigInfo->m_boxInfo.m_boxMouseEvent == L"true") {
1030                 std::string boxType;
1031                 if (ConfigInfo->m_type == L"") {
1032                     // in case of default livebox
1033                     boxType = web_provider_livebox_get_default_type();
1034                 } else {
1035                     boxType = DPL::ToUTF8String(ConfigInfo->m_type);
1036                 }
1037
1038                 int box_scrollable =
1039                     web_provider_plugin_get_box_scrollable(boxType.c_str());
1040
1041                 if (box_scrollable) {
1042                     box.boxMouseEvent = L"true";
1043                 } else {
1044                     box.boxMouseEvent = L"false";
1045                 }
1046             } else {
1047                 box.boxMouseEvent = L"false";
1048             }
1049
1050             if (ConfigInfo->m_boxInfo.m_boxTouchEffect == L"true") {
1051                 box.boxTouchEffect = L"true";
1052             } else {
1053                 box.boxTouchEffect= L"false";
1054             }
1055
1056             std::list<std::pair<DPL::String, DPL::String> > BoxSizeList
1057                 = ConfigInfo->m_boxInfo.m_boxSize;
1058             FOREACH(im, BoxSizeList) {
1059                 std::pair<DPL::String, DPL::String> boxSize = *im;
1060                 if (!boxSize.second.empty()) {
1061                     boxSize.second = defaultLocale + boxSize.second;
1062                 }
1063                 box.boxSize.push_back(boxSize);
1064             }
1065
1066             if (!ConfigInfo->m_boxInfo.m_pdSrc.empty()
1067                 && !ConfigInfo->m_boxInfo.m_pdWidth.empty()
1068                 && !ConfigInfo->m_boxInfo.m_pdHeight.empty())
1069             {
1070                 if ((0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 4, L"http"))
1071                     || (0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 5, L"https")))
1072                 {
1073                     box.pdSrc = ConfigInfo->m_boxInfo.m_pdSrc;
1074                 } else {
1075                     box.pdSrc = defaultLocale + ConfigInfo->m_boxInfo.m_pdSrc;
1076                 }
1077                 box.pdWidth = ConfigInfo->m_boxInfo.m_pdWidth;
1078                 box.pdHeight = ConfigInfo->m_boxInfo.m_pdHeight;
1079             }
1080             liveBox.setBox(box);
1081         }
1082         manifest.addLivebox(liveBox);
1083     }
1084 }
1085
1086 void TaskManifestFile::setAccount(Manifest& manifest)
1087 {
1088     WrtDB::ConfigParserData::AccountProvider account =
1089         m_context.widgetConfig.configInfo.accountProvider;
1090
1091     AccountProviderType provider;
1092
1093     if (account.m_iconSet.empty()) {
1094         LogInfo("Widget doesn't contain Account");
1095         return;
1096     }
1097     if (account.m_multiAccountSupport) {
1098         provider.multiAccount = L"ture";
1099     } else {
1100         provider.multiAccount = L"false";
1101     }
1102     provider.appid = m_context.widgetConfig.tzAppid;
1103
1104     FOREACH(it, account.m_iconSet) {
1105         std::pair<DPL::String, DPL::String> icon;
1106
1107         if (it->first == ConfigParserData::IconSectionType::DefaultIcon) {
1108             icon.first = L"account";
1109         } else if (it->first == ConfigParserData::IconSectionType::SmallIcon) {
1110             icon.first = L"account-small";
1111         }
1112         icon.second = it->second;
1113
1114         provider.icon.push_back(icon);
1115     }
1116
1117     FOREACH(it, account.m_displayNameSet) {
1118         provider.name.push_back(LabelType(it->second, it->first));
1119     }
1120
1121     FOREACH(it, account.m_capabilityList) {
1122         provider.capability.push_back(*it);
1123     }
1124
1125     Account accountInfo;
1126     accountInfo.addAccountProvider(provider);
1127     manifest.addAccount(accountInfo);
1128 }
1129
1130 void TaskManifestFile::setPrivilege(Manifest& manifest)
1131 {
1132     WrtDB::ConfigParserData::PrivilegeList privileges =
1133         m_context.widgetConfig.configInfo.privilegeList;
1134
1135     PrivilegeType privilege;
1136
1137     FOREACH(it, privileges)
1138     {
1139         privilege.addPrivilegeName(it->name);
1140     }
1141
1142     manifest.addPrivileges(privilege);
1143 }
1144
1145 } //namespace WidgetInstall
1146 } //namespace Jobs