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