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