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