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