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