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