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